Skip to content

The agent that grows with you

feat(ci): require desktop chat after bundle and install builds

ethernetbf75bc251662
diff --git a/.github/workflows/desktop-bundle-smoke.yml b/.github/workflows/desktop-bundle-smoke.yml
new file mode 100644
index 00000000000..36ee497d4b6
--- /dev/null
+++ b/.github/workflows/desktop-bundle-smoke.yml
@@ -0,0 +1,179 @@
+name: Desktop bundle smoke
+
+on:
+ workflow_call:
+ inputs:
+ platform:
+ required: true
+ type: string
+ arch:
+ required: true
+ type: string
+ format:
+ required: true
+ type: string
+ sha:
+ required: true
+ type: string
+ tag:
+ default: ''
+ type: string
+ commit-build:
+ default: false
+ type: boolean
+ public-base:
+ required: true
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ macos:
+ name: macOS install and chat
+ if: inputs.platform == 'darwin'
+ runs-on: ${{ inputs.arch == 'x64' && 'macos-15-intel' || 'macos-15' }}
+ timeout-minutes: 30
+ # Also constrains the recording action's nested cache to read-only.
+ cache-mode: read
+ env: &smoke-env
+ RELEASE_COMMIT: ${{ inputs.sha }}
+ RELEASE_TAG: ${{ inputs.tag }}
+ COMMIT_BUILD: ${{ inputs.commit-build }}
+ PUBLIC_BASE: ${{ inputs.public-base }}
+ PLATFORM: ${{ inputs.platform }}
+ ARCH: ${{ inputs.arch }}
+ FORMAT: ${{ inputs.format }}
+ steps: &smoke-steps
+ - name: Isolate smoke paths
+ shell: bash
+ run: printf 'SMOKE_ROOT=%s/bundle-smoke\n' "$RUNNER_TEMP" >> "$GITHUB_ENV"
+
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ inputs.sha }}
+ persist-credentials: false
+
+ - name: Set up driver tools only
+ id: tools
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+
+ - name: Install locked chat driver dependencies
+ id: dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
+
+ - name: Fetch one exact downloadable artifact
+ id: artifact
+ shell: bash
+ run: |
+ set -euo pipefail
+ mkdir -p "$SMOKE_ROOT/out"
+ case "$PLATFORM/$ARCH/$FORMAT" in
+ darwin/arm64/dmg|darwin/x64/dmg|darwin/arm64/zip|darwin/x64/zip)
+ name="darwin-$ARCH"; pattern="HermesBundled-*-mac-$ARCH.$FORMAT" ;;
+ win32/arm64/msix|win32/x64/msix)
+ name="win32-$ARCH"; pattern="HermesBundled-*-win-$ARCH.msix" ;;
+ win32/arm64/msixbundle|win32/x64/msixbundle)
+ name=windows-universal; pattern='HermesBundled-*-win.msixbundle' ;;
+ *) echo '::error::unsupported native smoke target'; exit 1 ;;
+ esac
+ args=(--tag "$RELEASE_TAG" --commit "$RELEASE_COMMIT")
+ if [ "$COMMIT_BUILD" = true ]; then
+ test -z "$RELEASE_TAG"
+ args=(--commit-build "$RELEASE_COMMIT")
+ fi
+ python -m scripts.releases.handoff fetch --public-base "$PUBLIC_BASE" "${args[@]}" \
+ --name "$name" --root "$SMOKE_ROOT/download" --include "$pattern" 2>&1 | tee "$SMOKE_ROOT/out/fetch.log"
+ python - "$name" "$pattern" <<'PY'
+ import fnmatch, json, os, sys
+ from pathlib import Path
+ from scripts.releases.r2 import file_sha256
+ root = Path(os.environ['SMOKE_ROOT'])
+ receipt = root / 'download' / f'handoff-{sys.argv[1]}.json'
+ data = json.loads(receipt.read_text(encoding='utf-8'))
+ selected = [row for row in data['files'] if fnmatch.fnmatchcase(row['path'], sys.argv[2])]
+ if len(selected) != 1:
+ raise ValueError(f'Expected exactly one non-Store artifact, found {len(selected)}')
+ row = selected[0]
+ artifact = root / 'download' / row['path']
+ if artifact.stat().st_size != row['size'] or file_sha256(artifact) != row['sha256']:
+ raise ValueError('Downloaded artifact no longer matches its receipt')
+ (root / 'out' / 'download.json').write_text(json.dumps({
+ 'commit': data['commit'], 'tag': data.get('tag'), 'receipt': receipt.name,
+ 'receiptSha256': file_sha256(receipt), 'artifact': row,
+ }, indent=2) + '\n', encoding='utf-8')
+ with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:
+ output.write(f'path={artifact.resolve().as_posix()}\n')
+ PY
+
+ - name: Start screen recording
+ id: recording
+ uses: ./.github/actions/e2e-screen-record
+ with:
+ mode: start
+ output: ${{ env.SMOKE_ROOT }}/out/recording.mkv
+
+ - name: Install and chat on macOS
+ id: macos-chat
+ if: runner.os == 'macOS'
+ shell: bash
+ env:
+ ARTIFACT: ${{ steps.artifact.outputs.path }}
+ run: |
+ args=()
+ if [ -n "$RELEASE_TAG" ]; then args+=(--tag "$RELEASE_TAG"); fi
+ bash tests/install/macos-bundle-smoke.sh --artifact "$ARTIFACT" --arch "$ARCH" \
+ --commit "$RELEASE_COMMIT" "${args[@]}" --work "$SMOKE_ROOT/work" --out "$SMOKE_ROOT/out"
+
+ - name: Install and chat on Windows
+ id: windows-chat
+ if: runner.os == 'Windows'
+ shell: powershell
+ env:
+ ARTIFACT: ${{ steps.artifact.outputs.path }}
+ run: |
+ $tagArgs = @()
+ if ($env:RELEASE_TAG) { $tagArgs = @('-Tag', $env:RELEASE_TAG) }
+ powershell -NoProfile -ExecutionPolicy Bypass -File tests/install/windows-bundle-smoke.ps1 -Artifact $env:ARTIFACT -Arch $env:ARCH -Commit $env:RELEASE_COMMIT @tagArgs -Work "$env:SMOKE_ROOT/work" -Out "$env:SMOKE_ROOT/out"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+
+ - name: Stop screen recording
+ if: always()
+ uses: ./.github/actions/e2e-screen-record
+ with:
+ mode: stop
+ output: ${{ env.SMOKE_ROOT }}/out/recording.mkv
+
+ - name: Record smoke step outcomes
+ if: always()
+ shell: bash
+ env:
+ STEP_RESULTS: ${{ toJSON(steps) }}
+ run: |
+ mkdir -p "$SMOKE_ROOT/out"
+ printf '%s\n' "$STEP_RESULTS" > "$SMOKE_ROOT/out/steps.json"
+
+ - name: Upload smoke diagnostics
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: desktop-smoke-${{ inputs.platform }}-${{ inputs.arch }}-${{ inputs.format }}-${{ github.run_id }}-${{ github.run_attempt }}
+ # Only evidence, never the isolated profile or installed application.
+ path: ${{ env.SMOKE_ROOT }}/out
+ if-no-files-found: warn
+ retention-days: 14
+
+ windows:
+ name: Windows install and chat
+ if: inputs.platform == 'win32'
+ runs-on: ${{ inputs.arch == 'arm64' && 'windows-11-arm' || 'windows-2025' }}
+ timeout-minutes: 30
+ cache-mode: read
+ env: *smoke-env
+ steps: *smoke-steps
\ No newline at end of file
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index e3cb5b5512b..f614957d608 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -14,9 +14,11 @@ name: Desktop Bundled Release
# build-darwin (darwin-arm64 + darwin-x64) → sign + notarize + stage
# dmg/zip/blockmap + per-arch feed inputs to the R2 tag archive
# build-linux → DISABLED for now (dummy skips)
-# publish-win32-updater → native universal bundles
-# (needs build-win32): canary also publishes its App Installer feed;
-# stable candidates stage sideload + Store bundles without touching feeds.
+# assemble-win32-bundle → native universal bundles
+# (needs build-win32): all downloadable builds stage without touching feeds.
+# smoke-darwin / smoke-win32 / smoke-win32-universal → native install + chat
+# publish-win32-updater → tested canary bytes + feed
+# (needs BOTH Windows smoke matrices); stable promotion stays separately gated.
# stable-store → verified Store submission
# (needs stable-publish): materialize the immutable accepted Store bundle
# and submit via the MSStore CLI without rebuilding.
@@ -740,13 +742,91 @@ jobs:
shell: bash
run: echo "::notice::linux bundled builds are disabled for now — re-enable in desktop-bundled-release.yml"
- # ── Windows updater channels (REAL — gated on build-win32 only) ──────────
- publish-win32-updater:
- name: Assemble Windows bundle and optionally publish canary feed
+ smoke-darwin:
+ name: Smoke macOS ${{ matrix.arch }} ${{ matrix.format }}
+ needs: [validate, build-darwin]
+ if: >-
+ !cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.build-darwin.result == 'success' && inputs.termux_only != true
+ && (inputs.release-phase == '' || inputs.release-phase == 'candidate')
+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: [arm64, x64]
+ format: [dmg, zip]
+ uses: ./.github/workflows/desktop-bundle-smoke.yml
+ with:
+ platform: darwin
+ arch: ${{ matrix.arch }}
+ format: ${{ matrix.format }}
+ sha: ${{ needs.validate.outputs.sha }}
+ tag: ${{ inputs.tag }}
+ commit-build: ${{ inputs.build_commit != '' }}
+ public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+
+ smoke-win32:
+ name: Smoke Windows ${{ matrix.arch }} MSIX
needs: [validate, build-win32]
- if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''
+ if: >-
+ !cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.build-win32.result == 'success' && inputs.termux_only != true
+ && (inputs.release-phase == '' || inputs.release-phase == 'candidate')
+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: [x64, arm64]
+ uses: ./.github/workflows/desktop-bundle-smoke.yml
+ with:
+ platform: win32
+ arch: ${{ matrix.arch }}
+ format: msix
+ sha: ${{ needs.validate.outputs.sha }}
+ tag: ${{ inputs.tag }}
+ commit-build: ${{ inputs.build_commit != '' }}
+ public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+
+ smoke-win32-universal:
+ name: Smoke Windows ${{ matrix.arch }} MSIXBUNDLE
+ needs: [validate, assemble-win32-bundle]
+ if: >-
+ !cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.assemble-win32-bundle.result == 'success' && inputs.termux_only != true
+ && (inputs.release-phase == '' || inputs.release-phase == 'candidate')
+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: [x64, arm64]
+ uses: ./.github/workflows/desktop-bundle-smoke.yml
+ with:
+ platform: win32
+ arch: ${{ matrix.arch }}
+ format: msixbundle
+ sha: ${{ needs.validate.outputs.sha }}
+ tag: ${{ inputs.tag }}
+ commit-build: ${{ inputs.build_commit != '' }}
+ public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+
+ # Assembly never writes a feed, including for canaries.
+ assemble-win32-bundle:
+ name: Assemble and stage the Windows universal bundle
+ needs: [validate, build-win32]
+ if: >-
+ !cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.build-win32.result == 'success' && inputs.termux_only != true
+ && (inputs.release-phase == '' || inputs.release-phase == 'candidate')
+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')
runs-on: windows-2025
environment: release-signing
+ cache-mode: read
timeout-minutes: 45
env:
HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
@@ -856,7 +936,7 @@ jobs:
( while sleep 240; do mint || true; done ) &
echo "AZURE_FEDERATED_TOKEN_FILE=$file" >> "$GITHUB_ENV"
- - name: Bundle + stage the MSIX feeds
+ - name: Assemble the signed MSIX bundle without publishing
shell: bash
env:
RELEASE_PHASE: ${{ inputs.release-phase }}
@@ -864,9 +944,8 @@ jobs:
AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
run: |
- # Candidate mode builds the bundles without writing a feed.
- # Canary mode publishes the App Installer bundle and pointer.
- # Commit mode assembles only the sideload product, without a feed.
+ # All modes stop at signed bytes. The separate handoff stages them
+ # for smoke; publication must not assemble or sign a second time.
if [ -n "$HERMES_BUILD_COMMIT" ]; then
node scripts/stage-msixbundle.mjs --commit "$HERMES_BUILD_COMMIT" --version "$HERMES_PAYLOAD_VERSION" --variant bundled --no-upload
exit 0
@@ -879,7 +958,6 @@ jobs:
fi
- name: Stage universal bundles to R2
- if: inputs.release-phase == 'candidate' || inputs.build_commit != ''
shell: bash
env:
RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
@@ -893,6 +971,74 @@ jobs:
--name windows-universal --root apps/desktop/release --include '*.msixbundle'
fi
+ publish-win32-updater:
+ name: Publish the tested Windows canary bundle
+ needs: [validate, assemble-win32-bundle, smoke-win32, smoke-win32-universal]
+ if: >-
+ !cancelled() && inputs.build_commit == '' && inputs.upload_release == true
+ && inputs.release-phase == '' && inputs.termux_only != true
+ && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.assemble-win32-bundle.result == 'success'
+ && needs.smoke-win32.result == 'success' && needs.smoke-win32-universal.result == 'success'
+ runs-on: ubuntu-24.04
+ environment: release-signing
+ timeout-minutes: 15
+ concurrency:
+ group: win32-updater-feed-canary
+ cancel-in-progress: false
+ env:
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ HERMES_DESKTOP_VARIANT: bundled
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ needs.validate.outputs.sha }}
+ - uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache-python: false
+ cache-node: false
+ - name: Retrieve the tested universal bundle
+ shell: bash
+ run: |
+ python -m scripts.releases.handoff fetch --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name windows-universal --root staged --include 'HermesBundled-*-win.msixbundle'
+ - name: Publish identical tested bytes without rebuilding
+ shell: bash
+ run: |
+ node --input-type=module -e '
+ import identity from "./apps/desktop/product-identity.cjs";
+ import { OUT_OF_STORE_PUBLISHER } from "./scripts/msix-shared.mjs";
+ console.log(JSON.stringify({identity: identity.msixAppIdWithOrg, publisher: OUT_OF_STORE_PUBLISHER}));
+ ' > staged/expected-identity.json
+ python - <<'PY'
+ import json, os, re
+ from pathlib import Path
+ from scripts.bundles.release_artifacts import main, single
+ expected = json.loads(Path('staged/expected-identity.json').read_text(encoding='utf-8'))
+ bundle = single(Path('staged').glob('HermesBundled-*-win.msixbundle'))
+ # The handoff binds the assembly filename and bytes. Never recompute
+ # its revision against stable tags that can change after native smoke.
+ match = re.fullmatch(r'HermesBundled-(\d+\.\d+\.\d+\.\d+)-win\.msixbundle', bundle.name)
+ if not match:
+ raise ValueError('Missing assembly version in receipt-bound bundle name')
+ version = match[1]
+ if (any(str(int(part)) != part or int(part) > 65535 for part in version.split('.'))
+ or version.rsplit('.', 1)[0] != os.environ['HERMES_PAYLOAD_TAG'].split('-')[0].removeprefix('v')):
+ raise ValueError('Assembly version differs from the release tag base')
+ # publish-appinstaller compares this version to the baked envelope.
+ main(['publish-appinstaller', '--root', 'staged', '--bundle', str(bundle),
+ '--tag', os.environ['HERMES_PAYLOAD_TAG'], '--variant', 'bundled',
+ '--identity', expected['identity'], '--publisher', expected['publisher'],
+ '--version', version])
+ PY
+
# ── macOS updater channel (REAL) ───────────────────────────────────────────
# Merges the per-arch feed ymls (arm64-stable-mac.yml / x64-stable-mac.yml
# …) into releases/darwin/<channel>/<channel>-mac.yml via
@@ -905,8 +1051,12 @@ jobs:
# publish in parallel by design (distinct feed files).
publish-darwin-updater:
name: Publish the macOS updater feed
- needs: [validate, build-darwin]
- if: inputs.build_commit == '' && inputs.upload_release == true && inputs.termux_only != true
+ needs: [validate, build-darwin, smoke-darwin]
+ if: >-
+ !cancelled() && inputs.build_commit == '' && inputs.upload_release == true
+ && inputs.release-phase == '' && inputs.termux_only != true
+ && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.build-darwin.result == 'success' && needs.smoke-darwin.result == 'success'
runs-on: ubuntu-24.04
environment: release-signing
timeout-minutes: 15
@@ -1336,7 +1486,7 @@ jobs:
builds-table:
name: Render the release builds table
- needs: [validate, build-win32, build-darwin, build-linux, publish-win32-updater, publish-darwin-updater, termux-deb]
+ needs: [validate, build-win32, build-darwin, build-linux, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, publish-win32-updater, publish-darwin-updater, termux-deb]
# Failed builds still get a per-tag diagnostic page. The renderer only
# advances the channel landing page when every prerequisite succeeded.
if: |
@@ -1380,7 +1530,7 @@ jobs:
commit-builds-summary:
name: Commit build summary (every binary, built or not)
- needs: [validate, build-win32, build-darwin, build-linux, publish-win32-updater, termux-deb]
+ needs: [validate, build-win32, build-darwin, build-linux, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, termux-deb]
if: |
always() && inputs.build_commit != ''
&& needs.validate.result == 'success' && needs.validate.outputs.sha != ''
@@ -1423,8 +1573,14 @@ jobs:
candidate-manifest:
name: Stage verified stable candidate artifacts
- needs: [validate, build-win32, build-darwin, publish-win32-updater, termux-deb]
- if: inputs.release-phase == 'candidate'
+ needs: [validate, build-win32, build-darwin, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, termux-deb]
+ if: >-
+ !cancelled() && inputs.release-phase == 'candidate'
+ && needs.validate.result == 'success' && needs.validate.outputs.sha != ''
+ && needs.build-win32.result == 'success' && needs.build-darwin.result == 'success'
+ && needs.assemble-win32-bundle.result == 'success' && needs.termux-deb.result == 'success'
+ && needs.smoke-darwin.result == 'success' && needs.smoke-win32.result == 'success'
+ && needs.smoke-win32-universal.result == 'success'
runs-on: ubuntu-latest-32-core
environment: release-signing
timeout-minutes: 90
@@ -1454,6 +1610,8 @@ jobs:
--name termux --name windows-universal --root candidates \
--include 'metadata-*.json' --include '*.msixbundle'
- id: manifest
+ env:
+ RELEASE_NEEDS: ${{ toJSON(needs) }}
run: python -m scripts.bundles.release_artifacts assemble --root candidates --out release-candidates.json
stable-publish:
@@ -1541,7 +1699,12 @@ jobs:
with:
cache-python: false
- run: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 -- -m scripts.bundles.release_artifacts promote --root verified
- - run: python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY"
+ - name: Render the admitted candidate smoke results
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
+ --candidate-manifest-sha256 "$CANDIDATE_MANIFEST_SHA256" --candidate-commit "$RELEASE_COMMIT"
stable-phase-result:
name: Stable bundle phase completed
@@ -1551,7 +1714,10 @@ jobs:
validate,
build-win32,
build-darwin,
- publish-win32-updater,
+ assemble-win32-bundle,
+ smoke-darwin,
+ smoke-win32,
+ smoke-win32-universal,
termux-deb,
candidate-manifest,
stable-publish,
@@ -1572,7 +1738,7 @@ jobs:
import json, os
from scripts.releases.stable import require_success
phases = {
- 'candidate': ['validate', 'build-win32', 'build-darwin', 'publish-win32-updater', 'termux-deb', 'candidate-manifest'],
+ 'candidate': ['validate', 'build-win32', 'build-darwin', 'assemble-win32-bundle', 'smoke-darwin', 'smoke-win32', 'smoke-win32-universal', 'termux-deb', 'candidate-manifest'],
'publish': ['validate', 'stable-publish', 'stable-store'],
'promote': ['validate', 'stable-promote'],
}
@@ -1581,7 +1747,7 @@ jobs:
publish-canary:
name: Publish the canary release
- needs: [build-win32, build-darwin, build-linux, builds-table, publish-win32-updater, publish-darwin-updater]
+ needs: [build-win32, build-darwin, build-linux, builds-table, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, publish-win32-updater, publish-darwin-updater]
if: |
always()
&& inputs.build_commit == ''
@@ -1591,6 +1757,10 @@ jobs:
&& needs.build-darwin.result == 'success'
&& needs.build-linux.result == 'success'
&& needs.builds-table.result == 'success'
+ && needs.assemble-win32-bundle.result == 'success'
+ && needs.smoke-darwin.result == 'success'
+ && needs.smoke-win32.result == 'success'
+ && needs.smoke-win32-universal.result == 'success'
&& needs.publish-win32-updater.result == 'success'
&& needs.publish-darwin-updater.result == 'success'
runs-on: ubuntu-24.04
diff --git a/.github/workflows/install-e2e-macos-run.yml b/.github/workflows/install-e2e-macos-run.yml
index 75c6d6526d2..b2f00caa4d9 100644
--- a/.github/workflows/install-e2e-macos-run.yml
+++ b/.github/workflows/install-e2e-macos-run.yml
@@ -108,6 +108,18 @@ jobs:
ref: ${{ github.sha }}
fetch-depth: 0
+ - name: Set up driver tools only
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+
+ - name: Install locked chat driver dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
+
- name: Start screen recording
uses: ./.github/actions/e2e-screen-record
with:
@@ -192,8 +204,17 @@ jobs:
with:
ref: ${{ github.sha }}
- - name: Install driver dependencies
- run: npm ci --ignore-scripts --no-audit --no-fund
+ - name: Set up driver tools only
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+
+ - name: Install locked chat driver dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
- name: Start screen recording
uses: ./.github/actions/e2e-screen-record
diff --git a/.github/workflows/install-e2e-run.yml b/.github/workflows/install-e2e-run.yml
index f61e0e9ec40..505b4be0e37 100644
--- a/.github/workflows/install-e2e-run.yml
+++ b/.github/workflows/install-e2e-run.yml
@@ -97,6 +97,19 @@ jobs:
ref: ${{ github.sha }}
fetch-depth: 0
+ # The checkout owns the chat driver, not OLD's installed Node/runtime.
+ - name: Set up driver tools only
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+
+ - name: Install locked chat driver dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
+
# One recording mechanism on every OS (Xvfb gives headless linux a
# display; the same display serves any app the driver launches).
- name: Start screen recording
diff --git a/.github/workflows/install-e2e-windows-run.yml b/.github/workflows/install-e2e-windows-run.yml
index 8139c2c4ee0..1f3c807e13e 100644
--- a/.github/workflows/install-e2e-windows-run.yml
+++ b/.github/workflows/install-e2e-windows-run.yml
@@ -101,11 +101,19 @@ jobs:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- - name: Install driver dependencies and verify helpers
+ - name: Set up driver tools only
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+ - name: Install locked chat driver dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
+ - name: Verify native helpers
shell: pwsh
run: |
- npm ci --ignore-scripts --no-audit --no-fund
- if ($LASTEXITCODE) { exit $LASTEXITCODE }
node --test tests/install/e2e-assets/windows-bundled-helpers.test.mjs
if ($LASTEXITCODE) { exit $LASTEXITCODE }
- name: Start recording
@@ -176,6 +184,18 @@ jobs:
ref: ${{ github.sha }}
fetch-depth: 0
+ - name: Set up driver tools only
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ cache: false
+ cache-python: false
+ cache-node: false
+
+ - name: Install locked chat driver dependencies
+ shell: bash
+ run: npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
+
# One recording mechanism on every OS: the composite action installs
# ffmpeg (cached - winget's download is the slow part), starts the
# capture, and record-stop fails on a zero-frame file so a silently
diff --git a/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts b/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
index 1ea609318b6..4eec09c46a7 100644
--- a/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
+++ b/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
@@ -1,16 +1,16 @@
import fs from 'node:fs'
import path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type MockBackendFixture,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
} from './fixtures'
-import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
import { expect, test } from './test'
diff --git a/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts b/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
index 8eac23c5a1f..0232837c72d 100644
--- a/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
+++ b/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
@@ -1,16 +1,16 @@
import fs from 'node:fs'
import path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type MockBackendFixture,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
} from './fixtures'
-import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
import { expect, test } from './test'
diff --git a/apps/desktop/e2e/bot-roster-user-sections.spec.ts b/apps/desktop/e2e/bot-roster-user-sections.spec.ts
index 7439777cce2..8492f4bddc3 100644
--- a/apps/desktop/e2e/bot-roster-user-sections.spec.ts
+++ b/apps/desktop/e2e/bot-roster-user-sections.spec.ts
@@ -1,16 +1,16 @@
import fs from 'node:fs'
import path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type MockBackendFixture,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
import { expect, test } from './test'
diff --git a/apps/desktop/e2e/chat.spec.ts b/apps/desktop/e2e/chat.spec.ts
index 13c2168d21d..b441309d4a1 100644
--- a/apps/desktop/e2e/chat.spec.ts
+++ b/apps/desktop/e2e/chat.spec.ts
@@ -8,10 +8,11 @@
* Prerequisite: `npm run build` must have been run so dist/ exists.
*/
-import { expect, test } from './test'
+import { runDesktopChatSmoke } from '../../../tests-js/scripts/desktop-chat-smoke'
+import { BLOCKING_CLARIFY_QUESTION, BLOCKING_CLARIFY_TRIGGER } from '../../../tests-js/scripts/mock-server'
import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { BLOCKING_CLARIFY_QUESTION, BLOCKING_CLARIFY_TRIGGER } from '../../../tests-js/scripts/mock-server'
+import { expect, test } from './test'
import { expectVisualSnapshot } from './visual-snapshot'
let fixture: MockBackendFixture | null = null
@@ -27,66 +28,20 @@ test.afterAll(async () => {
})
test.describe('chat interaction with mock backend', () => {
- test('send a message and receive a response', async () => {
- const page = fixture!.page
-
- // Find the composer — it's a contenteditable textbox.
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.waitFor({ state: 'visible', timeout: 10_000 })
-
- // Click to focus, then type the message character by character.
- // Using `type` instead of `fill` because the composer is a
- // contenteditable div with custom keydown handling that tracks
- // IME composition state — `fill` bypasses the event chain.
- await composer.click()
- await composer.type('Hello, can you hear me?', { delay: 20 })
-
- // Submit with Enter — the composer's keydown handler intercepts
- // plain Enter (without Shift) and calls submitDraft().
- await page.keyboard.press('Enter')
-
- // Wait for the user's message to appear in the transcript.
- // The message renders as an assistant-ui message in the chat view.
- await page.waitForFunction(
- () => {
- const body = document.body
-
- if (!body) {
- return false
- }
-
- return (body.textContent ?? '').includes('Hello, can you hear me?')
- },
- undefined,
- { timeout: 15_000 }
- )
-
- // Wait for the mock response to appear. The canned reply is:
- // "Hello from the mock inference server! The full boot chain is working."
- // Give it a generous timeout — the inference request goes through the
- // gateway → hermes serve → mock server → streaming SSE back.
- await page.waitForFunction(
- () => {
- const body = document.body
-
- if (!body) {
- return false
- }
-
- const text = body.textContent ?? ''
-
- return text.includes('mock inference server') || text.includes('boot chain is working')
- },
- undefined,
- { timeout: 60_000 }
- )
+ test('send a message and receive a response', async (): Promise<void> => {
+ await runDesktopChatSmoke(fixture!.page, {
+ mockUrl: fixture!.mockUrl,
+ phase: 'installed',
+ outDir: test.info().outputPath('desktop-chat'),
+ })
})
test('screenshot of chat with messages', async () => {
await expectVisualSnapshot(fixture!.page, { name: 'chat-with-messages', app: fixture!.app })
})
- test('offers stop, steer, and queue actions while busy', async ({}, testInfo) => {
+ test('offers stop, steer, and queue actions while busy', async () => {
+ const testInfo = test.info()
const page = fixture!.page
const composer = page.locator('[contenteditable="true"]').first()
const primary = page.locator('[data-slot="composer-root"] button[type="submit"]')
diff --git a/apps/desktop/e2e/fixtures.ts b/apps/desktop/e2e/fixtures.ts
index 134e957d886..1f8c6db7555 100644
--- a/apps/desktop/e2e/fixtures.ts
+++ b/apps/desktop/e2e/fixtures.ts
@@ -26,8 +26,11 @@ import * as path from 'node:path'
import { _electron, type ElectronApplication, type Page } from '@playwright/test'
+import { waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { type MockServerOptions, startMockServer } from '../../../tests-js/scripts/mock-server'
+
import { resolveElectronBinary } from './electron-binary'
-import { startMockServer, type MockServerOptions } from '../../../tests-js/scripts/mock-server'
import { installErrorBannerGuard } from './test'
const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
@@ -147,78 +150,6 @@ export function createSandbox(prefix: string): Sandbox {
// ─── Config writing ─────────────────────────────────────────────────────
-/**
- * Write a config.yaml that pre-configures a mock provider pointing at the
- * mock inference server. The provider is set as the active model provider so
- * the desktop app skips onboarding and boots straight to the chat UI.
- *
- * @param extraDisplayConfig optional YAML lines appended to the `display:`
- * section, used by the interim-message e2e test.
- * @param extraConfig optional top-level YAML sections for a test scenario.
- * @param modelContextLength optional primary-model context limit.
- */
-export function writeMockProviderConfig(
- hermesHome: string,
- mockUrl: string,
- extraDisplayConfig?: string,
- extraConfig?: string,
- modelContextLength?: number,
-): void {
- const configPath = path.join(hermesHome, 'config.yaml')
-
- const displaySection = extraDisplayConfig
- ? `\ndisplay:\n${extraDisplayConfig}\n`
- : ''
-
- // Title generation rides the MAIN model since 87af576e60 (#83636), so every
- // completed turn fires an extra background /v1/chat/completions at the mock.
- // That request contains the whole conversation — trigger keywords included —
- // which advances the mock's scripted-turn indices and trips hold-for-prompt
- // matchers from a request no spec ever sent. Disable it by default (no e2e
- // spec asserts on session titles); a test that passes its own `auxiliary:`
- // section via extraConfig owns the whole section instead.
- const autoTitleDefault = extraConfig?.includes('auxiliary:')
- ? ''
- : 'auxiliary:\n title_generation:\n enabled: false\n'
-
- // The scripted turns run REAL terminal commands, and anything the guard
- // classifies as dangerous (e.g. the sidebar sentinel-wait loop) parks the
- // turn behind a Run/Reject approval card. The default 'smart' mode then
- // fires an aux LLM approval call at the SAME mock provider — consuming a
- // scripted-turn index and never resolving — so the turn stalls until the
- // spec times out (the CI failure mode for the sidebar-dot family). No e2e
- // spec asserts on the approval flow, so run gate-free by default; a test
- // that passes its own `approvals:` section via extraConfig owns it.
- const approvalsDefault = extraConfig?.includes('approvals:')
- ? ''
- : 'approvals:\n mode: "off"\n'
-
- const config = `# Auto-generated by E2E test fixtures
-model:
- default: mock-model
- provider: mock
-${modelContextLength ? ` context_length: ${modelContextLength}\n` : ''}providers:
- mock:
- api: ${mockUrl}/v1
- name: Mock
- api_mode: chat_completions
- key_env: MOCK_API_KEY
- models:
- mock-model: {}
- context_length: 64000
-${autoTitleDefault}${approvalsDefault}${displaySection}${extraConfig ? `\n${extraConfig.trim()}\n` : ''}`
-
- fs.writeFileSync(configPath, config, 'utf8')
-}
-
-/**
- * Write a minimal .env with the mock API key. The key_env in config.yaml
- * references MOCK_API_KEY, so the backend resolves credentials from here.
- */
-export function writeEnvFile(hermesHome: string, apiKey = 'e2e-mock-key'): void {
- const envPath = path.join(hermesHome, '.env')
- fs.writeFileSync(envPath, `MOCK_API_KEY=${apiKey}\n`, 'utf8')
-}
/**
* Write an empty config (no providers). The desktop app should show the
@@ -366,6 +297,10 @@ export interface MockBackendFixture {
}
export interface MockBackendOptions {
+ /**
+ * Script and stream behavior for the mock inference server.
+ */
+ mockServer?: MockServerOptions
/**
* Optional YAML lines to inject under the `display:` section of the
* generated config.yaml. Used by the interim-message e2e test to toggle
@@ -385,9 +320,6 @@ export interface MockBackendOptions {
* 3. Launch the desktop app
* 4. Return handles for test interaction
*/
-export interface MockBackendOptions {
- mockServer?: MockServerOptions
-}
export async function setupMockBackend(options: MockBackendOptions = {}): Promise<MockBackendFixture> {
// 1. Start mock server
@@ -600,68 +532,11 @@ export async function setupPackagedApp(): Promise<PackagedAppFixture> {
// ─── Wait helpers ──────────────────────────────────────────────────────
-/**
- * Wait for the desktop app to finish booting and show the main chat UI.
- *
- * The boot overlay disappears when `completeDesktopBoot()` fires in the
- * renderer — at that point the gateway is open, config is loaded, and
- * sessions are loaded. We detect this by waiting for the boot/connecting
- * overlay to become invisible and the main app shell to be present.
- *
- * Two things must both be true before we return:
- * 1. The composer (chat input) is visible — it's disabled until the
- * gateway is open.
- * 2. No full-screen overlay (onboarding Preparing, connecting overlay,
- * boot-failure) covers the viewport center. The composer can be
- * "visible" in Playwright's eyes (non-zero bounding box, not
- * display:none) even when a z-1300+ overlay is painted on top of it,
- * so checking the composer alone catches the app mid-boot at ~92%
- * with the loading bar still showing.
- */
+/** Composer readiness includes hit testing, so boot overlays cannot produce an early pass. */
export async function waitForAppReady(fixture: MockBackendFixture | NoProviderFixture | DeadBackendFixture, timeoutMs = 60_000): Promise<void> {
const { page, app } = fixture
- // Wait for the composer to exist in the DOM (not necessarily interactive yet).
- await page.waitForSelector('textarea, [contenteditable="true"]', {
- state: 'attached',
- timeout: timeoutMs,
- })
-
- // Now poll until no full-screen overlay covers the viewport center.
- // elementFromPoint returns the topmost element at a point — if it's part
- // of a fixed inset-0 overlay (onboarding/connecting/boot-failure), the
- // app isn't ready yet.
- await page.waitForFunction(
- () => {
- const el = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2)
-
- if (!el) {
- return false
- }
-
- // Walk up to the nearest positioned ancestor — overlays are
- // `position: fixed; inset: 0`. If the hit element or an ancestor
- // is a full-viewport fixed overlay, we're still covered.
- let node: Element | null = el
- while (node) {
- const cs = window.getComputedStyle(node)
-
- if (cs.position === 'fixed') {
- const rect = node.getBoundingClientRect()
-
- if (rect.left <= 0 && rect.top <= 0 && rect.right >= window.innerWidth && rect.bottom >= window.innerHeight) {
- return false
- }
- }
-
- node = node.parentElement
- }
-
- return true
- },
- undefined,
- { timeout: timeoutMs },
- )
+ await waitForChatReady(page, timeoutMs)
// On Electron 40.x, ready-to-show may never fire (electron/electron#51972)
// and the window stays hidden even though the DOM is rendered. The main
diff --git a/apps/desktop/e2e/fleet-profile-rail.spec.ts b/apps/desktop/e2e/fleet-profile-rail.spec.ts
index 4303b90cd51..7df545aae85 100644
--- a/apps/desktop/e2e/fleet-profile-rail.spec.ts
+++ b/apps/desktop/e2e/fleet-profile-rail.spec.ts
@@ -17,6 +17,9 @@ import * as fs from 'node:fs'
import * as net from 'node:net'
import * as path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
@@ -24,10 +27,7 @@ import {
type MockBackendFixture,
type Sandbox,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
import { type ElectronApplication, expect, type Page, test } from './test'
const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
diff --git a/apps/desktop/e2e/hidden-history-messages.spec.ts b/apps/desktop/e2e/hidden-history-messages.spec.ts
index efaa0092530..dc000ba0779 100644
--- a/apps/desktop/e2e/hidden-history-messages.spec.ts
+++ b/apps/desktop/e2e/hidden-history-messages.spec.ts
@@ -9,21 +9,21 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import {
+ MOCK_REPLY,
+ startMockServer,
+ VERIFICATION_STOP_TEXT,
+ VERIFICATION_STOP_TRIGGER,
+} from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type MockBackendFixture,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
} from './fixtures'
-import {
- MOCK_REPLY,
- startMockServer,
- VERIFICATION_STOP_TEXT,
- VERIFICATION_STOP_TRIGGER,
-} from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
import { expect, test } from './test'
diff --git a/apps/desktop/e2e/image-attachment-resume.spec.ts b/apps/desktop/e2e/image-attachment-resume.spec.ts
index be9943e5815..66a2f75a700 100644
--- a/apps/desktop/e2e/image-attachment-resume.spec.ts
+++ b/apps/desktop/e2e/image-attachment-resume.spec.ts
@@ -14,16 +14,16 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { type MockServer, startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type Sandbox,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
} from './fixtures'
-import { type MockServer, startMockServer } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
import { type ElectronApplication, expect, type Page, test } from './test'
diff --git a/apps/desktop/e2e/large-session-resume.spec.ts b/apps/desktop/e2e/large-session-resume.spec.ts
index 4dfaaa7d922..e6fd1bf1400 100644
--- a/apps/desktop/e2e/large-session-resume.spec.ts
+++ b/apps/desktop/e2e/large-session-resume.spec.ts
@@ -2,7 +2,8 @@ import * as path from 'node:path'
import { type TestInfo } from '@playwright/test'
-import { expect, test, type ElectronApplication, type Page } from './test'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { MOCK_REPLY, type MockServer, type MockServerOptions, startMockServer } from '../../../tests-js/scripts/mock-server'
import {
buildAppEnv,
@@ -10,11 +11,9 @@ import {
launchDesktop,
type Sandbox,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
} from './fixtures'
-import { MOCK_REPLY, startMockServer, type MockServer, type MockServerOptions } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
+import { type ElectronApplication, expect, type Page, test } from './test'
const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
const SESSION_TITLE = 'E2E large persisted session'
diff --git a/apps/desktop/e2e/warm-resume-jitter.spec.ts b/apps/desktop/e2e/warm-resume-jitter.spec.ts
index 83f9fb3646d..174a879c1a7 100644
--- a/apps/desktop/e2e/warm-resume-jitter.spec.ts
+++ b/apps/desktop/e2e/warm-resume-jitter.spec.ts
@@ -30,19 +30,18 @@
* Prerequisite: `npm run build` must have been run so dist/ exists.
*/
-import { expect, test } from './test'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { startMockServer } from '../../../tests-js/scripts/mock-server'
import {
- type MockBackendFixture,
- waitForAppReady,
- createSandbox,
- writeMockProviderConfig,
- writeEnvFile,
buildAppEnv,
+ createSandbox,
launchDesktop,
+ type MockBackendFixture,
+ waitForAppReady,
} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
import { RealSessionBuilder } from './real-session-builder'
+import { expect, test } from './test'
const SESSION_TITLE = 'E2E Warm Resume Jitter Test'
diff --git a/apps/desktop/e2e/worktree-branch-status.spec.ts b/apps/desktop/e2e/worktree-branch-status.spec.ts
index 66c821a7bc8..e90926e68e0 100644
--- a/apps/desktop/e2e/worktree-branch-status.spec.ts
+++ b/apps/desktop/e2e/worktree-branch-status.spec.ts
@@ -2,16 +2,16 @@ import { execFileSync } from 'node:child_process'
import * as fs from 'node:fs'
import * as path from 'node:path'
+import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'
+import { startMockServer } from '../../../tests-js/scripts/mock-server'
+
import {
buildAppEnv,
createSandbox,
launchDesktop,
type MockBackendFixture,
waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
import { expect, test } from './test'
import { expectVisualSnapshot } from './visual-snapshot'
diff --git a/apps/desktop/tsconfig.e2e.json b/apps/desktop/tsconfig.e2e.json
index 5485ca4cc43..f7a5dbc8707 100644
--- a/apps/desktop/tsconfig.e2e.json
+++ b/apps/desktop/tsconfig.e2e.json
@@ -2,8 +2,9 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["node", "@playwright/test"],
+ "allowImportingTsExtensions": true,
"composite": true
},
- "include": ["e2e", "playwright.config.ts", "../../tests-js/scripts"],
+ "include": ["e2e", "playwright.config.ts", "../../tests-js/scripts", "../../tests/install/e2e-assets/desktop-smoke.ts"],
"exclude": ["src", "electron"]
}
diff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.md
index 5007477c5eb..f130b42550f 100644
--- a/docs/shared-bundle-builds.md
+++ b/docs/shared-bundle-builds.md
@@ -274,6 +274,29 @@ suites are `hermes-stable` and `hermes-canary`. Package files publish before
signed metadata. [Stable release admission](stable-releases.md) coordinates
acceptance and publication across distributions.
+## Public artifact handoffs
+
+The desktop release workflow downloads and installs each supported bundled
+format on a fresh native runner, then runs the same composer/provider/reply
+check as install-e2e. Windows universal assembly stages bytes before the smoke;
+its canary feed is published separately only after both native smoke matrices
+pass. macOS feed publication and stable candidate acceptance are likewise gated.
+See [install and chat acceptance](../tests/install/README.md#post-build-artifact-smoke)
+for covered formats, checkpoint evidence and the Store/Linux/no-upload limits.
+
+`scripts.releases.handoff fetch --public-base URL` downloads a staged artifact
+without R2 credentials. Supply either `--tag TAG --commit SHA` or
+`--commit-build SHA`, plus the producer `--name`, destination `--root`, and
+optional `--include` selectors. This uses the same receipt identity, path,
+size and SHA-256 checks as authenticated handoffs. Tagged and commit-only
+archives remain separate; the command does not resolve a mutable latest feed.
+
+Public reads require HTTPS, except for loopback fixture servers. They reject
+URL credentials, unsafe paths and redirects. An incomplete or corrupt download
+cannot replace an existing verified destination. Receipt files are saved only
+after all selected artifacts verify. Selection of one desktop format must still
+reject missing or ambiguous matches before installation.
+
## Cache ownership
PM binary download archives and the native uv wheel cache have different
diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.py
index 9d9689cad41..79e55efea60 100644
--- a/scripts/bundles/release_artifacts.py
+++ b/scripts/bundles/release_artifacts.py
@@ -14,7 +14,7 @@ import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
-from scripts.releases.stable import read_manifest, require_stable_identity, validate_candidates
+from scripts.releases.stable import read_admitted_candidate, successful_smoke_results, validate_candidates
def sha256_file(file: Path) -> str:
@@ -82,11 +82,13 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
out.write_text(json.dumps(row, sort_keys=True, indent=2) + "\n", encoding="utf-8")
-def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path) -> dict:
+def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path,
+ *, smoke_results: dict) -> dict:
"""Bind the native metadata to files already staged by their build jobs."""
from scripts.releases.handoff import receipt_name, validate_receipt
from scripts.releases.r2 import put, staging_key_for
+ smoke_results = successful_smoke_results(smoke_results)
expected = ("win32-x64", "win32-arm64", "darwin-x64", "darwin-arm64", "termux", "windows-universal")
by_name = {}
for name in expected:
@@ -130,7 +132,8 @@ def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path) ->
filename = universal_name if row["platform"] == "windows" else row["filename"]
item = by_name[filename]
packages.append({k: v for k, v in {**row, "artifact": {"url": item["url"], "sha256": item["sha256"]}}.items() if k != "filename"})
- result = {"schema": 1, "tag": tag, "commit": commit, "packages": packages, "files": files}
+ result = {"schema": 2, "tag": tag, "commit": commit, "packages": packages, "files": files,
+ "smoke_results": smoke_results}
validate_candidates(result, tag, commit, public_base)
if not any(row["platform"] == "termux" for row in packages):
raise ValueError("Missing Termux candidate")
@@ -287,20 +290,14 @@ def main(argv: list[str] | None = None) -> None:
if args.command == "record":
record(args.platform, args.arch, args.root, args.tag, args.commit, args.out)
elif args.command == "assemble":
- assemble(args.root, args.tag, args.commit, args.public_base, args.out)
+ assemble(args.root, args.tag, args.commit, args.public_base, args.out,
+ smoke_results=json.loads(os.environ.get("RELEASE_NEEDS", "{}")))
if os.environ.get("GITHUB_OUTPUT"):
with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as file:
file.write(f"manifest-url={args.public_base.rstrip('/')}/releases/tag/{args.tag}/release-candidates.json\nmanifest-sha256={sha256_file(args.out)}\n")
else:
- expected_digest = os.environ.get("CANDIDATE_MANIFEST_SHA256", "")
- if not re.fullmatch(r"[a-f0-9]{64}", expected_digest):
- raise ValueError("Pinned candidate manifest digest is required")
- require_stable_identity(args.tag, args.commit, f"refs/tags/{args.tag}")
- manifest = read_manifest(
- f"{args.public_base.rstrip('/')}/releases/tag/{args.tag}/release-candidates.json",
- expected_digest, expected_origin=args.public_base,
- )
- validate_candidates(manifest, args.tag, args.commit, args.public_base)
+ manifest = read_admitted_candidate(args.tag, args.commit, args.public_base,
+ os.environ.get("CANDIDATE_MANIFEST_SHA256", ""))
if args.command == "materialize":
materialize(manifest, args.root, public_base=args.public_base, store_only=args.store_only)
else:
diff --git a/scripts/releases/handoff.py b/scripts/releases/handoff.py
index 249e505dfd9..594df040e74 100644
--- a/scripts/releases/handoff.py
+++ b/scripts/releases/handoff.py
@@ -126,50 +126,56 @@ def stage_commit_build(commit: str, name: str, root: Path, includes: list[str])
return _stage(receipt, selected)
-def read_receipt(tag: str, commit: str, name: str) -> dict:
+def read_receipt(tag: str, commit: str, name: str, *, public_base: str | None = None) -> dict:
validate_identity(tag, commit, name)
- creds, base, bucket = r2.credentials()
key = r2.staging_key_for(tag, receipt_name(name))
- text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
- if text is None:
- raise ValueError(f"Missing release handoff: {name}")
- receipt = json.loads(text)
+ if public_base is not None:
+ receipt = r2.read_public_receipt(public_base, key)
+ else:
+ creds, base, bucket = r2.credentials()
+ text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
+ if text is None:
+ raise ValueError(f"Missing release handoff: {name}")
+ receipt = json.loads(text)
validate_receipt(receipt, tag, commit, name)
return receipt
-def read_commit_receipt(commit: str, name: str) -> dict:
+def read_commit_receipt(commit: str, name: str, *, public_base: str | None = None) -> dict:
validate_commit_identity(commit, name)
- creds, base, bucket = r2.credentials()
key = r2.commit_key_for(commit, receipt_name(name))
try:
- text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
+ if public_base is not None:
+ receipt = r2.read_public_receipt(public_base, key)
+ else:
+ creds, base, bucket = r2.credentials()
+ text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
+ if text is None:
+ raise MissingReceipt(f"Missing commit handoff: {name}")
+ receipt = json.loads(text)
except r2.R2RequestError as err:
if err.status == 404:
raise MissingReceipt(f"Missing commit handoff: {name}") from err
raise
- if text is None:
- raise MissingReceipt(f"Missing commit handoff: {name}")
- receipt = json.loads(text)
validate_commit_receipt(receipt, commit, name)
return receipt
def fetch(tag: str, commit: str, names: list[str], root: Path,
- includes: list[str] | None = None) -> list[dict]:
- receipts = [read_receipt(tag, commit, name) for name in names]
- return _fetch_receipts(receipts, root, includes)
+ includes: list[str] | None = None, *, public_base: str | None = None) -> list[dict]:
+ receipts = [read_receipt(tag, commit, name, public_base=public_base) for name in names]
+ return _fetch_receipts(receipts, root, includes, public_base=public_base)
def fetch_commit_build(commit: str, names: list[str], root: Path,
- includes: list[str] | None = None) -> list[dict]:
+ includes: list[str] | None = None, *, public_base: str | None = None) -> list[dict]:
"""Fetch commit artifacts through the shared receipt-bound transport."""
- receipts = [read_commit_receipt(commit, name) for name in names]
- return _fetch_receipts(receipts, root, includes)
+ receipts = [read_commit_receipt(commit, name, public_base=public_base) for name in names]
+ return _fetch_receipts(receipts, root, includes, public_base=public_base)
def _fetch_receipts(receipts: list[dict], root: Path,
- includes: list[str] | None = None) -> list[dict]:
+ includes: list[str] | None = None, *, public_base: str | None = None) -> list[dict]:
"""Download exact receipt-bound bytes before writing local receipt copies."""
root = root.resolve()
selected = {}
@@ -190,11 +196,17 @@ def _fetch_receipts(receipts: list[dict], root: Path,
if not selected:
raise ValueError("No files selected from release handoff")
root.mkdir(parents=True, exist_ok=True)
- creds, base, bucket = r2.credentials()
+ credentials = r2.credentials() if public_base is None else None
for row, key in selected.values():
- r2.download_object(creds, base, bucket, key,
- root / row["path"], r2.amz_timestamp(),
- expected_size=row["size"], expected_sha256=row["sha256"])
+ if credentials is not None:
+ creds, base, bucket = credentials
+ r2.download_object(creds, base, bucket, key,
+ root / row["path"], r2.amz_timestamp(),
+ expected_size=row["size"], expected_sha256=row["sha256"])
+ else:
+ assert public_base is not None
+ r2.download_public_object(public_base, key, root / row["path"],
+ expected_size=row["size"], expected_sha256=row["sha256"])
for receipt in receipts:
(root / receipt_name(receipt["name"])).write_text(json.dumps(receipt, sort_keys=True, indent=2) + "\n", encoding="utf-8")
return receipts
@@ -212,7 +224,10 @@ def main(argv: list[str] | None = None) -> None:
parser.add_argument("--name", action="append", required=True)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--include", action="append")
+ parser.add_argument("--public-base", help="Fetch from the public archive without R2 credentials")
args = parser.parse_args(argv)
+ if args.public_base is not None and args.command != 'fetch':
+ parser.error('--public-base is only supported for fetch')
if args.commit_build:
if args.tag:
parser.error("--commit-build and --tag are mutually exclusive")
@@ -224,14 +239,14 @@ def main(argv: list[str] | None = None) -> None:
parser.error("stage needs one name and at least one include pattern")
stage_commit_build(commit, args.name[0], args.root, args.include)
else:
- fetch_commit_build(commit, args.name, args.root, args.include)
+ fetch_commit_build(commit, args.name, args.root, args.include, public_base=args.public_base)
return
if args.command == "stage":
if len(args.name) != 1 or not args.include:
parser.error("stage needs one name and at least one include pattern")
stage(args.tag, args.commit, args.name[0], args.root, args.include)
else:
- fetch(args.tag, args.commit, args.name, args.root, args.include)
+ fetch(args.tag, args.commit, args.name, args.root, args.include, public_base=args.public_base)
if __name__ == "__main__":
diff --git a/scripts/releases/r2.py b/scripts/releases/r2.py
index 78dec9594ad..1e1ec728f80 100644
--- a/scripts/releases/r2.py
+++ b/scripts/releases/r2.py
@@ -322,6 +322,52 @@ def download_object(
creds: dict[str, str], base: str, bucket: str, key: str, file: Path, now: str,
*, expected_size: int, expected_sha256: str,
) -> None:
+ url = f"{base}/{bucket}/{encode_key_path(key)}"
+ parsed = urlparse(url)
+ def headers(attempt: int) -> dict[str, str]:
+ return r2_headers("GET", parsed.netloc, parsed.path, "", EMPTY_SHA,
+ now if attempt == 1 else amz_timestamp(), creds)
+ _download_url(url, file, headers, expected_size=expected_size, expected_sha256=expected_sha256)
+
+
+def public_artifact_url(base: str, key: str) -> str:
+ """Public reads never carry credentials or follow redirects out of the archive."""
+ parsed = urlparse(base)
+ if (not parsed.hostname or parsed.username is not None or parsed.password is not None
+ or parsed.query or parsed.fragment or parsed.params
+ or any(c in base for c in ('%', '\\')) or any(ord(c) <= 32 for c in base)
+ or any(part in ('.', '..') for part in parsed.path.split('/'))
+ or not (parsed.scheme == 'https' or (parsed.scheme == 'http'
+ and parsed.hostname in ('127.0.0.1', 'localhost', '::1')))):
+ raise ValueError('Invalid public artifact base URL')
+ return public_url_for(base, relative_artifact_path(key))
+
+
+def read_public_receipt(base: str, key: str) -> dict:
+ url = public_artifact_url(base, key)
+ parsed = urlparse(url)
+ conn = _connection(url, timeout=60.0)
+ try:
+ conn.request('GET', parsed.path)
+ response = conn.getresponse()
+ if response.status != 200:
+ raise R2RequestError('GET', parsed.path, response.status)
+ # Receipts are metadata, never an unbounded binary download.
+ body = response.read(4 * 1024 * 1024 + 1)
+ if len(body) > 4 * 1024 * 1024:
+ raise ValueError('Public handoff receipt exceeds metadata limit')
+ return json.loads(body)
+ finally:
+ conn.close()
+
+
+def download_public_object(base: str, key: str, file: Path, *, expected_size: int, expected_sha256: str) -> None:
+ _download_url(public_artifact_url(base, key), file, lambda _attempt: {},
+ expected_size=expected_size, expected_sha256=expected_sha256)
+
+
+def _download_url(url: str, file: Path, request_headers: Callable[[int], dict[str, str]],
+ *, expected_size: int, expected_sha256: str) -> None:
"""Publish a download locally only after its exact receipt matches."""
import tempfile
@@ -329,15 +375,12 @@ def download_object(
raise ValueError("Invalid artifact size or SHA256")
file = Path(file)
file.parent.mkdir(parents=True, exist_ok=True)
- url = f"{base}/{bucket}/{encode_key_path(key)}"
parsed = urlparse(url)
for attempt in range(1, 4):
- headers = r2_headers("GET", parsed.netloc, parsed.path, "", EMPTY_SHA,
- now if attempt == 1 else amz_timestamp(), creds)
conn = _connection(url, timeout=600.0)
temporary = None
try:
- conn.request("GET", parsed.path, headers=headers)
+ conn.request("GET", parsed.path, headers=request_headers(attempt))
response = conn.getresponse()
if response.status != 200:
raise R2RequestError("GET", parsed.path, response.status)
@@ -347,9 +390,11 @@ def download_object(
while chunk := response.read(1024 * 1024):
digest.update(chunk)
size += len(chunk)
+ if size > expected_size:
+ raise ValueError(f"Artifact checksum mismatch: {parsed.path}")
output.write(chunk)
if size != expected_size or digest.hexdigest() != expected_sha256:
- raise ValueError(f"Artifact checksum mismatch: {key}")
+ raise ValueError(f"Artifact checksum mismatch: {parsed.path}")
temporary.replace(file)
return
except R2RequestError as error:
diff --git a/scripts/releases/stable.py b/scripts/releases/stable.py
index 43f39b13933..f3a25a5f704 100644
--- a/scripts/releases/stable.py
+++ b/scripts/releases/stable.py
@@ -17,6 +17,11 @@ from scripts.releases.semver import STABLE_TAG
SHA = re.compile(r"[a-f0-9]{40}")
DIGEST = re.compile(r"[a-f0-9]{64}")
DESKTOP_TARGETS = ("windows/x64", "windows/arm64", "macos/x64", "macos/arm64")
+SMOKE_JOBS = {
+ "smoke-darwin": "macOS DMG + ZIP (arm64 and x64)",
+ "smoke-win32": "Windows MSIX (arm64 and x64)",
+ "smoke-win32-universal": "Windows MSIXBUNDLE (arm64 and x64)",
+}
def require_stable_identity(tag: str, commit: str, ref: str) -> None:
@@ -33,10 +38,29 @@ def require_success(needs: dict, required: list[str]) -> None:
raise ValueError("Release blocked: " + ", ".join(failures))
-def validate_candidates(manifest: dict, tag: str, commit: str, public_base: str) -> dict:
+def successful_smoke_results(needs: object) -> dict:
+ """Persist only observed successful native groups, never infer them from artifacts."""
+ if not isinstance(needs, dict):
+ raise ValueError("Candidate smoke results must be a job-result object")
+ results = {}
+ for job in SMOKE_JOBS:
+ row = needs.get(job)
+ results[job] = {"result": row.get("result") if isinstance(row, dict) else None}
+ require_success(results, list(SMOKE_JOBS))
+ return results
+
+
+def validate_candidates(manifest: dict, tag: str, commit: str, public_base: str,
+ *, allow_legacy: bool = False) -> dict:
require_stable_identity(tag, commit, f"refs/tags/{tag}")
- if manifest.get("schema") != 1 or manifest.get("tag") != tag or manifest.get("commit") != commit or not isinstance(manifest.get("packages"), list):
+ if manifest.get("schema") not in (1, 2) or manifest.get("tag") != tag or manifest.get("commit") != commit or not isinstance(manifest.get("packages"), list):
raise ValueError("Candidate manifest does not match release identity")
+ if manifest["schema"] == 1:
+ # A published baseline supplies old package identities, not new smoke evidence.
+ if not allow_legacy:
+ raise ValueError("Legacy candidate has no bound smoke admission; build a new candidate tag")
+ else:
+ successful_smoke_results(manifest.get("smoke_results"))
prefix = urlsplit(f"{public_base.rstrip('/')}/releases/tag/{tag}/")
if prefix.scheme != "https" or prefix.username or prefix.password or not prefix.netloc:
raise ValueError("Public release origin must use HTTPS")
@@ -79,7 +103,7 @@ def windows_version(value: str) -> tuple[int, ...]:
def plan_transitions(previous: dict, candidate: dict, public_base: str) -> list[dict]:
- old = validate_candidates(previous, previous.get("tag"), previous.get("commit"), public_base)
+ old = validate_candidates(previous, previous.get("tag"), previous.get("commit"), public_base, allow_legacy=True)
new = validate_candidates(candidate, candidate.get("tag"), candidate.get("commit"), public_base)
result = []
for target in DESKTOP_TARGETS:
@@ -154,6 +178,17 @@ def read_candidate(env: dict) -> dict:
return read_manifest(env["CANDIDATE_MANIFEST_URL"], digest)
+def read_admitted_candidate(tag: str, commit: str, public_base: str, digest: str) -> dict:
+ """The page and package promoter consume the same pinned admission."""
+ if not DIGEST.fullmatch(digest or ""):
+ raise ValueError("Pinned candidate manifest digest is required")
+ require_stable_identity(tag, commit, f"refs/tags/{tag}")
+ manifest = read_manifest(f"{public_base.rstrip('/')}/releases/tag/{tag}/release-candidates.json",
+ digest, expected_origin=public_base)
+ validate_candidates(manifest, tag, commit, public_base)
+ return manifest
+
+
def summary(text: str, env: dict) -> None:
with Path(env["GITHUB_STEP_SUMMARY"]).open("a", encoding="utf-8") as file:
file.write(text + "\n")
diff --git a/scripts/render-builds-table.py b/scripts/render-builds-table.py
index 9b530ab294d..f97d89d8b3e 100644
--- a/scripts/render-builds-table.py
+++ b/scripts/render-builds-table.py
@@ -53,7 +53,7 @@ from urllib.parse import quote
# Direct-script invocation starts with scripts/, not the repository root.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from scripts.releases import handoff, r2, semver # noqa: E402
+from scripts.releases import handoff, r2, semver, stable # noqa: E402
MARKER = "<!-- HERMES_BUILDS_TABLE -->"
END_MARKER = "<!-- /HERMES_BUILDS_TABLE -->"
@@ -120,7 +120,7 @@ def table_rows(assets_by_app: dict) -> list[tuple[str, list[tuple[str, str, str,
def render_tables(assets_by_app: dict, base_url: str,
incomplete_jobs: list[str] | None = None,
- run_url: str | None = None) -> str:
+ run_url: str | None = None, *, smoke_results: dict | None = None) -> str:
"""The replacement block: marker + tables + end marker."""
sections = []
for title, rows in table_rows(assets_by_app):
@@ -140,6 +140,7 @@ def render_tables(assets_by_app: dict, base_url: str,
sections.append("### Build diagnostics\n\n| Job | Diagnostics |\n|---|---|\n"
+ "\n".join(f"| {job} | [View build run]({run_url}) |"
for job in incomplete_jobs))
+ sections.append(smoke_markdown(smoke_results))
return MARKER + "\n## Downloads\n\n" + "\n\n".join(sections) + "\n" + END_MARKER
@@ -199,10 +200,35 @@ COMMIT_RECEIPT_NAMES = sorted({leg for _label, leg, _pattern in _COMMIT_EXPECTED
_COMMIT_JOBS = {
"win32-x64": "build-win32", "win32-arm64": "build-win32",
"darwin-x64": "build-darwin", "darwin-arm64": "build-darwin",
- "windows-universal": "publish-win32-updater", "termux": "termux-deb",
+ "windows-universal": "assemble-win32-bundle", "termux": "termux-deb",
}
+_SMOKE_SCOPE = (
+ "Download availability is independent of smoke status. Each result covers all native legs "
+ "in that format group. Linux bundles are disabled; unsigned Store envelopes are not install-smoked. "
+ "No-upload dry tags have no download handoff and are not smoke-qualified."
+)
+
+
+def smoke_rows(results: dict | None) -> list[tuple[str, str]]:
+ statuses = {"success": "Passed", "failure": "Failed", "cancelled": "Cancelled", "skipped": "Not run"}
+ return [(label, statuses.get((results or {}).get(job, {}).get("result"), "Not run (no result)"))
+ for job, label in stable.SMOKE_JOBS.items()]
+
+
+def smoke_markdown(results: dict | None) -> str:
+ return ("### Native install/chat smoke\n\n" + _SMOKE_SCOPE
+ + "\n\n| Packages | Smoke status |\n|---|---|\n"
+ + "\n".join(f"| {label} | {status} |" for label, status in smoke_rows(results)))
+
+
+def smoke_html(results: dict | None) -> list[str]:
+ return ["<h2>Native install/chat smoke</h2>", f"<p>{html.escape(_SMOKE_SCOPE)}</p>",
+ *_table(("Packages", "Smoke status"),
+ [[html.escape(label), html.escape(status)] for label, status in smoke_rows(results)])]
+
+
def commit_expected_rows(names: list[str],
receipts: dict[str, dict | None]) -> list[dict]:
"""Classify artifacts from validated receipts without trusting orphan objects."""
@@ -273,7 +299,7 @@ def commit_entries(commit: str, names: list[str], base_url: str,
def render_commit_summary(names: list[str], base_url: str, commit: str,
receipts: dict[str, dict | None],
failed_legs: list[str] | None = None,
- run_url: str | None = None) -> str:
+ run_url: str | None = None, *, smoke_results: dict | None = None) -> str:
"""Render every expected product without reading or changing a release."""
_validated_commit_inputs(commit, receipts)
lines = [
@@ -285,7 +311,7 @@ def render_commit_summary(names: list[str], base_url: str, commit: str,
for label, status, url, link_text in commit_entries(commit, names, base_url, receipts, failed_legs, run_url):
cell = f"[{link_text}]({url})" if url and link_text else "—"
lines.append(f"| {label} | {status} | {cell} |")
- return "\n".join([*lines, ""])
+ return "\n".join([*lines, "", smoke_markdown(smoke_results), ""])
def read_commit_receipts(commit: str,
@@ -373,7 +399,8 @@ def _link(url: str) -> str:
def render_page(tag: str, assets_by_app: dict, base_url: str,
incomplete_jobs: list[str] | None = None,
- run_url: str | None = None, *, repo: str = DEFAULT_REPO) -> str:
+ run_url: str | None = None, *, repo: str = DEFAULT_REPO,
+ smoke_results: dict | None = None) -> str:
"""The tag/channel page: the release-body download table as HTML."""
channel = r2.channel_for_tag(tag)
tag_url = f"https://github.com/{quote(repo, safe='/')}/releases/tag/{quote(tag, safe='')}"
@@ -403,6 +430,7 @@ def render_page(tag: str, assets_by_app: dict, base_url: str,
("Job", "Diagnostics"),
[[html.escape(job), f"{_link(run_url)}View build run</a>"] for job in incomplete_jobs],
))
+ body.extend(smoke_html(smoke_results))
return _page(f"Hermes Desktop {channel} builds", tag, body)
@@ -410,7 +438,8 @@ def render_commit_page(commit: str, names: list[str], base_url: str,
receipts: dict[str, dict | None],
failed_legs: list[str] | None = None,
run_url: str | None = None, *, repo: str = DEFAULT_REPO,
- bundle_env: dict[str, str | None] | None = None) -> str:
+ bundle_env: dict[str, str | None] | None = None,
+ smoke_results: dict | None = None) -> str:
"""The commit-build page: every expected binary, built or not."""
_validated_commit_inputs(commit, receipts)
commit_url = f"https://github.com/{quote(repo, safe='/')}/commit/{commit}"
@@ -437,6 +466,7 @@ def render_commit_page(commit: str, names: list[str], base_url: str,
for key, value in sorted(validate(bundle_env).items())
]),
])
+ body.extend(smoke_html(smoke_results))
return _page(f"Hermes commit build {commit[:12]}", commit, body)
@@ -493,13 +523,13 @@ def existing_page(key: str) -> str | None:
def write_channel_page(tag: str, assets_by_app: dict, base_url: str,
- *, repo: str = DEFAULT_REPO) -> str | None:
+ *, repo: str = DEFAULT_REPO, smoke_results: dict | None = None) -> str | None:
"""Publish releases/<channel>/index.html for the tag's own channel."""
key = r2.channel_page_key_for(r2.channel_for_tag(tag))
if not supersedes(existing_page(key), tag):
print(f"::warning::{key} already describes a newer release; leaving it unchanged")
return None
- return write_page(key, render_page(tag, assets_by_app, base_url, repo=repo), base_url)
+ return write_page(key, render_page(tag, assets_by_app, base_url, repo=repo, smoke_results=smoke_results), base_url)
def r2_object_names_under(prefix: str) -> list[str]:
@@ -526,6 +556,10 @@ def splice(body: str, block: str) -> str:
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tag", required=False, help="Release tag to render the release-body table for")
+ parser.add_argument("--candidate-manifest-sha256", default=None,
+ help="Stable promotion: render smoke admission from this pinned candidate, not RELEASE_NEEDS")
+ parser.add_argument("--candidate-commit", default=None,
+ help="Exact admitted commit for --candidate-manifest-sha256")
parser.add_argument("--summary-commit", default=None,
help="Commit-only mode: render the FULL expected-binary matrix for "
"releases/commit/<sha>/ into --summary-out. Never touches a "
@@ -550,10 +584,25 @@ def main() -> int:
help="Render a 'builds in progress' link to this workflow run "
"instead of the tables")
args = parser.parse_args()
+ try:
+ smoke_results = json.loads(os.environ.get("RELEASE_NEEDS", "{}"))
+ if not isinstance(smoke_results, dict):
+ smoke_results = {}
+ except ValueError:
+ smoke_results = {}
if args.summary_commit and (args.tag or args.pending_run_url):
parser.error("--summary-commit cannot be combined with release-body arguments")
+ candidate = None
+ if args.candidate_manifest_sha256 is not None or args.candidate_commit is not None:
+ if (args.candidate_manifest_sha256 is None or args.candidate_commit is None
+ or not args.tag or not args.r2_base_url or args.summary_commit or args.pending_run_url):
+ parser.error("Candidate rendering requires tag, base URL, manifest SHA256 and commit; no summary or pending mode")
+ candidate = stable.read_admitted_candidate(args.tag, args.candidate_commit, args.r2_base_url,
+ args.candidate_manifest_sha256)
+ smoke_results = candidate["smoke_results"]
+
if args.summary_commit:
if not args.summary_out:
@@ -575,12 +624,13 @@ def main() -> int:
receipts = read_commit_receipts(commit)
failed_legs = (failed_legs_from_release_needs(os.environ.get("RELEASE_NEEDS"))
or [leg.strip() for leg in args.summary_failed_legs.split(",") if leg.strip()])
- block = render_commit_summary(names, args.r2_base_url, commit, receipts, failed_legs, args.run_url)
+ block = render_commit_summary(names, args.r2_base_url, commit, receipts, failed_legs, args.run_url,
+ smoke_results=smoke_results)
with open(args.summary_out, "a", encoding="utf-8") as out:
out.write(block)
write_page(r2.commit_page_key_for(commit),
render_commit_page(commit, names, args.r2_base_url, receipts, failed_legs, args.run_url,
- repo=args.repo, bundle_env=bundle_env),
+ repo=args.repo, bundle_env=bundle_env, smoke_results=smoke_results),
args.r2_base_url)
built = sum(1 for row in commit_expected_rows(names, receipts) if row["state"] == "built")
print(f"✓ Commit summary appended to {args.summary_out} ({built}/{len(_COMMIT_EXPECTED)} binaries built)")
@@ -599,15 +649,18 @@ def main() -> int:
print("::error::--r2-base-url (or CLOUDFLARE_R2_PUBLIC_URL) is required to render the tables")
return 1
names = r2_object_names(args.tag)
+ if candidate is not None:
+ admitted = {r2.staging_key_for(args.tag, item["path"]) for item in candidate["files"]}
+ names = [name for name in names if name in admitted]
assets = parse_assets(names)
- incomplete = incomplete_release_jobs(os.environ.get("RELEASE_NEEDS"))
- block = render_tables(assets, args.r2_base_url, incomplete, args.run_url)
+ incomplete = [] if candidate is not None else incomplete_release_jobs(os.environ.get("RELEASE_NEEDS"))
+ block = render_tables(assets, args.r2_base_url, incomplete, args.run_url, smoke_results=smoke_results)
# A failed run still owns its tag page, never the channel pointer
# consumed by source updates. Missing artifacts never become downloads.
if not args.dry_run:
write_page(r2.staging_key_for(args.tag, "index.html"),
render_page(args.tag, assets, args.r2_base_url, incomplete, args.run_url,
- repo=args.repo), args.r2_base_url)
+ repo=args.repo, smoke_results=smoke_results), args.r2_base_url)
# Keep the per-tag diagnostic page even when GitHub cannot supply a draft.
view = subprocess.run(
@@ -621,7 +674,7 @@ def main() -> int:
release = json.loads(view.stdout)
body = release.get("body") or ""
if not args.pending_run_url and not args.dry_run and not incomplete and names:
- write_channel_page(args.tag, assets, args.r2_base_url, repo=args.repo)
+ write_channel_page(args.tag, assets, args.r2_base_url, repo=args.repo, smoke_results=smoke_results)
if MARKER not in body:
print("::warning::release body has no HERMES_BUILDS_TABLE marker; leaving it unchanged")
return 0
diff --git a/scripts/stage-msixbundle.mjs b/scripts/stage-msixbundle.mjs
index 9ca82001eb1..dd973c00228 100644
--- a/scripts/stage-msixbundle.mjs
+++ b/scripts/stage-msixbundle.mjs
@@ -1,8 +1,7 @@
#!/usr/bin/env node
// Native Windows adapter: bundle x64 + arm64 MSIX packages and sign the
-// envelope. Candidate/commit modes stop at the artifact. Canary releases hand
-// the completed bundle and expected identity to release Python, which verifies
-// the manifest and publishes the bundle before its App Installer pointer.
+// envelope. Every mode stops at the artifact; CI stages it for native smoke
+// before the separate release Python publisher can write an App Installer feed.
// Usage: node scripts/stage-msixbundle.mjs --tag vX.Y.Z --candidate
// node scripts/stage-msixbundle.mjs --tag vX.Y.Z-canary.STAMP
import { execFileSync } from 'node:child_process'
@@ -11,7 +10,7 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parseArgs } from 'node:util'
-import { appIdentity, OUT_OF_STORE_PUBLISHER } from './msix-shared.mjs'
+import { appIdentity } from './msix-shared.mjs'
import { ensureWindowsBundleTools } from '../apps/desktop/scripts/windows-bundle-tools.mjs'
@@ -79,7 +78,7 @@ if (!commitBuild && !canary && !candidate) throw new Error('Stable bundles must
const desktop = path.join(REPO_ROOT, 'apps', 'desktop')
const releaseDir = path.join(desktop, 'release')
-const { identity, version, name, fileVersion } = appIdentity(desktop, tag)
+const { version, name, fileVersion } = appIdentity(desktop, tag)
// Per-arch .msix files are found by the name electron-builder gave them
// (appInfo.version = the 3-part or full-canary string, NOT the 4-part feed
@@ -160,23 +159,6 @@ if (signing) {
console.warn('[stage-msixbundle] AZURE_SIGN_* not set — bundle will be UNSIGNED')
}
-if (candidate) {
- execFileSync(signtool, ['verify', '/pa', bundle], { stdio: 'inherit' })
- console.log(`[stage-msixbundle] candidate ready: ${bundle}`)
- process.exit(0)
-}
-
-// Commit-only mode stops here: the workflow hands the bundle to R2 through
-// scripts.releases.handoff (schema-2 receipt) — never a feed dir.
-if (commitBuild) {
- console.log(`[stage-msixbundle] commit bundle ready (no upload): ${bundle}`)
- process.exit(0)
-}
-
-// Python owns descriptor serialization, identity verification and publication.
-execFileSync(process.env.HERMES_PYTHON || 'python', [
- '-m', 'scripts.bundles.release_artifacts', 'publish-appinstaller',
- '--root', releaseDir, '--bundle', bundle, '--tag', tag, '--variant', variant,
- '--identity', identity.msixAppIdWithOrg, '--publisher', OUT_OF_STORE_PUBLISHER, '--version', version,
-], { cwd: REPO_ROOT, stdio: 'inherit' })
-console.log('[stage-msixbundle] done — feed manifests + bundle staged')
+// Local assembly may be unsigned. CI's native smoke requires a valid signature
+// on the receipt-bound download before any release publication can proceed.
+console.log(`[stage-msixbundle] bundle ready (no upload): ${bundle}`)
diff --git a/tests-js/bundle-smoke-metadata.test.mjs b/tests-js/bundle-smoke-metadata.test.mjs
new file mode 100644
index 00000000000..06742974b9e
--- /dev/null
+++ b/tests-js/bundle-smoke-metadata.test.mjs
@@ -0,0 +1,73 @@
+import { expect, test } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { bundleIdentity, verifyBundleStamp } from '../tests/install/e2e-assets/bundle-smoke-metadata.mjs'
+import { stampAssertions } from '../tests/install/e2e-assets/mac-bundled-manifest.cjs'
+
+const commit = 'a'.repeat(40)
+
+test('fresh-install provenance admits tagless commit stamps without relaxing update acceptance', () => {
+ const stamp = { commit, tag: null, source: 'commit-build', branch: null, dirty: false,
+ distribution: 'desktop-app', payload: 'bundled', updateMechanism: 'external', displayVersion: '1.2.3' }
+ for (const platform of ['darwin', 'win32']) {
+ expect(verifyBundleStamp(stamp, { commit, platform })).toBe('1.2.3')
+ for (const [key, value] of [['commit', 'b'.repeat(40)], ['tag', 'v1.2.3'], ['payload', 'light'],
+ ['source', 'git'], ['branch', 'main'], ['dirty', true], ['updateMechanism', 'electron-updater']]) {
+ expect(() => verifyBundleStamp({ ...stamp, [key]: value }, { commit, platform })).toThrow(key)
+ }
+ const tag = 'v1.2.3-canary.20260913000000'
+ const tagged = { ...stamp, tag, source: 'git', branch: 'main', displayVersion: tag.slice(1),
+ updateMechanism: platform === 'darwin' ? 'electron-updater' : 'app-installer' }
+ expect(verifyBundleStamp(tagged, { commit, tag, platform })).toBe(tag.slice(1))
+ expect(() => verifyBundleStamp({ ...tagged, updateMechanism: 'external' }, { commit, tag, platform })).toThrow('updateMechanism')
+ }
+ expect(stampAssertions(stamp, { commit, tag: null }).join(';')).toContain('electron-updater')
+})
+
+test('identity uses the production bundled variant and exact input tokens, not inherited build flags', () => {
+ const stable = bundleIdentity(commit, 'v1.2.3')
+ const canary = bundleIdentity(commit, 'v1.2.3-canary.20260913000000')
+ const tagless = bundleIdentity(commit)
+ expect(stable.appId).not.toBe(canary.appId)
+ expect(stable.msixIdentity).not.toBe(tagless.msixIdentity)
+ expect(tagless.appId).toContain(commit.slice(0, 7))
+ expect(tagless.publisher).toBe(stable.publisher)
+ for (const bad of [commit.slice(0, 7), ` ${commit}`, commit.toUpperCase()]) {
+ expect(() => bundleIdentity(bad)).toThrow('commit')
+ }
+ expect(() => bundleIdentity(commit, 'v1.2.3 ')).toThrow('tag')
+ const hostileEnvironment = { ...process.env, HERMES_DESKTOP_VARIANT: 'store', HERMES_BUILD_COMMIT: 'b'.repeat(40), HERMES_PAYLOAD_TAG: 'v9.9.9' }
+ const cli = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/bundle-smoke-metadata.mjs')
+ expect(JSON.parse(execFileSync(process.execPath, [cli, 'identity', '--commit', commit], { env: hostileEnvironment, encoding: 'utf8' }))).toEqual(tagless)
+})
+
+test('workspace admission rejects reuse and symlink escapes before creating anything outside runner temp', () => {
+ const temp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-paths-')))
+ const cli = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/bundle-smoke-metadata.mjs')
+ const run = (work, out) => spawnSync(process.execPath, [cli, 'prepare', '--work', work, '--out', out],
+ { env: { ...process.env, RUNNER_TEMP: temp }, encoding: 'utf8' })
+ try {
+ const work = path.join(temp, 'work'), out = path.join(temp, 'out')
+ expect(run(work, out).status).toBe(0)
+ expect(run(work, out).status).toBe(1)
+ expect(run(path.join(temp, '..', 'escape'), out).status).toBe(1)
+ expect(run(path.join(temp, 'another-work'), path.join(temp, 'another-work')).status).toBe(1)
+ fs.symlinkSync(os.tmpdir(), path.join(temp, 'link'), process.platform === 'win32' ? 'junction' : 'dir')
+ expect(run(path.join(temp, 'link', 'escape'), out).status).toBe(1)
+ const marker = path.join(work, 'keep')
+ fs.writeFileSync(marker, 'untouched')
+ expect(run(work, out).status).toBe(1)
+ expect(fs.readFileSync(marker, 'utf8')).toBe('untouched')
+ const alias = path.join(temp, 'alias')
+ fs.symlinkSync(temp, alias, process.platform === 'win32' ? 'junction' : 'dir')
+ expect(run(path.join(alias, 'fresh'), out).status).toBe(0)
+ } finally { fs.rmSync(temp, { recursive: true, force: true }) }
+})
+
+test.runIf(process.platform === 'win32')('PowerShell admits only the pinned package and native slice', () => {
+ const script = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/windows-bundle-metadata.test.ps1')
+ expect(execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script],
+ { encoding: 'utf8' })).toContain('PASS: MSIX identity/executable and MSIXBUNDLE native-slice admission')
+})
\ No newline at end of file
diff --git a/tests-js/scripts/desktop-chat-smoke.ts b/tests-js/scripts/desktop-chat-smoke.ts
new file mode 100644
index 00000000000..22893d186eb
--- /dev/null
+++ b/tests-js/scripts/desktop-chat-smoke.ts
@@ -0,0 +1,182 @@
+import { randomUUID } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+
+import { expect, type Locator, type Page } from '@playwright/test'
+import { z } from 'zod'
+
+import { validateMockUrl } from './mock-provider-config.ts'
+import { MOCK_REPLY } from './mock-server.ts'
+
+export type ChatPhase = 'old' | 'new' | 'installed'
+
+export interface DesktopChatSmokeOptions {
+ mockUrl: string
+ phase: ChatPhase
+ outDir: string
+ expectCommit?: string
+ provenanceCommit?: string
+ observePrompts?: () => Promise<readonly string[]>
+}
+
+export interface ChatIdentity {
+ appVersion: string
+ commit: string | null
+ hermesRoot: string
+ platform: string
+}
+
+interface SmokeWindow extends Window {
+ hermesDesktop?: { getVersion: () => Promise<ChatIdentity> }
+}
+
+export interface TranscriptMessage {
+ id: string
+ role: string
+ text: string
+ streaming: boolean
+ error: boolean
+}
+
+export interface DesktopChatReceipt {
+ status: 'passed'
+ phase: ChatPhase
+ expectedCommit: string | null
+ identity: ChatIdentity
+ provenanceCommit: string | null
+ prompt: string
+ requestWitness: { index: number; prompt: string; before: number }
+ transcript: { beforeIds: string[]; user: TranscriptMessage; assistant: TranscriptMessage }
+ turnComplete: true
+ screenshot: string
+}
+
+const identitySchema = z.object({
+ appVersion: z.string(), commit: z.string().nullable().optional(),
+ hermesRoot: z.string(), platform: z.string(),
+})
+
+export async function readChatIdentity(page: Page): Promise<ChatIdentity> {
+ const identity = identitySchema.parse(await page.evaluate(async (): Promise<ChatIdentity> => {
+ // SAFETY: the driver uses a desktop page; the returned IPC data is parsed outside the renderer.
+ const bridge = (window as SmokeWindow).hermesDesktop
+ if (!bridge) {
+ throw new Error('Desktop version bridge is unavailable')
+ }
+ return bridge.getVersion()
+ }))
+ return { ...identity, commit: identity.commit ?? null }
+}
+
+/** Old desktops do not report a commit; their caller must verify the installed runtime. */
+export function assertChatCommit(identity: ChatIdentity, expected: string, provenanceCommit?: string): void {
+ if (identity.commit !== null && identity.commit !== expected) {
+ throw new Error(`Running commit ${identity.commit} does not equal expected ${expected}`)
+ }
+ if (provenanceCommit !== undefined && provenanceCommit !== expected) {
+ throw new Error(`Verified installation commit ${provenanceCommit} does not equal expected ${expected}`)
+ }
+ if (identity.commit === null && provenanceCommit !== expected) {
+ throw new Error('Desktop does not report a commit; verified installation provenance is required')
+ }
+}
+
+export async function readMockPrompts(mockUrl: string): Promise<string[]> {
+ const response = await fetch(`${validateMockUrl(mockUrl)}/__e2e__/prompts`, {
+ signal: AbortSignal.timeout(5000), redirect: 'error',
+ })
+ if (!response.ok) {
+ throw new Error(`Mock request witness returned HTTP ${response.status}`)
+ }
+ return z.object({ receivedPrompts: z.array(z.string()) }).parse(await response.json()).receivedPrompts
+}
+
+export async function waitForChatReady(page: Page, timeoutMs = 120_000): Promise<Locator> {
+ const composer = page.locator('[data-slot="composer-root"] [contenteditable="true"], [data-slot="composer-root"] textarea').filter({ visible: true }).first()
+ await composer.waitFor({ state: 'visible', timeout: timeoutMs })
+ await expect(composer).toBeEditable({ timeout: timeoutMs })
+ // Trial input checks hit testing, not merely a non-zero box behind the boot overlay.
+ await composer.click({ trial: true, timeout: timeoutMs })
+ return composer
+}
+
+async function readTranscript(page: Page): Promise<TranscriptMessage[]> {
+ return page.locator('[data-slot="aui_thread-viewport"]:visible [data-message-id][data-role]').evaluateAll(
+ (nodes: Element[]): TranscriptMessage[] => nodes.map((node: Element): TranscriptMessage => ({
+ id: node.getAttribute('data-message-id') ?? '',
+ role: node.getAttribute('data-role') ?? '',
+ text: node.textContent ?? '',
+ streaming: node.getAttribute('data-streaming') === 'true' || Boolean(node.querySelector('[data-message-streaming="true"]')),
+ error: Boolean(node.querySelector('[role="alert"]')),
+ })),
+ )
+}
+
+/** Match an ordered new pair, never a reply carried over from an earlier checkpoint. */
+export function newCompletedPair(
+ messages: TranscriptMessage[], beforeIds: readonly string[], prompt: string,
+): { user: TranscriptMessage; assistant: TranscriptMessage } | null {
+ const userIndex = messages.findIndex((message: TranscriptMessage): boolean =>
+ message.role === 'user' && message.text.includes(prompt) && !beforeIds.includes(message.id))
+ const user = messages[userIndex]
+ const assistant = messages[userIndex + 1]
+ if (!user || !user.id || !assistant?.id || assistant.role !== 'assistant'
+ || beforeIds.includes(assistant.id) || !assistant.text.includes(MOCK_REPLY)
+ || assistant.streaming || assistant.error) {
+ return null
+ }
+ return { user, assistant }
+}
+
+/** Lifecycle belongs to the caller, so this also runs inside the OLD update window. */
+export async function runDesktopChatSmoke(page: Page, options: DesktopChatSmokeOptions): Promise<DesktopChatReceipt> {
+ const { phase, outDir, expectCommit } = options
+ fs.mkdirSync(outDir, { recursive: true })
+ const receiptPath = path.join(outDir, `desktop-chat-${phase}.json`)
+ const screenshot = path.join(outDir, `desktop-chat-${phase}.png`)
+ const prompt = `Hello, can you hear me? Desktop smoke ${phase} ${randomUUID()}`
+ const observe = options.observePrompts ?? ((): Promise<string[]> => readMockPrompts(options.mockUrl))
+ try {
+ const composer = await waitForChatReady(page)
+ const identity = await readChatIdentity(page)
+ if (expectCommit) { assertChatCommit(identity, expectCommit, options.provenanceCommit) }
+ const beforeIds = (await readTranscript(page)).map((message: TranscriptMessage): string => message.id)
+ const before = (await observe()).length
+ await composer.click()
+ await composer.press('ControlOrMeta+A')
+ await composer.pressSequentially(prompt)
+ await composer.press('Enter')
+ await expect.poll(async (): Promise<string> => composer.evaluate((node: HTMLElement): string =>
+ node instanceof HTMLTextAreaElement ? node.value : node.textContent ?? ''),
+ { timeout: 15_000, message: 'The submitted draft must clear before the idle control proves completion' }).toBe('')
+ let witnessIndex = -1
+ let receivedPrompt = ''
+ await expect.poll(async (): Promise<boolean> => {
+ const prompts = await observe()
+ witnessIndex = prompts.findIndex((text: string, index: number): boolean => index >= before && text.includes(prompt))
+ receivedPrompt = prompts[witnessIndex] ?? ''
+ return witnessIndex >= before
+ }, { timeout: 90_000, message: 'The mock must receive this checkpoint prompt after the send' }).toBe(true)
+ await expect.poll(async (): Promise<boolean> => newCompletedPair(await readTranscript(page), beforeIds, prompt) !== null,
+ { timeout: 90_000, message: 'A new completed assistant reply must follow the new user message' }).toBe(true)
+ // An empty idle composer offers voice chat; older desktops retain Send.
+ // Stop and the streaming marker must settle even when all reply text arrived.
+ await expect(page.locator('[data-slot="composer-root"] button[aria-label="Start voice conversation"]:visible, [data-slot="composer-root"] button[type="submit"][aria-label="Send"]:visible')).toBeVisible({ timeout: 90_000 })
+ const pair = newCompletedPair(await readTranscript(page), beforeIds, prompt)
+ if (!pair) {
+ throw new Error('New transcript pair disappeared before the turn completed')
+ }
+ await page.screenshot({ path: screenshot })
+ const receipt: DesktopChatReceipt = {
+ status: 'passed', phase, expectedCommit: expectCommit ?? null, identity, provenanceCommit: options.provenanceCommit ?? null, prompt,
+ requestWitness: { index: witnessIndex, prompt: receivedPrompt, before },
+ transcript: { beforeIds, ...pair }, turnComplete: true, screenshot,
+ }
+ fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`)
+ return receipt
+ } catch (error) {
+ await page.screenshot({ path: screenshot }).catch((): void => {})
+ fs.writeFileSync(receiptPath, `${JSON.stringify({ status: 'failed', phase, expectedCommit: expectCommit ?? null, prompt, error: String(error) }, null, 2)}\n`)
+ throw error
+ }
+}
\ No newline at end of file
diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.ts
new file mode 100644
index 00000000000..add77d7673a
--- /dev/null
+++ b/tests-js/scripts/desktop-smoke-process.ts
@@ -0,0 +1,157 @@
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+
+import { z } from 'zod'
+
+export interface NativeProcess {
+ pid: number
+ parentPid: number
+ executable: string
+ command: string
+ sourceRoot?: string
+ cwd?: string
+}
+
+export function within(root: string, candidate: string): boolean {
+ const relative = path.relative(fs.realpathSync(root), fs.realpathSync(candidate))
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+}
+
+function nativeText(command: string, args: string[]): string {
+ return execFileSync(command, args, { encoding: 'utf8', timeout: 30_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+}
+
+/** Call only after binding the live listener (and bundled resources) to root. */
+export function readInstallationCommit(root: string, origin: 'source' | 'bundled'): string {
+ const commit = origin === 'source' ? nativeText('git', ['-C', root, 'rev-parse', 'HEAD'])
+ : z.object({ payload: z.literal('bundled'), commit: z.string() }).parse(
+ JSON.parse(fs.readFileSync(path.join(root, '..', 'install-stamp.json'), 'utf8')),
+ ).commit
+ return z.string().regex(/^[0-9a-f]{40}$/).parse(commit)
+}
+
+const windowsProcesses = z.array(z.object({
+ ProcessId: z.number(), ParentProcessId: z.number(), ExecutablePath: z.string().nullable(), CommandLine: z.string().nullable(),
+}))
+
+export function readNativeProcesses(): NativeProcess[] {
+ if (process.platform === 'win32') {
+ const rows = windowsProcesses.parse(JSON.parse(nativeText('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
+ '[Console]::OutputEncoding = [Text.UTF8Encoding]::new(); ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,ExecutablePath,CommandLine)'])))
+ return rows.map((row): NativeProcess => ({ pid: row.ProcessId, parentPid: row.ParentProcessId, executable: row.ExecutablePath ?? '', command: row.CommandLine ?? '' }))
+ }
+ const table = nativeText('ps', ['-axo', 'pid=,ppid=,comm='])
+ return table.split('\n').flatMap((line: string): NativeProcess[] => {
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line)
+ if (!match) {
+ return []
+ }
+ return [{ pid: Number(match[1]), parentPid: Number(match[2]), executable: match[3], command: '' }]
+ })
+}
+
+export function descendants(processes: NativeProcess[], parentPid: number): NativeProcess[] {
+ const owned = new Set<number>([parentPid])
+ for (;;) {
+ const priorSize = owned.size
+ for (const child of processes) {
+ if (owned.has(child.parentPid)) {
+ owned.add(child.pid)
+ }
+ }
+ if (priorSize === owned.size) {
+ return processes.filter((child: NativeProcess): boolean => child.pid !== parentPid && owned.has(child.pid))
+ }
+ }
+}
+
+function linuxListeningPid(port: number, candidates: NativeProcess[]): number[] {
+ const inodes = new Set<string>()
+ for (const filename of ['/proc/net/tcp', '/proc/net/tcp6']) {
+ for (const line of fs.readFileSync(filename, 'utf8').split('\n').slice(1)) {
+ const fields = line.trim().split(/\s+/)
+ if (fields[3] === '0A' && Number.parseInt(fields[1].split(':')[1], 16) === port) {
+ inodes.add(`socket:[${fields[9]}]`)
+ }
+ }
+ }
+ return candidates.filter((candidate: NativeProcess): boolean => {
+ try {
+ const dir = `/proc/${candidate.pid}/fd`
+ return fs.readdirSync(dir).some((fd: string): boolean => {
+ try { return inodes.has(fs.readlinkSync(path.join(dir, fd))) } catch { return false }
+ })
+ } catch { return false }
+ }).map((candidate: NativeProcess): number => candidate.pid)
+}
+
+/** Identify the actual listener, not a healthy helper or a command recorded before spawn. */
+export function localBackendProcess(port: number, electronPid: number): NativeProcess {
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
+ throw new Error('Invalid backend port')
+ }
+ const children = descendants(readNativeProcesses(), electronPid)
+ let pids: number[]
+ if (process.platform === 'win32') {
+ pids = z.array(z.number()).parse(JSON.parse(nativeText('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
+ `ConvertTo-Json -Compress -InputObject @((Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction Stop).OwningProcess | Sort-Object -Unique)`])))
+ } else if (process.platform === 'darwin') {
+ pids = nativeText('/usr/sbin/lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fp']).split('\n')
+ .filter((line: string): boolean => /^p\d+$/.test(line)).map((line: string): number => Number(line.slice(1)))
+ } else {
+ pids = linuxListeningPid(port, children)
+ }
+ const matches = children.filter((child: NativeProcess): boolean => pids.includes(child.pid))
+ if (matches.length !== 1) {
+ throw new Error(`Expected one Electron-owned backend listener on port ${port}; found ${matches.length}`)
+ }
+ const backend = matches[0]
+ if (process.platform === 'linux') {
+ backend.executable = fs.readlinkSync(`/proc/${backend.pid}/exe`)
+ backend.cwd = fs.readlinkSync(`/proc/${backend.pid}/cwd`)
+ backend.command = fs.readFileSync(`/proc/${backend.pid}/cmdline`, 'utf8').split('\0').filter(Boolean).map((arg: string): string => JSON.stringify(arg)).join(' ')
+ backend.sourceRoot = fs.readFileSync(`/proc/${backend.pid}/environ`, 'utf8').split('\0')
+ .find((entry: string): boolean => entry.startsWith('HERMES_PYTHON_SRC_ROOT='))?.slice('HERMES_PYTHON_SRC_ROOT='.length)
+ } else if (process.platform === 'darwin') {
+ backend.command = nativeText('ps', ['-p', String(backend.pid), '-o', 'args='])
+ backend.cwd = nativeText('/usr/sbin/lsof', ['-a', '-p', String(backend.pid), '-d', 'cwd', '-Fn'])
+ .split('\n').find((line: string): boolean => line.startsWith('n'))?.slice(1)
+ backend.sourceRoot = /(?:^|\s)HERMES_PYTHON_SRC_ROOT=(.*?)(?=\s+[A-Za-z_][A-Za-z_0-9]*=|$)/
+ .exec(nativeText('ps', ['eww', '-p', String(backend.pid), '-o', 'args=']))?.[1]
+ }
+ return backend
+}
+
+export function assertBackendOrigin(backend: NativeProcess, root: string, origin: 'source' | 'bundled'): void {
+ if (origin === 'bundled') {
+ if (path.basename(root) !== 'agent-payload' || !within(root, backend.executable)) {
+ throw new Error('Bundled backend listener is not running the installed agent-payload interpreter')
+ }
+ return
+ }
+ // A Python -m entry has no source path in argv. Its live import root is
+ // either the captured editable root (Nix) or the process's working directory.
+ const moduleLaunch = /(?:^|\s)"?-m"?\s+"?hermes_cli\.main"?(?:\s|$)/.test(backend.command)
+ && /^python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?$/i.test(path.basename(backend.executable))
+ const importRoot = backend.sourceRoot || backend.cwd
+ if (moduleLaunch && importRoot) {
+ if (fs.realpathSync(importRoot) !== fs.realpathSync(root)) {
+ throw new Error('Source backend listener imports a different source tree')
+ }
+ return
+ }
+ // PM's Windows .cmd fallback encodes the installation-bound bootstrap;
+ // POSIX launchers pass that same script directly as Python's -c argument.
+ const encoded = /base64\.b64decode\('([A-Za-z0-9+/=]+)'\)/.exec(backend.command)?.[1]
+ const command = encoded ? Buffer.from(encoded, 'base64').toString('utf8') : backend.command
+ // Source venvs may resolve to system Python; their entry script still lives in the installation.
+ const spellings = [root, fs.realpathSync(root)].flatMap((value: string): string[] => [value, JSON.stringify(value).slice(1, -1)])
+ const fromInstall = spellings.some((value: string): boolean => {
+ const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ return new RegExp(`(?:^|[\\s"'])${escaped}(?:[/\\\\]|[\\s"']|$)`, process.platform === 'win32' ? 'i' : '').test(command)
+ })
+ if (!fromInstall) {
+ throw new Error('Source backend listener command does not name the expected installed source tree')
+ }
+}
\ No newline at end of file
diff --git a/tests-js/scripts/desktop-smoke.test.ts b/tests-js/scripts/desktop-smoke.test.ts
new file mode 100644
index 00000000000..505e40dccb6
--- /dev/null
+++ b/tests-js/scripts/desktop-smoke.test.ts
@@ -0,0 +1,197 @@
+import { spawn, spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import yaml from 'js-yaml'
+import { expect, test } from 'vitest'
+
+import { resolveSmokeLaunch, runInstalledDesktopSmoke, smokeEnvironment } from '../../tests/install/e2e-assets/desktop-smoke.ts'
+
+import { assertChatCommit, newCompletedPair, readMockPrompts, type TranscriptMessage } from './desktop-chat-smoke.ts'
+import { assertBackendOrigin, localBackendProcess, readInstallationCommit } from './desktop-smoke-process.ts'
+import { writeEnvFile, writeMockProviderConfig } from './mock-provider-config.ts'
+import { MOCK_REPLY, startMockServer } from './mock-server.ts'
+
+test('one server owns inference and a fresh, per-server prompt witness', async (): Promise<void> => {
+ const first = await startMockServer()
+ const second = await startMockServer()
+ try {
+ expect(await readMockPrompts(first.url)).toEqual([])
+ const prompt = 'unique request from the OLD checkpoint'
+ const response = await fetch(`${first.url}/v1/chat/completions`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ model: 'mock-model', messages: [{ role: 'user', content: prompt }] }),
+ })
+ expect(await response.json()).toMatchObject({ choices: [{ message: { content: MOCK_REPLY } }] })
+ expect(await readMockPrompts(first.url)).toEqual(first.receivedPrompts)
+ expect(first.receivedPrompts).toEqual([prompt])
+ await fetch(`${first.url}/v1/chat/completions`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ messages: [{ role: 'user', content: [{ type: 'text', text: 'NEW multipart prompt' }] }] }),
+ })
+ expect(await readMockPrompts(first.url)).toEqual([prompt, 'NEW multipart prompt'])
+ expect(await readMockPrompts(second.url)).toEqual([])
+ } finally {
+ await first.close()
+ await second.close()
+ }
+ await expect(readMockPrompts(first.url)).rejects.toThrow()
+})
+
+test('provider reconfiguration preserves feed, plugins, history and explicit fixture options', (): void => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-config-'))
+ try {
+ const feed = { desktop_feed_base_url: 'http://127.0.0.1:8123/feed' }
+ fs.writeFileSync(path.join(home, 'config.yaml'), yaml.dump({ updates: feed, plugins: { witness: true }, model: { temperature: 0.7 } }))
+ fs.writeFileSync(path.join(home, 'state.db'), 'history witness')
+ fs.writeFileSync(path.join(home, '.env'), 'OTHER_TEST_VALUE=kept\nMOCK_API_KEY=old\n')
+ writeMockProviderConfig(home, 'http://127.0.0.1:9000')
+ writeEnvFile(home)
+ writeMockProviderConfig(home, 'http://127.0.0.1:9001', 'interim_assistant_messages: true', 'approvals:\n mode: smart', 12000)
+ writeEnvFile(home)
+ expect(yaml.load(fs.readFileSync(path.join(home, 'config.yaml'), 'utf8'))).toMatchObject({
+ updates: feed, plugins: { witness: true },
+ model: { provider: 'mock', temperature: 0.7, context_length: 12000 },
+ providers: { mock: { api: 'http://127.0.0.1:9001/v1', context_length: 64000 } },
+ auxiliary: { title_generation: { enabled: false } }, approvals: { mode: 'smart' }, display: { interim_assistant_messages: true },
+ })
+ expect(fs.readFileSync(path.join(home, '.env'), 'utf8')).toBe('OTHER_TEST_VALUE=kept\nMOCK_API_KEY=e2e-mock-key\n')
+ expect(fs.readFileSync(path.join(home, 'state.db'), 'utf8')).toBe('history witness')
+ } finally { fs.rmSync(home, { recursive: true, force: true }) }
+})
+
+test('OLD history, partial/wrong replies, active streams and errors cannot satisfy NEW', (): void => {
+ const message = (id: string, role: string, text: string): TranscriptMessage => ({ id, role, text, streaming: false, error: false })
+ const old = [message('old-user', 'user', 'old'), message('old-reply', 'assistant', MOCK_REPLY)]
+ const before = old.map((row: TranscriptMessage): string => row.id)
+ const user = message('new-user', 'user', 'new nonce')
+ const reply = message('new-reply', 'assistant', MOCK_REPLY)
+ for (const rows of [old, [...old, user], [...old, user, { ...reply, id: 'old-reply' }],
+ [...old, user, { ...reply, text: 'boot chain is working' }], [...old, user, { ...reply, text: 'wrong' }],
+ [...old, user, { ...reply, streaming: true }], [...old, user, { ...reply, error: true }],
+ [...old, user, message('other-user', 'user', 'unrelated'), reply]]) {
+ expect(newCompletedPair(rows, before, 'new nonce')).toBeNull()
+ }
+ expect(newCompletedPair([...old, user, reply], before, 'new nonce')).toEqual({ user, assistant: reply })
+})
+
+test.runIf(process.platform !== 'win32')('shell wrapper exports the live witness URL without losing journey config', (): void => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-wrapper-'))
+ const assets = path.resolve(import.meta.dirname, '../../tests/install/e2e-assets')
+ try {
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'updates:\n desktop_feed_base_url: http://127.0.0.1:1234/feed\n')
+ const result = spawnSync('bash', ['-c', `
+ set -eu
+ ok() { printf '%s\\n' "$*"; }
+ fail() { printf '%s\\n' "$*" >&2; exit 1; }
+ log_group() { :; }
+ source "$ASSETS/mock-provider.sh"
+ trap mock_stop EXIT
+ mock_start "$HERMES_HOME"
+ node --input-type=module -e 'const r=await fetch(process.env.HERMES_E2E_MOCK_URL+"/__e2e__/prompts"); if(!r.ok || (await r.json()).receivedPrompts.length!==0)process.exit(1)'
+ `], { env: { ...process.env, ASSETS: assets, HERMES_HOME: home, LOG_DIR: home }, encoding: 'utf8', timeout: 20_000 })
+ expect(result.status, result.stdout + result.stderr).toBe(0)
+ expect(yaml.load(fs.readFileSync(path.join(home, 'config.yaml'), 'utf8'))).toMatchObject({ updates: { desktop_feed_base_url: 'http://127.0.0.1:1234/feed' } })
+ } finally { fs.rmSync(home, { recursive: true, force: true }) }
+})
+
+test.runIf(process.platform === 'linux')('origin proof finds the live child listener and rejects a package impostor', async (): Promise<void> => {
+ const child = spawn(process.execPath, ['-e', 'const s=require("node:net").createServer();s.listen(0,"127.0.0.1",()=>console.log(s.address().port))'], { stdio: ['ignore', 'pipe', 'pipe'] })
+ try {
+ const port = await new Promise<number>((resolve, reject): void => {
+ child.once('error', reject)
+ child.stdout.once('data', (data: Buffer): void => resolve(Number(data.toString().trim())))
+ })
+ const backend = localBackendProcess(port, process.pid)
+ expect(backend.pid).toBe(child.pid)
+ expect(backend.executable).toBe(fs.realpathSync(process.execPath))
+ expect((): void => assertBackendOrigin(backend, os.tmpdir(), 'bundled')).toThrow('agent-payload')
+ expect((): void => assertBackendOrigin(backend, os.tmpdir(), 'source')).toThrow('source tree')
+ expect((): void => { localBackendProcess(port, child.pid!) }).toThrow('found 0')
+ } finally { child.kill(); await new Promise<void>((resolve): void => { child.once('exit', (): void => resolve()) }) }
+})
+
+test('source launch restores only an explicitly captured exact editable root', (): void => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-source-'))
+ const specPath = path.join(home, 'launch.json')
+ const childRoot = path.join(home, 'child')
+ fs.mkdirSync(childRoot)
+ const options = { exe: process.execPath, root: home, origin: 'source' as const, home,
+ 'user-data': path.join(home, 'user-data'), out: home, phase: 'old' as const,
+ 'expect-commit': 'a'.repeat(40), 'launch-spec': specPath }
+ const writeSpec = (sourceRoot: string): void => {
+ // oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- This is the existing launch-capture wire field.
+ fs.writeFileSync(specPath, JSON.stringify({ argv: [process.execPath], cwd: home, matchedShape: 'packaged',
+ env: { HERMES_DESKTOP_PYTHON: process.execPath, HERMES_PYTHON_SRC_ROOT: sourceRoot } }))
+ }
+ try {
+ writeSpec(home)
+ expect(resolveSmokeLaunch(options).env.HERMES_PYTHON_SRC_ROOT).toBe(home)
+ for (const wrong of [childRoot, path.dirname(home), 'relative-root']) {
+ writeSpec(wrong)
+ expect((): void => { resolveSmokeLaunch(options) }).toThrow('expected source installation')
+ }
+ expect(smokeEnvironment({ HERMES_PYTHON_SRC_ROOT: home }, home, options['user-data']).HERMES_PYTHON_SRC_ROOT).toBeUndefined()
+ } finally { fs.rmSync(home, { recursive: true, force: true }) }
+})
+
+test.runIf(process.platform === 'linux')('module-launched source listener proves its import root without an argv path', async (): Promise<void> => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-module-'))
+ fs.mkdirSync(path.join(home, 'hermes_cli'))
+ fs.writeFileSync(path.join(home, 'hermes_cli', '__init__.py'), '')
+ fs.writeFileSync(path.join(home, 'hermes_cli', 'main.py'), 'import socket, time\ns = socket.socket()\ns.bind(("127.0.0.1", 0))\ns.listen()\nprint(s.getsockname()[1], flush=True)\ntime.sleep(60)\n')
+ const child = spawn('python3', ['-m', 'hermes_cli.main'], {
+ cwd: home, env: { ...process.env, HERMES_PYTHON_SRC_ROOT: home }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ try {
+ const port = await new Promise<number>((resolve, reject): void => {
+ child.once('error', reject)
+ child.stdout.once('data', (data: Buffer): void => resolve(Number(data.toString().trim())))
+ })
+ const backend = localBackendProcess(port, process.pid)
+ expect(backend.sourceRoot).toBe(home)
+ expect(backend.cwd).toBe(home)
+ expect((): void => assertBackendOrigin(backend, home, 'source')).not.toThrow()
+ expect((): void => assertBackendOrigin({ ...backend, sourceRoot: undefined }, home, 'source')).not.toThrow()
+ expect((): void => assertBackendOrigin(backend, os.tmpdir(), 'source')).toThrow('source tree')
+ } finally {
+ child.kill()
+ await new Promise<void>((resolve): void => { child.once('exit', (): void => resolve()) })
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+})
+
+test('historical identity needs verified provenance and never overrides an app-reported mismatch', (): void => {
+ const expected = 'a'.repeat(40)
+ const identity = { appVersion: 'historical', commit: null, hermesRoot: '/unused', platform: process.platform }
+ expect((): void => assertChatCommit(identity, expected)).toThrow('provenance is required')
+ expect((): void => assertChatCommit(identity, expected, expected)).not.toThrow()
+ expect((): void => assertChatCommit(identity, expected, 'b'.repeat(40))).toThrow('does not equal expected')
+ expect((): void => assertChatCommit({ ...identity, commit: 'b'.repeat(40) }, expected, expected)).toThrow('Running commit')
+ expect((): void => assertChatCommit({ ...identity, commit: expected }, expected)).not.toThrow()
+ const resources = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-stamp-'))
+ const payload = path.join(resources, 'agent-payload')
+ fs.mkdirSync(payload)
+ try {
+ fs.writeFileSync(path.join(resources, 'install-stamp.json'), JSON.stringify({ payload: 'bundled', commit: expected }))
+ expect(readInstallationCommit(payload, 'bundled')).toBe(expected)
+ fs.writeFileSync(path.join(resources, 'install-stamp.json'), JSON.stringify({ payload: 'bundled', commit: 'malformed' }))
+ expect((): void => { readInstallationCommit(payload, 'bundled') }).toThrow()
+ } finally { fs.rmSync(resources, { recursive: true, force: true }) }
+})
+
+test('driver strips caller secrets and records missing executables as failure without launching', async (): Promise<void> => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-admission-'))
+ try {
+ const env = smokeEnvironment({ PATH: '/usr/bin', DISPLAY: ':1', OPENAI_API_KEY: 'secret', HERMES_DESKTOP_BOOT_FAKE: '1',
+ HERMES_DESKTOP_HERMES_ROOT: '/wrong', PYTHONPATH: '/wrong', NODE_OPTIONS: '--inspect', HERMES_HOME: '/wrong' }, home, path.join(home, 'user-data'))
+ expect(env).toMatchObject({ PATH: '/usr/bin', DISPLAY: ':1', HERMES_HOME: home })
+ for (const key of ['OPENAI_API_KEY', 'HERMES_DESKTOP_BOOT_FAKE', 'HERMES_DESKTOP_HERMES_ROOT', 'PYTHONPATH', 'NODE_OPTIONS']) {
+ expect(env[key]).toBeUndefined()
+ }
+ await expect(runInstalledDesktopSmoke({ exe: path.join(home, 'missing'), root: home, origin: 'bundled', home,
+ 'user-data': path.join(home, 'user-data'), out: home, phase: 'installed', 'expect-commit': 'a'.repeat(40) })).rejects.toThrow()
+ expect(JSON.parse(fs.readFileSync(path.join(home, 'desktop-chat-installed.json'), 'utf8'))).toMatchObject({ status: 'failed', origin: 'bundled' })
+ } finally { fs.rmSync(home, { recursive: true, force: true }) }
+})
\ No newline at end of file
diff --git a/tests-js/scripts/mock-provider-config.ts b/tests-js/scripts/mock-provider-config.ts
new file mode 100644
index 00000000000..0b0c3e36581
--- /dev/null
+++ b/tests-js/scripts/mock-provider-config.ts
@@ -0,0 +1,75 @@
+import fs from 'node:fs'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+import yaml from 'js-yaml'
+import { z } from 'zod'
+
+const section = z.object({}).passthrough()
+const configSchema = z.object({
+ model: section.optional(),
+ providers: section.optional(),
+ auxiliary: z.object({ title_generation: section.optional() }).passthrough().optional(),
+ approvals: section.optional(),
+ display: section.optional(),
+}).passthrough()
+
+export function validateMockUrl(value: string): string {
+ const url = new URL(value)
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || !url.port
+ || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
+ throw new Error('Mock URL must be a credential-free http://127.0.0.1:PORT origin')
+ }
+ return url.origin
+}
+
+/** Merge only test-owned settings. Do not replace the update feed or plugins. */
+export function writeMockProviderConfig(
+ hermesHome: string,
+ mockUrl: string,
+ extraDisplayConfig?: string,
+ extraConfig?: string,
+ modelContextLength?: number,
+): void {
+ const url = validateMockUrl(mockUrl)
+ fs.mkdirSync(hermesHome, { recursive: true })
+ const configPath = path.join(hermesHome, 'config.yaml')
+ const config = configSchema.parse(fs.existsSync(configPath) ? yaml.load(fs.readFileSync(configPath, 'utf8')) ?? {} : {})
+ const extra = configSchema.parse(extraConfig ? yaml.load(extraConfig) ?? {} : {})
+ const display = section.parse(extraDisplayConfig ? yaml.load(extraDisplayConfig) ?? {} : {})
+ const merged = {
+ ...config,
+ model: { ...config.model, default: 'mock-model', provider: 'mock', context_length: modelContextLength ?? 64000 },
+ providers: {
+ ...config.providers,
+ mock: { api: `${url}/v1`, name: 'Mock', api_mode: 'chat_completions', key_env: 'MOCK_API_KEY', models: { 'mock-model': {} }, context_length: 64000 },
+ },
+ auxiliary: { ...config.auxiliary, title_generation: { ...config.auxiliary?.title_generation, enabled: false } },
+ approvals: { ...config.approvals, mode: 'off' },
+ ...extra,
+ }
+ if (extraDisplayConfig) {
+ merged.display = { ...config.display, ...extra.display, ...display }
+ }
+ fs.writeFileSync(configPath, yaml.dump(merged), 'utf8')
+}
+
+/** Keep journey-owned entries, replacing only the inert test key. */
+export function writeEnvFile(hermesHome: string, apiKey = 'e2e-mock-key'): void {
+ if (!/^[\w-]+$/.test(apiKey)) {
+ throw new Error('Mock key must be an inert single-line test value')
+ }
+ const envPath = path.join(hermesHome, '.env')
+ const prior = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : ''
+ const lines = prior.split(/\r?\n/).filter((line: string): boolean => !/^\s*(?:export\s+)?MOCK_API_KEY\s*=/.test(line))
+ fs.writeFileSync(envPath, `${lines.join('\n').trimEnd()}\nMOCK_API_KEY=${apiKey}\n`, { mode: 0o600 })
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const [home, url] = process.argv.slice(2)
+ if (!home || !url || !path.isAbsolute(home)) {
+ throw new Error('usage: node mock-provider-config.ts ABSOLUTE_HERMES_HOME MOCK_URL')
+ }
+ writeMockProviderConfig(home, url)
+ writeEnvFile(home)
+}
\ No newline at end of file
diff --git a/tests-js/scripts/mock-server.ts b/tests-js/scripts/mock-server.ts
index 6dffd2cf0f3..7c8a476837f 100644
--- a/tests-js/scripts/mock-server.ts
+++ b/tests-js/scripts/mock-server.ts
@@ -27,6 +27,10 @@ import os from 'node:os'
import nodePath from 'node:path'
import { pathToFileURL } from 'node:url'
+import { z } from 'zod'
+
+import { writeEnvFile, writeMockProviderConfig } from './mock-provider-config.ts'
+
/** A canned assistant reply used for every chat completion request. */
export const MOCK_REPLY = 'Hello from the mock inference server! The full boot chain is working.'
@@ -432,6 +436,13 @@ export function startMockServer(options: MockServerOptions = {}): Promise<MockSe
return
}
+ if (req.method === 'GET' && req.url === '/__e2e__/prompts') {
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
+ res.end(JSON.stringify({ receivedPrompts }))
+
+ return
+ }
+
// GET /v1/models — return a single fake model.
if (req.method === 'GET' && req.url === '/v1/models') {
res.writeHead(200, { 'Content-Type': 'application/json' })
@@ -475,6 +486,10 @@ export function startMockServer(options: MockServerOptions = {}): Promise<MockSe
if (typeof lastUserMessage?.content === 'string') {
receivedPrompts.push(lastUserMessage.content)
+ } else if (Array.isArray(lastUserMessage?.content)) {
+ const parts = z.array(z.object({ type: z.string(), text: z.string().optional() })).parse(lastUserMessage.content)
+ receivedPrompts.push(parts.filter((part): boolean => part.type === 'text')
+ .map((part): string => part.text ?? '').join('\n'))
}
const stream = parsed.stream === true
@@ -1071,29 +1086,6 @@ function createDevSandbox(): DevSandbox {
}
}
-/** Write a config.yaml + .env that pre-configure the mock provider. */
-function writeMockConfig(hermesHome: string, mockUrl: string): void {
- fs.writeFileSync(
- nodePath.join(hermesHome, 'config.yaml'),
- `# Auto-generated by dev-mock
-model:
- default: mock-model
- provider: mock
-providers:
- mock:
- api: ${mockUrl}/v1
- name: Mock
- api_mode: chat_completions
- key_env: MOCK_API_KEY
- models:
- mock-model: {}
- context_length: 64000
-`,
- 'utf8',
- )
- fs.writeFileSync(nodePath.join(hermesHome, '.env'), 'MOCK_API_KEY=e2e-mock-key\n', 'utf8')
-}
-
/** Resolve the Electron binary: the repo's own install, then PATH. */
function findElectron(repoRoot: string): string {
const local = nodePath.join(repoRoot, 'node_modules', 'electron', 'dist', 'electron')
@@ -1130,7 +1122,8 @@ async function runDevLaunch(): Promise<void> {
console.log(` Mock server: ${mock.url}`)
const sandbox = createDevSandbox()
- writeMockConfig(sandbox.hermesHome, mock.url)
+ writeMockProviderConfig(sandbox.hermesHome, mock.url)
+ writeEnvFile(sandbox.hermesHome)
console.log(` HERMES_HOME: ${sandbox.hermesHome}`)
const electronBin = findElectron(repoRoot)
diff --git a/tests-js/tsconfig.json b/tests-js/tsconfig.json
index 61bea60736a..a32388148c5 100644
--- a/tests-js/tsconfig.json
+++ b/tests-js/tsconfig.json
@@ -3,6 +3,7 @@
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
diff --git a/tests/ci/test_commit_build_staging.py b/tests/ci/test_commit_build_staging.py
index 44bc8253fe9..3009dfb2cb8 100644
--- a/tests/ci/test_commit_build_staging.py
+++ b/tests/ci/test_commit_build_staging.py
@@ -23,7 +23,7 @@ def step_script(job, name):
return next(step['run'] for step in _workflow()['jobs'][job]['steps'] if step.get('name') == name)
-def shell_step(tmp_path, r2_server, job, name, env):
+def shell_step(tmp_path, r2_server, job, name, env, *, script=None):
helper = tmp_path / 'bin'
helper.mkdir(exist_ok=True)
driver = helper / 'python-driver.py'
@@ -34,11 +34,12 @@ def shell_step(tmp_path, r2_server, job, name, env):
f'r2.s3_endpoint=lambda _: "http://127.0.0.1:{r2_server.server_port}"\n'
'args=sys.argv[1:]\n'
'assert args[:2] == ["-m", "scripts.releases.handoff"] or '
- 'args[:1] == ["scripts/render-builds-table.py"] or args == ["-"], args\n'
+ 'args[:1] in (["scripts/render-builds-table.py"], ["-"]), args\n'
'if args[:1] == ["-m"]:\n'
' sys.argv=args[1:]\n'
' runpy.run_module(args[1],run_name="__main__")\n'
- 'elif args == ["-"]:\n'
+ 'elif args[:1] == ["-"]:\n'
+ ' sys.argv=args\n'
' exec(compile(sys.stdin.read(), "workflow-inline", "exec"))\n'
'else:\n'
' sys.argv=args\n'
@@ -50,11 +51,11 @@ def shell_step(tmp_path, r2_server, job, name, env):
command.write_text(f'#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(driver))} "$@"\n',
encoding='utf-8', newline='\n')
command.chmod(0o755)
- script = tmp_path / 'step.sh'
- script.write_text(step_script(job, name), encoding='utf-8', newline='\n')
+ script_file = tmp_path / 'step.sh'
+ script_file.write_text(script if script is not None else step_script(job, name), encoding='utf-8', newline='\n')
environment = _child_env(**env)
environment['PATH'] = str(helper) + os.pathsep + environment['PATH']
- return subprocess.run([_BASH, '-e', '-o', 'pipefail', str(script)], cwd=tmp_path,
+ return subprocess.run([_BASH, '-e', '-o', 'pipefail', str(script_file)], cwd=tmp_path,
env=environment, capture_output=True, text=True, encoding='utf-8', timeout=60)
@@ -84,7 +85,7 @@ def test_failed_commit_summary_publishes_downloads_or_run_links(tmp_path, r2_ser
result = shell_step(tmp_path, r2_server, 'commit-builds-summary',
'Render the full expected-binary matrix', env)
assert result.returncode == 0, result.stdout + result.stderr
- text = summary.read_text(encoding='utf-8')
+ text = summary.read_text(encoding='utf-8-sig')
page_key = f'releases/commit/{sha}/index.html'
with urlopen(f'{base}/{page_key}', timeout=5) as response:
page = response.read().decode()
@@ -105,7 +106,7 @@ def test_failed_commit_summary_publishes_downloads_or_run_links(tmp_path, r2_ser
for line in text.splitlines():
if 'Not built' in line:
assert f'[View build run]({run_url})' in line and base not in line
- elif 'Linux' in line:
+ elif line.startswith('| Linux'):
assert 'Disabled' in line and '](' not in line
assert all(key.startswith(f'releases/commit/{sha}/') for key in r2_server.store)
for name in ('build-win32', 'build-darwin'):
@@ -138,7 +139,7 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm
('build-darwin-commit', 'Stage macOS packages and feed inputs to R2', 'darwin-x64', [
'HermesBundled-0.33.0-mac-x64.dmg', 'HermesBundled-0.33.0-mac-x64.zip',
'HermesBundled-0.33.0-mac-x64.zip.blockmap']),
- ('publish-win32-updater', 'Stage universal bundles to R2', 'windows-universal', [
+ ('assemble-win32-bundle', 'Stage universal bundles to R2', 'windows-universal', [
'HermesBundled-0.33.0.0-win.msixbundle']),
]
artifact_keys = set()
@@ -174,13 +175,13 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm
summary = tmp_path / 'summary.md'
summary_env = {**env, 'GITHUB_STEP_SUMMARY': str(summary), 'RELEASE_NEEDS': json.dumps({
'validate': {'result': 'success'}, 'build-win32': {'result': 'success'},
- 'build-darwin': {'result': 'success'}, 'publish-win32-updater': {'result': 'success'},
+ 'build-darwin': {'result': 'success'}, 'assemble-win32-bundle': {'result': 'success'},
'termux-deb': {'result': 'success'}, 'build-linux': {'result': 'success'},
})}
result = shell_step(tmp_path, r2_server, 'commit-builds-summary',
'Render the full expected-binary matrix', summary_env)
assert result.returncode == 0, result.stdout + result.stderr
- text = summary.read_text(encoding='utf-8')
+ text = summary.read_text(encoding='utf-8-sig')
links = re.findall(r'\]\((http[^)]+)\)', text)
# Blockmaps are receipt inputs; every other staged product has a download row.
expected = {f'{base}/{quote(key, safe="/")}' for key in artifact_keys if not key.endswith('.blockmap')}
@@ -193,7 +194,7 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm
page_key = f'releases/commit/{sha}/index.html'
page = r2_server.store[page_key][0].decode()
assert all(f'href="{url}"' in page for url in expected)
- assert 'Store' not in page and 'Linux x64' in page and 'Linux ARM64' in page
+ assert 'Store-' not in page and 'Linux x64' in page and 'Linux ARM64' in page
assert all(key.startswith(f'releases/commit/{sha}/') for key in r2_server.store)
assert not any(method == 'DELETE' for method, _, _ in r2_server.requests)
@@ -203,7 +204,7 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm
failed = shell_step(tmp_path, r2_server, 'commit-builds-summary',
'Render the full expected-binary matrix', summary_env)
assert failed.returncode != 0
- assert summary.read_text(encoding='utf-8') == text
+ assert summary.read_text(encoding='utf-8-sig') == text
assert r2_server.store[page_key][0].decode() == page
r2_server.store[receipt_key] = original
@@ -215,4 +216,4 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm
incomplete = shell_step(tmp_path, r2_server, 'commit-builds-summary',
'Render the full expected-binary matrix', summary_env)
assert incomplete.returncode == 0, incomplete.stdout + incomplete.stderr
- assert 'failed: build-darwin' in summary.read_text(encoding='utf-8')
+ assert 'failed: build-darwin' in summary.read_text(encoding='utf-8-sig')
diff --git a/tests/ci/test_desktop_bundle_smoke.py b/tests/ci/test_desktop_bundle_smoke.py
new file mode 100644
index 00000000000..7db818b3c4a
--- /dev/null
+++ b/tests/ci/test_desktop_bundle_smoke.py
@@ -0,0 +1,351 @@
+"""Replay artifact handoffs and publication; evaluate the actual workflow gates."""
+import copy
+import hashlib
+import itertools
+import json
+import re
+import shutil
+import subprocess
+import xml.etree.ElementTree as ET
+import zipfile
+from pathlib import Path
+
+import hermes_yaml
+import pytest
+
+from tests.ci.test_commit_build_staging import ROOT, shell_step
+from tests.ci.test_desktop_release_tag_admission import _BASH, _child_env, _workflow
+from tests.scripts.test_release_r2 import r2_server # noqa: F401
+
+SHA = 'a' * 40
+TAG = 'v0.28.0-canary.20260818101010'
+
+
+def smoke_workflow():
+ return hermes_yaml.safe_load((ROOT / '.github/workflows/desktop-bundle-smoke.yml').read_text(encoding='utf-8-sig'))
+
+
+def gate(expression, inputs, needs, *, cancelled=False, job_if=True):
+ """Evaluate the workflow's boolean subset, including Actions' implicit success.
+
+ This is not a scheduler simulation; native Actions still owns cancellation
+ and skipped-ancestor propagation. Requiring a status function prevents an
+ implicit success() from suppressing consumers of the skipped trust branch.
+ """
+ expression = expression.strip().removeprefix('${{').removesuffix('}}').strip()
+ if job_if and not re.search(r'\b(always|cancelled|success|failure)\(', expression):
+ if any(row.get('result') != 'success' for row in needs.values()):
+ return False
+
+ def value(match):
+ bits = match[0].split('.')
+ result = {'inputs': inputs, 'needs': needs}
+ for bit in bits:
+ result = result.get(bit, '') if isinstance(result, dict) else ''
+ return repr(result)
+
+ expression = re.sub(r'\b(?:inputs|needs)(?:\.[\w-]+)+', value, expression)
+ expression = expression.replace('&&', ' and ').replace('||', ' or ')
+ expression = re.sub(r'!(?!=)', ' not ', expression)
+ expression = re.sub(r'\btrue\b', 'True', expression)
+ expression = re.sub(r'\bfalse\b', 'False', expression)
+ return bool(eval('(' + expression.strip() + ')', {'__builtins__': {}}, {
+ 'always': lambda: True, 'cancelled': lambda: cancelled,
+ 'contains': lambda value, needle: needle in value,
+ }))
+
+
+def admitted(jobs):
+ return {name: {'result': 'success', 'outputs': {'sha': SHA}} for name in jobs}
+
+
+def test_native_consumers_and_publication_fail_closed_across_trust_skips(tmp_path):
+ jobs = _workflow()['jobs']
+ base_inputs = {'build_commit': '', 'upload_release': True, 'release-phase': '', 'termux_only': False, 'tag': TAG}
+ consumers = ['smoke-darwin', 'smoke-win32', 'smoke-win32-universal', 'assemble-win32-bundle',
+ 'publish-win32-updater', 'publish-darwin-updater', 'candidate-manifest']
+ for name in consumers:
+ job = jobs[name]
+ inputs = {**base_inputs, 'release-phase': 'candidate' if name == 'candidate-manifest' else ''}
+ needs = admitted(job['needs'])
+ # A skipped execution exists in the ancestry of every native result.
+ needs['build-win32-commit'] = {'result': 'skipped'}
+ assert gate(job['if'], inputs, needs), name
+ assert not gate(job['if'], inputs, needs, cancelled=True), name
+ for dependency in job['needs']:
+ for result in ('failure', 'skipped', 'cancelled'):
+ faulty = copy.deepcopy(needs)
+ faulty[dependency]['result'] = result
+ assert not gate(job['if'], inputs, faulty), (name, dependency, result)
+ needs['validate']['outputs'] = {}
+ assert not gate(job['if'], inputs, needs), name
+
+ scope_jobs = consumers[:4]
+ for name in scope_jobs:
+ needs = admitted(jobs[name]['needs'])
+ for phase, commit, upload, termux, allowed in [
+ ('', SHA, False, False, True), ('candidate', '', False, False, True),
+ ('', '', True, False, True), ('', '', False, False, False),
+ ('publish', '', False, False, False), ('promote', '', False, False, False),
+ ('', SHA, False, True, False),
+ ]:
+ inputs = {**base_inputs, 'release-phase': phase, 'build_commit': commit,
+ 'upload_release': upload, 'termux_only': termux}
+ assert gate(jobs[name]['if'], inputs, needs) is allowed, (name, inputs)
+ for name in ('publish-win32-updater', 'publish-darwin-updater'):
+ for key, value in [('build_commit', SHA), ('upload_release', False),
+ ('termux_only', True), ('release-phase', 'candidate'), ('release-phase', 'promote')]:
+ assert not gate(jobs[name]['if'], {**base_inputs, key: value}, admitted(jobs[name]['needs']))
+
+ for platform in ('win32', 'darwin'):
+ job = jobs[f'build-{platform}']
+ outcomes = ('success', 'failure', 'skipped', 'cancelled')
+ for commit, release, commit_result in itertools.product(
+ ('', SHA), outcomes, outcomes):
+ needs = admitted(job['needs'])
+ needs[f'build-{platform}-release']['result'] = release
+ needs[f'build-{platform}-commit']['result'] = commit_result
+ selected = gate(job['env']['SELECTED_BUILD_SUCCEEDED'], {'build_commit': commit}, needs, job_if=False)
+ expected = (commit == '' and release == 'success' and commit_result == 'skipped') or (
+ commit != '' and commit_result == 'success' and release == 'skipped')
+ assert selected is expected
+ result = subprocess.run([_BASH, '-e', '-c', job['steps'][0]['run']], cwd=tmp_path,
+ env=_child_env(SELECTED_BUILD_SUCCEEDED=str(selected).lower()),
+ capture_output=True, text=True, timeout=5)
+ assert (result.returncode == 0) is expected
+
+
+def test_smoke_matrix_native_routes_and_driver_only_dependencies():
+ workflow = smoke_workflow()
+ jobs = _workflow()['jobs']
+ executions = []
+ for name in ('smoke-darwin', 'smoke-win32', 'smoke-win32-universal'):
+ caller = jobs[name]
+ assert caller['strategy']['fail-fast'] is False
+ assert caller['permissions'] == {'contents': 'read'} and 'secrets' not in caller
+ matrix = caller['strategy']['matrix']
+ for arch, fmt in itertools.product(matrix['arch'], matrix.get('format', [caller['with']['format']])):
+ executions.append((caller['with']['platform'], arch, fmt))
+ assert set(executions) == {(platform, arch, fmt) for arch in ('arm64', 'x64')
+ for platform, formats in [('darwin', ('dmg', 'zip')), ('win32', ('msix', 'msixbundle'))]
+ for fmt in formats}
+ for job in workflow['jobs'].values():
+ assert job['cache-mode'] == 'read' and 'environment' not in job
+ checkout = next(step for step in job['steps'] if 'actions/checkout@' in step.get('uses', ''))
+ assert checkout['with']['persist-credentials'] is False
+ assert checkout['with']['ref'] == '${{ inputs.sha }}'
+ upload = next(step for step in job['steps'] if 'actions/upload-artifact@' in step.get('uses', ''))
+ assert upload['if'] == 'always()' and upload['with']['path'].endswith('/out')
+
+ workflows = [workflow] + [hermes_yaml.safe_load((ROOT / '.github/workflows' / name).read_text(encoding='utf-8-sig'))
+ for name in ('install-e2e-run.yml', 'install-e2e-macos-run.yml', 'install-e2e-windows-run.yml')]
+ for document in workflows:
+ for job in document['jobs'].values():
+ if 'steps' not in job:
+ continue
+ steps = job['steps']
+ setup = next(step for step in steps if step.get('uses') == './.github/actions/setup-pm')
+ assert setup['with']['toolchain'] == 'all' and not setup['with'].get('extras')
+ assert all(setup['with'][key] is False for key in ('cache', 'cache-node', 'cache-python'))
+ install = next(step for step in steps if step.get('name') == 'Install locked chat driver dependencies')
+ assert steps.index(setup) < steps.index(install)
+ args = install['run'].split()
+ assert args[:2] == ['npm', 'ci'] and args[args.index('--workspace') + 1] == 'apps/desktop'
+ assert {'--include-workspace-root', '--include=dev', '--ignore-scripts', '--no-audit', '--no-fund'} <= set(args)
+
+
+def transport_env(tmp_path, server, *, commit=False):
+ return dict(HERMES_PAYLOAD_TAG='' if commit else TAG, HERMES_BUILD_COMMIT=SHA if commit else '',
+ RELEASE_TAG='' if commit else TAG, RELEASE_COMMIT=SHA, COMMIT_BUILD=str(commit).lower(),
+ PUBLIC_BASE=f'http://127.0.0.1:{server.server_port}/hermes-releases',
+ CLOUDFLARE_R2_PUBLIC_URL=f'http://127.0.0.1:{server.server_port}/hermes-releases',
+ CLOUDFLARE_R2_ACCOUNT_ID='loopback', CLOUDFLARE_R2_ACCESS_KEY_ID='test-inert',
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY='test-inert', CLOUDFLARE_R2_BUCKET='hermes-releases',
+ RELEASE_PHASE='', SMOKE_ROOT=str(tmp_path / 'smoke'), GITHUB_OUTPUT=str(tmp_path / 'output'))
+
+
[email protected]('commit', [False, True])
[email protected]('platform,fmt', [('darwin', 'dmg'), ('darwin', 'zip'), ('win32', 'msix'), ('win32', 'msixbundle')])
[email protected]('arch', ['arm64', 'x64'])
+def test_public_smoke_fetches_the_receipt_bound_native_format(tmp_path, r2_server, commit, platform, fmt, arch):
+ env = transport_env(tmp_path, r2_server, commit=commit)
+ release = tmp_path / 'apps/desktop/release'
+ release.mkdir(parents=True)
+ suffix = f'mac-{arch}.{fmt}' if platform == 'darwin' else ('win.msixbundle' if fmt == 'msixbundle' else f'win-{arch}.msix')
+ filename = f'HermesBundled-0.28.0-{suffix}'
+ payload = b'transport fixture only: not a deployable package'
+ (release / filename).write_bytes(payload)
+ (release / ('Store-' + filename)).write_bytes(b'not eligible')
+ universal = fmt == 'msixbundle'
+ job = 'assemble-win32-bundle' if universal else f'build-{platform}-commit'
+ stage = 'Stage universal bundles to R2' if universal else (
+ 'Stage Windows packages to R2' if platform == 'win32' else 'Stage macOS packages and feed inputs to R2')
+ if platform == 'darwin':
+ # The producer stages all of its formats together; smoke selects one.
+ for ext in ('dmg', 'zip', 'zip.blockmap'):
+ (release / f'HermesBundled-0.28.0-mac-{arch}.{ext}').write_bytes(payload)
+ (release / f'{arch}-canary-mac.yml').write_bytes(payload)
+ staged = shell_step(tmp_path, r2_server, job, stage, {**env, 'TARGET': f'{platform}-{arch}'})
+ assert staged.returncode == 0, staged.stdout + staged.stderr
+ assert all('/canary/' not in key for key in r2_server.store)
+ script = next(step['run'] for step in smoke_workflow()['jobs']['macos']['steps']
+ if step.get('id') == 'artifact')
+ # Deliberately remove every storage credential before executing public fetch.
+ public_env = {key: '' if key.startswith('CLOUDFLARE_') else value for key, value in env.items()}
+ public_env.update(PLATFORM=platform, ARCH=arch, FORMAT=fmt)
+ r2_server.requests.clear()
+ result = shell_step(tmp_path, r2_server, '', '', public_env, script=script)
+ assert result.returncode == 0, result.stdout + result.stderr
+ selected = Path((tmp_path / 'output').read_text(encoding='utf-8-sig').strip().removeprefix('path='))
+ assert selected.name == filename and selected.read_bytes() == payload
+ witness = json.loads((tmp_path / 'smoke/out/download.json').read_text(encoding='utf-8-sig'))
+ assert witness['commit'] == SHA and witness['artifact']['sha256'] == hashlib.sha256(payload).hexdigest()
+ assert not any(file.name.startswith('Store-') for file in selected.parent.iterdir())
+ assert all(method == 'GET' and 'Authorization' not in headers for method, _, headers in r2_server.requests)
+
+
[email protected]('fault', ['missing', 'ambiguous', 'wrong-commit', 'corrupt'])
+def test_download_faults_never_export_an_accepted_artifact(tmp_path, r2_server, fault):
+ env = transport_env(tmp_path, r2_server, commit=True)
+ filename = 'HermesBundled-0.28.0-win-x64.msix'
+ payload = b'inert integrity fixture'
+ row = {'path': filename, 'size': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()}
+ receipt = {'schema': 2, 'commit': 'b' * 40 if fault == 'wrong-commit' else SHA,
+ 'name': 'win32-x64', 'files': [row]}
+ prefix = f'releases/commit/{SHA}/'
+ r2_server.store[prefix + filename] = (b'corrupted' if fault == 'corrupt' else payload, '"e"')
+ if fault == 'missing':
+ receipt['files'] = [{**row, 'path': 'Store-' + filename}]
+ elif fault == 'ambiguous':
+ second = 'HermesBundled-0.29.0-win-x64.msix'
+ receipt['files'].append({**row, 'path': second})
+ r2_server.store[prefix + second] = (payload, '"e"')
+ r2_server.store[prefix + 'handoff-win32-x64.json'] = (json.dumps(receipt).encode(), '"e"')
+ script = next(step['run'] for step in smoke_workflow()['jobs']['macos']['steps'] if step.get('id') == 'artifact')
+ result = shell_step(tmp_path, r2_server, '', '', {**env, 'PLATFORM': 'win32', 'ARCH': 'x64', 'FORMAT': 'msix'}, script=script)
+ assert result.returncode != 0
+ assert not (tmp_path / 'output').exists()
+ assert not (tmp_path / 'smoke/out/download.json').exists()
+
+
+def test_stable_phase_and_canary_gates_require_smoke_but_preserve_other_phases(tmp_path, r2_server):
+ jobs = _workflow()['jobs']
+ required = {
+ 'candidate': ['validate', 'build-win32', 'build-darwin', 'assemble-win32-bundle',
+ 'smoke-darwin', 'smoke-win32', 'smoke-win32-universal', 'termux-deb', 'candidate-manifest'],
+ 'publish': ['validate', 'stable-publish', 'stable-store'],
+ 'promote': ['validate', 'stable-promote'],
+ }
+ for phase, selected in required.items():
+ needs = {name: {'result': 'success' if name in selected else 'skipped'}
+ for name in jobs['stable-phase-result']['needs']}
+ for failed in [None, *selected]:
+ changed = copy.deepcopy(needs)
+ if failed:
+ changed[failed]['result'] = 'cancelled'
+ result = shell_step(tmp_path, r2_server, 'stable-phase-result', 'Require every phase job', {
+ 'RELEASE_NEEDS': json.dumps(changed), 'RELEASE_PHASE': phase})
+ assert (result.returncode == 0) is (failed is None), (phase, failed, result.stderr)
+ inputs = {'build_commit': '', 'upload_release': True, 'tag': TAG}
+ needs = admitted(jobs['publish-canary']['needs'])
+ assert gate(jobs['publish-canary']['if'], inputs, needs)
+ for name in ('smoke-darwin', 'smoke-win32', 'smoke-win32-universal'):
+ for state in ('failure', 'skipped', 'cancelled'):
+ faulty = copy.deepcopy(needs)
+ faulty[name]['result'] = state
+ assert not gate(jobs['publish-canary']['if'], inputs, faulty)
+
+
+def test_canary_publisher_consumes_staged_bytes_and_writes_pointer_last(tmp_path, r2_server):
+ tag = 'v0.28.1-canary.20260818101010'
+ env = {**transport_env(tmp_path, r2_server), 'HERMES_DESKTOP_VARIANT': 'bundled',
+ 'HERMES_PAYLOAD_TAG': tag, 'RELEASE_TAG': tag}
+ # Use the real assembly identity derivation with a stable base available.
+ for file in ['scripts/msix-shared.mjs', 'scripts/release-content-types.json',
+ 'apps/desktop/product-identity.cjs', 'apps/desktop/package.json']:
+ target = tmp_path / file
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(ROOT / file, target)
+
+ def git(*args, date='2026-08-18T08:10:10Z'):
+ subprocess.run(['git', *args], cwd=tmp_path, check=True, capture_output=True,
+ env=_child_env(GIT_AUTHOR_NAME='Fixture', GIT_AUTHOR_EMAIL='[email protected]',
+ GIT_COMMITTER_NAME='Fixture', GIT_COMMITTER_EMAIL='[email protected]',
+ GIT_AUTHOR_DATE=date, GIT_COMMITTER_DATE=date,
+ GIT_CONFIG_GLOBAL=str(tmp_path / 'no-git-config'), GIT_CONFIG_NOSYSTEM='1'))
+
+ def assembly_identity():
+ result = subprocess.run(['node', '--input-type=module', '-e',
+ 'import {appIdentity} from "./scripts/msix-shared.mjs";'
+ 'console.log(JSON.stringify(appIdentity(process.cwd()+"/apps/desktop")));'],
+ cwd=tmp_path, env=_child_env(**env), check=True, capture_output=True, text=True)
+ return json.loads(result.stdout)
+
+ git('init', '-q')
+ git('-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'stable base')
+ git('tag', 'v0.28.0')
+ assembled = assembly_identity()
+ version = assembled['version']
+ release = tmp_path / 'apps/desktop/release'
+ release.mkdir(parents=True)
+ filename = f"{assembled['name']}-{version}-win.msixbundle"
+ bundle = release / filename
+ with zipfile.ZipFile(bundle, 'w') as archive:
+ archive.writestr('AppxMetadata/AppxBundleManifest.xml',
+ '<Bundle><Identity Name="NousResearch.HermesBundledCanary" '
+ 'Publisher="CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US" '
+ f'Version="{version}"/></Bundle>')
+ tested_bytes = bundle.read_bytes()
+ staged = shell_step(tmp_path, r2_server, 'assemble-win32-bundle', 'Stage universal bundles to R2', env)
+ assert staged.returncode == 0, staged.stdout + staged.stderr
+ assert all(key.startswith(f'releases/tag/{tag}/') for key in r2_server.store)
+ # A newer stable becomes visible after assembly but before publication.
+ git('-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'new stable', date='2026-08-18T11:10:10Z')
+ git('tag', 'v0.28.1')
+ assert assembly_identity()['version'] != version
+ for name in ('Retrieve the tested universal bundle', 'Publish identical tested bytes without rebuilding'):
+ result = shell_step(tmp_path, r2_server, 'publish-win32-updater', name, env)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert (tmp_path / 'staged' / filename).read_bytes() == tested_bytes
+ assert r2_server.store[f'releases/win32/canary/{filename}'][0] == tested_bytes
+ writes = [path for method, path, _ in r2_server.requests if method == 'PUT']
+ assert writes[-1].endswith('/canary.appinstaller')
+ descriptor = ET.fromstring(r2_server.store['releases/win32/canary/canary.appinstaller'][0])
+ main_bundle = descriptor.find('{*}MainBundle')
+ assert main_bundle is not None
+ assert descriptor.get('Version') == main_bundle.get('Version') == version
+
+ # The publication job must refuse an ambiguous envelope, even when a
+ # caller accidentally broadens the receipt selector in future.
+ (tmp_path / 'staged/HermesBundled-0.29.0.0-win.msixbundle').write_bytes(tested_bytes)
+ before = len(writes)
+ refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',
+ 'Publish identical tested bytes without rebuilding', env)
+ assert refused.returncode != 0
+ assert len([row for row in r2_server.requests if row[0] == 'PUT']) == before
+ (tmp_path / 'staged/HermesBundled-0.29.0.0-win.msixbundle').unlink()
+
+ # Filename, tag base, and baked identity must still agree. Reading the
+ # accepted assembly version is not permission to trust arbitrary metadata.
+ staged_bundle = tmp_path / 'staged' / filename
+ for field, wrong in [('Version', '0.28.1.0'), ('Name', 'NousResearch.Other'), ('Publisher', 'CN=Other')]:
+ with zipfile.ZipFile(bundle) as archive:
+ manifest = ET.fromstring(archive.read('AppxMetadata/AppxBundleManifest.xml'))
+ native = manifest.find('Identity')
+ assert native is not None
+ native.set(field, wrong)
+ with zipfile.ZipFile(staged_bundle, 'w') as archive:
+ archive.writestr('AppxMetadata/AppxBundleManifest.xml', ET.tostring(manifest))
+ refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',
+ 'Publish identical tested bytes without rebuilding', env)
+ assert refused.returncode != 0, field
+ assert len([row for row in r2_server.requests if row[0] == 'PUT']) == before
+ staged_bundle.write_bytes(tested_bytes)
+ for wrong in ['HermesBundled-0.29.0.0-win.msixbundle', 'HermesBundled-0.28.1.65536-win.msixbundle',
+ 'HermesBundled-0.28.1-canary.20260818101010-win.msixbundle']:
+ renamed = staged_bundle.rename(staged_bundle.with_name(wrong))
+ refused = shell_step(tmp_path, r2_server, 'publish-win32-updater',
+ 'Publish identical tested bytes without rebuilding', env)
+ assert refused.returncode != 0, wrong
+ assert len([row for row in r2_server.requests if row[0] == 'PUT']) == before
+ renamed.rename(staged_bundle)
\ No newline at end of file
diff --git a/tests/ci/test_desktop_store_eligibility.py b/tests/ci/test_desktop_store_eligibility.py
index 490ec9da15d..c1f5a40ad26 100644
--- a/tests/ci/test_desktop_store_eligibility.py
+++ b/tests/ci/test_desktop_store_eligibility.py
@@ -2,6 +2,7 @@
import json
import os
import shlex
+import shutil
import subprocess
import sys
@@ -15,14 +16,14 @@ from tests.ci.test_desktop_release_tag_admission import _BASH, _child_env, _work
('v0.28.0-canary.20260818', '', False),
('', 'a' * 40, False),
])
-def test_windows_build_and_bundle_only_request_store_for_stable(tmp_path, tag, commit, store):
+def test_bundle_only_requests_store_for_stable(tmp_path, tag, commit, store):
helper = tmp_path / 'bin'
helper.mkdir()
log = tmp_path / 'calls.jsonl'
recorder = helper / 'record.py'
recorder.write_text(
'import json,os,sys\n'
- 'with open(os.environ["CALL_LOG"],"a") as file: file.write(json.dumps(sys.argv[1:])+"\\n")\n',
+ 'with open(os.environ["CALL_LOG"],"a",encoding="utf-8") as file: file.write(json.dumps(sys.argv[1:])+"\\n")\n',
encoding='utf-8',
)
for tool in ['python', 'node']:
@@ -33,13 +34,41 @@ def test_windows_build_and_bundle_only_request_store_for_stable(tmp_path, tag, c
env = _child_env(HERMES_PAYLOAD_TAG=tag, HERMES_BUILD_COMMIT=commit,
HERMES_PAYLOAD_VERSION='0.28.0', RELEASE_PHASE='candidate' if store else '', CALL_LOG=str(log))
env['PATH'] = str(helper) + os.pathsep + env['PATH']
- for job, name in [('build-win32', 'Build and package'),
- ('publish-win32-updater', 'Bundle + stage the MSIX feeds')]:
- script = next(step['run'] for step in jobs[job]['steps'] if step.get('name') == name)
- result = subprocess.run([_BASH, '-e', '-o', 'pipefail', '-c', script], env=env, cwd=tmp_path,
- capture_output=True, text=True, timeout=15)
- assert result.returncode == 0, result.stdout + result.stderr
- calls = [json.loads(line) for line in log.read_text().splitlines()]
- assert any('--variant=bundled' in call for call in calls)
- assert any('--variant=store' in call for call in calls) is store
+ job = jobs['assemble-win32-bundle']
+ script = next(step['run'] for step in job['steps']
+ if step.get('name') == 'Assemble the signed MSIX bundle without publishing')
+ result = subprocess.run([_BASH, '-e', '-o', 'pipefail', '-c', script], env=env, cwd=tmp_path,
+ capture_output=True, text=True, timeout=15)
+ assert result.returncode == 0, result.stdout + result.stderr
+ calls = [json.loads(line) for line in log.read_text(encoding='utf-8-sig').splitlines()]
+ assert calls[0][:1] == ['scripts/stage-msixbundle.mjs']
+ assert calls[0][calls[0].index('--variant') + 1] == 'bundled'
+ assert ('--no-upload' in calls[0]) is bool(commit)
+ assert ('--candidate' in calls[0]) is store
assert any('scripts/bundle-store-msixbundle.mjs' in call for call in calls) is store
+ assert not any('publish-appinstaller' in call for call in calls)
+
+
[email protected]('tag,commit,store', [
+ ('v0.28.0', '', True), ('v0.28.0-canary.20260818', '', False), ('', 'a' * 40, False),
+])
+def test_native_windows_build_selects_store_only_for_stable(tmp_path, tag, commit, store):
+ jobs = _workflow()['jobs']
+ selected = 'build-win32-commit' if commit else 'build-win32-release'
+ script = next(step['run'] for step in jobs[selected]['steps'] if step.get('name') == 'Build and package')
+ wrapper = tmp_path / 'run.ps1'
+ # Only the build boundary is substituted; execute the actual PowerShell
+ # branch and native-exit handling instead of interpreting it as Bash.
+ wrapper.write_text('function python { $args -join " " | Add-Content $env:CALL_LOG -Encoding UTF8; $global:LASTEXITCODE = 0 }\n' + script, encoding='utf-8')
+ log = tmp_path / 'calls.txt'
+ powershell = shutil.which('powershell')
+ assert powershell
+ result = subprocess.run([powershell, '-NoProfile', '-File', str(wrapper)],
+ env=_child_env(HERMES_PAYLOAD_TAG=tag, HERMES_BUILD_COMMIT=commit,
+ RUNNER_TEMP=str(tmp_path), CALL_LOG=str(log)),
+ capture_output=True, text=True, timeout=15)
+ assert result.returncode == 0, result.stdout + result.stderr
+ calls = log.read_text(encoding='utf-8-sig')
+ assert '--variant bundled' in calls
+ assert ('--variant store' in calls) is store
diff --git a/tests/install/README.md b/tests/install/README.md
index a3b7d7d5ccb..84bcb88e15d 100644
--- a/tests/install/README.md
+++ b/tests/install/README.md
@@ -43,13 +43,76 @@ Each leg with the script drivers has these phases:
3. Update: move `main` to HEAD. Apply one update method. An app update must produce a new successful receipt or handoff result; a changed checkout alone is not completion.
4. Verify the installed command and products before running `hermes --version`. Select the command under the installation's `.hermes/bin`; use the old venv only for a source tree without PM. Check PM currency and compiler receipts where supported. Preserve the no-desktop scenario for a plain install. Do not rebuild, remove dependencies, or force-stop an updater during verification. Historical installs without these receipts get artifact-presence checks, not a freshness claim.
-The cheap fixture checks are `tests/scripts/test_source_driver.py` and `tests-js/source-update-observer.test.mjs`. They do not run installers or prove native GUI relaunch. The source app helper does not relaunch the updated app for it; the native packaged-update drivers own automatic-relaunch acceptance. The observer does not change source files, products, dependency selections, or facts.
+The cheap fixture checks are `tests/scripts/test_source_driver.py` and `tests-js/source-update-observer.test.mjs`. They do not run installers or prove native GUI relaunch. The native packaged-update drivers own automatic-relaunch acceptance. A later driver-owned launch checks chat only after the original update/relaunch assertions pass; it cannot repair a failed handoff. The observer does not change source files, products, dependency selections, or facts.
The Windows `desktop-installer@latest` install downloads the published
`Hermes-Setup.exe` and drives its GUI with AutoHotkey. The selected update
method is a separate axis. App-update methods click the running app's Update
control; script and CLI methods use their corresponding entry points.
+## Desktop chat at install and update checkpoints
+
+Desktop-bearing routes run the same message check used by post-build bundle
+smoke and the desktop chat spec: `tests-js/scripts/desktop-chat-smoke.ts`.
+It types a unique prompt through the real composer, requires a new request at
+the existing loopback mock provider, and waits for a new completed assistant
+reply in the active transcript. A reply preserved from OLD cannot satisfy NEW.
+Only inference is mocked; Electron, the installed backend, and rendering run
+for real. These checks require no external model credentials.
+
+- A desktop-bearing OLD installation must chat before its update. App-driven
+ updates also check the actual OLD window before clicking Update now.
+- After the existing completion and product checks, NEW must chat if the route
+ expects desktop. A route that adds desktop only at update retains the OLD
+ no-desktop assertion.
+- Plain source install/update routes that never request desktop record
+ `not-applicable`; the chat driver does not build desktop for them.
+- Native package updates must prove automatic relaunch first. The driver then
+ closes the verified app normally and launches the same installed binary for
+ `post-update-launch` chat. That second launch is not automatic-relaunch proof.
+
+`tests/install/e2e-assets/desktop-smoke.ts` runs an exact installed executable
+with an isolated home/userData and checks the actual backend listener's origin.
+Source checkpoints use that leg's installed tree; bundle checkpoints use its
+embedded payload. Missing products fail rather than trigger a build or repair.
+Driver Node/Playwright come from the current checkout, not OLD's dependencies.
+
+Each checkpoint writes a `desktop-chat-old.json`, `desktop-chat-new.json`, or
+`desktop-chat-installed.json` result plus a screenshot. Failed chat fails the
+leg even when version, health, and update receipts passed. Existing plugin and
+user-state preservation checks remain required. The mock configuration writer
+preserves unrelated settings, including the controlled update feed.
+
+## Post-build artifact smoke
+
+`desktop-bundled-release.yml` calls `desktop-bundle-smoke.yml` on fresh native
+Windows and macOS runners. It downloads the admitted commit's receipt-bound
+bytes through the public archive and installs the actual artifact before chat:
+
+| Native target | Independently installed formats |
+|---|---|
+| macOS arm64 and x64 | DMG, ZIP |
+| Windows arm64 and x64 | MSIX, universal MSIXBUNDLE |
+
+The universal envelope runs on both Windows architectures, verifying native
+slice selection. Windows assembly/staging is separate from feed publication;
+both Windows smoke matrices must pass before publishing its canary feed.
+macOS publication and stable candidate acceptance also require their smoke
+results. Failed checks retain the downloadable build and diagnostic artifacts.
+
+Stable candidate schema 2 binds these successful smoke groups into the pinned
+candidate manifest. Promotion renders that evidence, not the skipped smoke
+jobs from its own phase. Schema-1 candidates lack this admission and cannot be
+promoted by the new workflow; create a new candidate tag. They remain valid as
+previous-version upgrade baselines.
+
+This covers signed downloadable commit builds, canaries with upload enabled,
+and stable candidates. No-upload tag builds have no cross-job download handoff.
+Linux bundle jobs remain disabled, but Linux source-install desktop checks run.
+Unsigned Store submissions are not sideloaded or re-signed for this smoke;
+their Store acceptance remains separate. Passing helper tests does not establish
+native installation or chat acceptance: those require the corresponding runner.
+
## Old versions
A leg can install a release from months back. The driver must not assume that the old version has today's CLI surface. The rule: probe, do not assume.
diff --git a/tests/install/e2e-assets/bundle-smoke-metadata.mjs b/tests/install/e2e-assets/bundle-smoke-metadata.mjs
new file mode 100644
index 00000000000..384bd5845d9
--- /dev/null
+++ b/tests/install/e2e-assets/bundle-smoke-metadata.mjs
@@ -0,0 +1,117 @@
+// Fresh-install admission is separate from the stricter OLD -> NEW update contract.
+import fs from 'node:fs'
+import path from 'node:path'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { parseArgs } from 'node:util'
+import { fileURLToPath } from 'node:url'
+import { OUT_OF_STORE_PUBLISHER } from '../../../scripts/msix-shared.mjs'
+import { codesignTeam } from './mac-bundled-manifest.cjs'
+
+const identityModule = fileURLToPath(new URL('../../../apps/desktop/product-identity.cjs', import.meta.url))
+
+export function bundleIdentity(commit, tag = '') {
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error('Expected exact full lowercase commit SHA')
+ if (tag && !/^v\d+\.\d+\.\d+(?:-canary\.20\d{6}(?:\d{6})?)?$/.test(tag)) throw new Error('Invalid release tag')
+ // The production module reads build flags at require-time. A child avoids
+ // mutating the driver's environment or returning a cached variant identity.
+ const identity = JSON.parse(execFileSync(process.execPath, ['-e',
+ 'console.log(JSON.stringify(require(process.argv[1])))', identityModule], {
+ encoding: 'utf8', env: { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled',
+ HERMES_PAYLOAD_TAG: tag, HERMES_BUILD_COMMIT: tag ? '' : commit },
+ }))
+ return { appId: identity.appId, msixIdentity: identity.msixAppIdWithOrg,
+ applicationId: identity.appNamePascal, publisher: OUT_OF_STORE_PUBLISHER }
+}
+
+export function verifyBundleStamp(stamp, { commit, tag = '', platform }) {
+ if (!['darwin', 'win32'].includes(platform)) throw new Error('Unsupported native platform')
+ const expected = { commit, tag: tag || null, payload: 'bundled', distribution: 'desktop-app', dirty: false,
+ updateMechanism: tag ? { darwin: 'electron-updater', win32: 'app-installer' }[platform] : 'external' }
+ if (!tag) Object.assign(expected, { source: 'commit-build', branch: null })
+ for (const [key, value] of Object.entries(expected)) {
+ if (stamp?.[key] !== value) throw new Error(`stamp.${key}: ${JSON.stringify(stamp?.[key])} != ${JSON.stringify(value)}`)
+ }
+ const version = tag ? tag.slice(1) : stamp.displayVersion
+ if (!tag && !/^\d+\.\d+\.\d+$/.test(version)) throw new Error('stamp.displayVersion must be a commit-build semver')
+ return version
+}
+
+function childPath(root, relative) {
+ const full = fs.realpathSync(path.resolve(root, relative))
+ if (!full.startsWith(`${fs.realpathSync(root)}${path.sep}`)) throw new Error(`Path escapes installed root: ${relative}`)
+ return full
+}
+
+function verifyMac(app, commit, tag, arch) {
+ const expected = bundleIdentity(commit, tag)
+
+ execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=2', app], { stdio: 'inherit' })
+ const display = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=4', app], { encoding: 'utf8' })
+ if (display.error || display.status !== 0) throw new Error(`codesign display failed: ${display.error || display.stderr}`)
+ const signedTeam = codesignTeam(display.stderr)
+ // The admitted artifact digest pins the signed bytes. Require a real team,
+ // not a new CI identity setting that could drift from the signing certificate.
+ if (!/^[A-Z0-9]{10}$/.test(signedTeam || '')) throw new Error('Bundle has no valid signing team')
+ if (/^Identifier=(.+)$/m.exec(display.stderr)?.[1] !== expected.appId) throw new Error('Signing identifier disagrees with product identity')
+ const plist = JSON.parse(execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-',
+ path.join(app, 'Contents/Info.plist')], { encoding: 'utf8' }))
+ if (plist.CFBundleIdentifier !== expected.appId) throw new Error('CFBundleIdentifier disagrees with product identity')
+ const stamp = JSON.parse(fs.readFileSync(childPath(app, 'Contents/Resources/install-stamp.json'), 'utf8'))
+ const version = verifyBundleStamp(stamp, { commit, tag, platform: 'darwin' })
+ if (plist.CFBundleShortVersionString !== version) throw new Error('CFBundleShortVersionString disagrees with stamp/tag')
+ if (!plist.CFBundleExecutable || /[/\\]/.test(plist.CFBundleExecutable)) throw new Error('Invalid CFBundleExecutable')
+ const exe = childPath(app, `Contents/MacOS/${plist.CFBundleExecutable}`)
+ fs.accessSync(exe, fs.constants.X_OK)
+ const archs = execFileSync('/usr/bin/lipo', ['-archs', exe], { encoding: 'utf8' }).trim().split(/\s+/)
+ const native = { arm64: 'arm64', x64: 'x86_64' }[arch]
+ if (archs.length !== 1 || archs[0] !== native) throw new Error(`Expected native ${arch}, got ${archs}`)
+ execFileSync('/usr/bin/xcrun', ['stapler', 'validate', app], { stdio: 'inherit' })
+ execFileSync('/usr/sbin/spctl', ['-a', '-vv', '-t', 'exec', app], { stdio: 'inherit' })
+ const root = childPath(app, 'Contents/Resources/agent-payload')
+ return { app, exe, root, arch, version, bundleIdentifier: expected.appId, teamIdentifier: signedTeam, stamp }
+}
+
+function prepareDirectories(work, out) {
+ const temp = fs.realpathSync(process.env.RUNNER_TEMP)
+ const canonical = [work, out].map(dir => {
+ if (!path.isAbsolute(dir)) throw new Error('Work and out must be absolute descendants of RUNNER_TEMP')
+ dir = path.resolve(dir)
+ let parent = dir
+ while (!fs.existsSync(parent)) parent = path.dirname(parent)
+ // macOS /var is itself an alias of /private/var; allow aliases only if
+ // their actual destination is still beneath this runner's temporary root.
+ const full = path.resolve(fs.realpathSync(parent), path.relative(parent, dir))
+ const relative = path.relative(temp, full)
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ throw new Error('Work and out must stay beneath RUNNER_TEMP')
+ }
+ return full
+ })
+ if (canonical[0] === canonical[1] || canonical[0].startsWith(`${canonical[1]}${path.sep}`)) {
+ throw new Error('Output must not contain the private work directory')
+ }
+ if (fs.existsSync(canonical[0])) throw new Error(`Refusing to reuse work directory: ${work}`)
+ fs.mkdirSync(canonical[0], { recursive: true })
+ fs.mkdirSync(canonical[1], { recursive: true })
+}
+
+function main() {
+ const [command, ...args] = process.argv.slice(2)
+ const { values } = parseArgs({ args, options: Object.fromEntries(
+ ['commit', 'tag', 'platform', 'stamp', 'app', 'arch', 'out', 'work'].map(key => [key, { type: 'string' }])) })
+ const commands = {
+ identity: () => bundleIdentity(values.commit, values.tag),
+ stamp: () => verifyBundleStamp(JSON.parse(fs.readFileSync(values.stamp, 'utf8')), values),
+ 'verify-mac': () => verifyMac(values.app, values.commit, values.tag, values.arch),
+ prepare: () => prepareDirectories(values.work, values.out),
+ }
+ if (!commands[command]) throw new Error(`Unknown command: ${command}`)
+ const result = commands[command]()
+ if (result !== undefined) {
+ const text = JSON.stringify(result, null, 2) + '\n'
+ if (values.out && command !== 'prepare') fs.writeFileSync(values.out, text)
+ else process.stdout.write(text)
+ }
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main()
\ No newline at end of file
diff --git a/tests/install/e2e-assets/desktop-smoke-windows.ps1 b/tests/install/e2e-assets/desktop-smoke-windows.ps1
new file mode 100644
index 00000000000..70209317926
--- /dev/null
+++ b/tests/install/e2e-assets/desktop-smoke-windows.ps1
@@ -0,0 +1,42 @@
+# Journey-owned mock and ordinary window close, shared by source and MSIX drivers.
+# Callers supply a checkout-provisioned Node; never resolve tooling from OLD.
+function Start-DesktopJourneyMock([string]$Node, [string]$Assets, [string]$Work, [string]$HermesHome, [string]$Out) {
+ New-Item -ItemType Directory -Path $Out -Force | Out-Null
+ $urlFile = Join-Path $Work 'chat-mock-url'
+ Remove-Item -LiteralPath $urlFile -Force -ErrorAction SilentlyContinue
+ $mock = Start-Process -FilePath $Node -ArgumentList @(('"' + (Join-Path $Assets 'mock-provider.mjs') + '"'), ('"' + $urlFile + '"')) `
+ -PassThru -RedirectStandardOutput (Join-Path $Out 'chat-mock.log') -RedirectStandardError (Join-Path $Out 'chat-mock-error.log')
+ try {
+ $deadline = (Get-Date).AddSeconds(30)
+ while (-not (Test-Path -LiteralPath $urlFile)) {
+ if ($mock.HasExited -or (Get-Date) -ge $deadline) { throw 'Desktop mock did not become ready' }
+ Start-Sleep -Milliseconds 200
+ }
+ $env:HERMES_E2E_MOCK_URL = (Get-Content -LiteralPath $urlFile -Raw).Trim()
+ Invoke-RestMethod -Uri "$env:HERMES_E2E_MOCK_URL/__e2e__/prompts" -TimeoutSec 5 | Out-Null
+ $configWriter = [IO.Path]::GetFullPath((Join-Path $Assets '..\..\..\tests-js\scripts\mock-provider-config.ts'))
+ & $Node $configWriter $HermesHome $env:HERMES_E2E_MOCK_URL
+ if ($LASTEXITCODE -ne 0) { throw 'Desktop mock configuration failed' }
+ return $mock
+ } catch {
+ if (-not $mock.HasExited) { Stop-Process -Id $mock.Id -ErrorAction SilentlyContinue }
+ throw
+ }
+}
+
+function Close-VerifiedDesktop([string]$Exe, [int]$ProcessId = 0) {
+ $rows = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $Exe })
+ $windows = @($rows | ForEach-Object { Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue } | Where-Object { $_.MainWindowHandle -ne 0 })
+ if ($ProcessId) { $windows = @($windows | Where-Object { $_.Id -eq $ProcessId }) }
+ if ($windows.Count -ne 1) { throw 'Cannot identify exactly one verified desktop window to close normally' }
+ $window = $windows[0]
+ if (-not $window.CloseMainWindow()) { throw 'Verified desktop refused a normal window close' }
+ if (-not $window.WaitForExit(30000)) { throw 'Verified desktop did not exit normally; no force-kill or smoke relaunch attempted' }
+ $deadline = (Get-Date).AddSeconds(30)
+ do {
+ $remaining = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $Exe })
+ if (-not $remaining.Count) { return }
+ Start-Sleep -Milliseconds 200
+ } while ((Get-Date) -lt $deadline)
+ throw 'Verified desktop children did not exit normally; no smoke relaunch attempted'
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/desktop-smoke.ts b/tests/install/e2e-assets/desktop-smoke.ts
new file mode 100644
index 00000000000..893b369c00b
--- /dev/null
+++ b/tests/install/e2e-assets/desktop-smoke.ts
@@ -0,0 +1,292 @@
+import fs from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+
+import { _electron, type ElectronApplication, type Page } from '@playwright/test'
+import { z } from 'zod'
+
+import { readChatIdentity, runDesktopChatSmoke, waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke.ts'
+import { assertBackendOrigin, localBackendProcess, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts'
+import { validateMockUrl, writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config.ts'
+import { type MockServer, startMockServer } from '../../../tests-js/scripts/mock-server.ts'
+
+const require = createRequire(import.meta.url)
+const { pickAppWindow }: { pickAppWindow: (app: ElectronApplication, log: (message: string) => void) => Promise<Page> } = require('./update-ui.cjs')
+const { prepareWindowForInput }: { prepareWindowForInput: (app: ElectronApplication, page: Page) => Promise<void> } = require('./window-input.cjs')
+
+const absolutePath = z.string().refine(path.isAbsolute, 'Expected an absolute path')
+const optionsSchema = z.object({
+ exe: absolutePath, root: absolutePath, origin: z.enum(['source', 'bundled']),
+ home: absolutePath, 'user-data': absolutePath, out: absolutePath,
+ phase: z.enum(['old', 'new', 'installed']), 'expect-commit': z.string().regex(/^[0-9a-f]{40}$/),
+ 'launch-spec': absolutePath.optional(), 'mock-url': z.string().optional(),
+})
+type SmokeOptions = z.infer<typeof optionsSchema>
+
+const launchSpecSchema = z.object({
+ argv: z.array(z.string()).min(1), cwd: absolutePath,
+ // oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- This is the existing launch-capture wire field.
+ env: z.record(z.string(), z.string()), matchedShape: z.enum(['source', 'packaged']),
+})
+
+interface SmokeEnvironment extends Record<string, string> {
+ HOME: string
+ USERPROFILE: string
+ HERMES_HOME: string
+ HERMES_DESKTOP_USER_DATA_DIR: string
+ XDG_CONFIG_HOME: string
+ XDG_DATA_HOME: string
+ XDG_CACHE_HOME: string
+}
+
+interface Launch {
+ executablePath: string
+ args: string[]
+ cwd: string
+ env: SmokeEnvironment
+}
+
+interface RunningDesktop {
+ pid: number
+ executable: string
+ resources: string
+ userData: string
+ home: string
+}
+
+interface ElectronProcess extends NodeJS.Process {
+ resourcesPath: string
+}
+
+export function smokeEnvironment(inherited: NodeJS.ProcessEnv, home: string, userData: string): SmokeEnvironment {
+ const clean: Record<string, string> = {}
+ const keepHermes = new Set(['HERMES_TEST_INSTALL_REF', 'HERMES_TEST_INSTALL_REPO'])
+ for (const [key, value] of Object.entries(inherited)) {
+ const name = key.toUpperCase()
+ if (!value || /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/.test(name)
+ || /^(?:PYTHON|VIRTUAL_ENV|CONDA|NODE_|NPM_|ELECTRON_|VITE_|UV_|PM_)/.test(name)
+ || /^(?:OPENAI|ANTHROPIC|OPENROUTER|OLLAMA|GEMINI|GROQ|XAI)_/.test(name)
+ || (name.startsWith('HERMES_') && !keepHermes.has(name))
+ || ['INIT_CWD', 'TERMINAL_CWD', 'LD_PRELOAD', 'DYLD_INSERT_LIBRARIES', 'SSH_AUTH_SOCK', 'SSH_ASKPASS', 'GIT_ASKPASS'].includes(name)) {
+ continue
+ }
+ clean[key] = value
+ }
+ return {
+ ...clean, HOME: path.join(home, '.desktop-smoke-home'), USERPROFILE: path.join(home, '.desktop-smoke-home'),
+ XDG_CONFIG_HOME: path.join(home, '.desktop-smoke-home', '.config'),
+ XDG_DATA_HOME: path.join(home, '.desktop-smoke-home', '.local', 'share'),
+ XDG_CACHE_HOME: path.join(home, '.desktop-smoke-home', '.cache'),
+ HERMES_HOME: home, HERMES_DESKTOP_USER_DATA_DIR: userData,
+ APPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Roaming'),
+ LOCALAPPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Local'),
+ }
+}
+
+export function resolveSmokeLaunch(options: SmokeOptions): Launch {
+ const spec = options['launch-spec'] ? launchSpecSchema.parse(JSON.parse(fs.readFileSync(options['launch-spec'], 'utf8').replace(/^\uFEFF/, ''))) : null
+ const env = smokeEnvironment({ ...process.env, ...spec?.env }, options.home, options['user-data'])
+ let args: string[] = []
+ let cwd = env.HOME!
+ if (spec) {
+ if (options.origin !== 'source') {
+ throw new Error('A captured source launch specification cannot select a bundled backend')
+ }
+ if (!within(options.root, spec.cwd)) {
+ throw new Error('Source launch cwd is outside the expected installation')
+ }
+ cwd = spec.cwd
+ // oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- This is the existing launch-capture wire field.
+ if (spec.matchedShape === 'source') {
+ const index = spec.argv.indexOf('electron')
+ if (index < 0 || !spec.argv.includes('.')) {
+ throw new Error('Unsupported captured source launch shape')
+ }
+ args = [spec.cwd, ...spec.argv.slice(index + 1).filter((arg: string): boolean => arg !== '.')]
+ } else {
+ if (fs.realpathSync(spec.argv[0]) !== fs.realpathSync(options.exe)) {
+ throw new Error('Launch spec executable differs from --exe')
+ }
+ args = spec.argv.slice(1)
+ }
+ const editableRoot = spec.env.HERMES_PYTHON_SRC_ROOT
+ if (editableRoot) {
+ if (!path.isAbsolute(editableRoot) || fs.realpathSync(editableRoot) !== fs.realpathSync(options.root)) {
+ throw new Error('Captured HERMES_PYTHON_SRC_ROOT differs from the expected source installation')
+ }
+ env.HERMES_PYTHON_SRC_ROOT = editableRoot
+ }
+ // Retain the product-selected source interpreter, not the driver's activated Python.
+ for (const key of ['HERMES_DESKTOP_PYTHON', 'HERMES_DESKTOP_HERMES', 'HERMES_DESKTOP_HERMES_ROOT']) {
+ const value = spec.env[key]
+ if (value) {
+ if (!path.isAbsolute(value) || (key !== 'HERMES_DESKTOP_PYTHON' && !within(options.root, value))) {
+ throw new Error(`Captured ${key} escapes the expected source installation`)
+ }
+ fs.accessSync(value)
+ env[key] = value
+ }
+ }
+ }
+ return { executablePath: options.exe, args, cwd, env }
+}
+
+/** Select local through the persisted connection contract before any baked remote default can dial. */
+function selectLocal(userData: string): void {
+ const v1Path = path.join(userData, 'connection.json')
+ const document = z.object({}).passthrough()
+ const v1 = fs.existsSync(v1Path) ? document.parse(JSON.parse(fs.readFileSync(v1Path, 'utf8'))) : {}
+ fs.writeFileSync(v1Path, JSON.stringify({ ...v1, mode: 'local' }), { mode: 0o600 })
+ const v2Path = path.join(userData, 'connections.json')
+ if (fs.existsSync(v2Path)) {
+ const v2 = document.parse(JSON.parse(fs.readFileSync(v2Path, 'utf8')))
+ fs.writeFileSync(v2Path, JSON.stringify({ ...v2, primary: 'local', launchMode: 'primary', lastUsed: 'local' }), { mode: 0o600 })
+ }
+}
+
+interface BackendWindow extends Window {
+ hermesDesktop?: {
+ getConnection: () => Promise<{ baseUrl: string; mode?: string; logs: string[] }>
+ }
+}
+
+async function backendConnection(page: Page): Promise<{ baseUrl: string; mode?: string; logs: string[] }> {
+ return z.object({ baseUrl: z.string(), mode: z.string().optional(), logs: z.array(z.string()) }).parse(
+ await page.evaluate(async (): Promise<{ baseUrl: string; mode?: string; logs: string[] }> => {
+ // SAFETY: the desktop preload owns this bridge; its result is validated at the boundary.
+ const bridge = (window as BackendWindow).hermesDesktop
+ if (!bridge) { throw new Error('Desktop connection bridge is unavailable') }
+ const { baseUrl, mode, logs } = await bridge.getConnection()
+ return { baseUrl, mode, logs }
+ }),
+ )
+}
+
+function redact(text: string): string {
+ return text.replace(/([?&](?:token|ticket|key)=)[^&\s"']+/gi, '$1[redacted]')
+ .replace(/((?:authorization|api[_ -]?key|token|secret|password)\s*[:=]\s*)(?:Bearer\s+)?[^\s,"']+/gi, '$1[redacted]')
+}
+
+function captureBackendLogs(home: string, outDir: string, phase: string): void {
+ for (const name of ['desktop.log', 'errors.log', 'agent.log']) {
+ const filename = path.join(home, 'logs', name)
+ if (fs.existsSync(filename)) {
+ fs.writeFileSync(path.join(outDir, `desktop-${phase}-${name}`), redact(fs.readFileSync(filename, 'utf8')))
+ }
+ }
+}
+
+async function gracefulClose(app: ElectronApplication): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ await Promise.race([app.close(), new Promise<never>((_resolve, reject): void => {
+ timer = setTimeout((): void => reject(new Error('Desktop did not close gracefully')), 20_000)
+ })])
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+async function verifyRunningDesktop(app: ElectronApplication, options: SmokeOptions, launch: Launch): Promise<RunningDesktop> {
+ const running = await app.evaluate(({ app: electronApp }): RunningDesktop => {
+ // SAFETY: this callback runs in Electron main, whose process includes resourcesPath.
+ const runtime = process as ElectronProcess
+ return { pid: runtime.pid, executable: runtime.execPath, resources: runtime.resourcesPath, userData: electronApp.getPath('userData'), home: electronApp.getPath('home') }
+ })
+ if (fs.realpathSync(running.userData) !== fs.realpathSync(options['user-data']) || fs.realpathSync(running.home) !== fs.realpathSync(launch.env.HOME)) {
+ throw new Error('Desktop did not honor the isolated home and userData directories')
+ }
+ if (fs.realpathSync(running.executable) !== fs.realpathSync(options.exe)) {
+ throw new Error('Running Electron executable differs from --exe')
+ }
+ if (options.origin === 'bundled' && fs.realpathSync(path.join(running.resources, 'agent-payload')) !== fs.realpathSync(options.root)) {
+ throw new Error('Running Electron resources differ from the expected payload root')
+ }
+ return running
+}
+
+export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<void> {
+ const out = options.out
+ fs.mkdirSync(out, { recursive: true })
+ const receiptPath = path.join(out, `desktop-chat-${options.phase}.json`)
+ let mock: MockServer | undefined
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+ const consoleLines: string[] = []
+ try {
+ fs.accessSync(options.exe, fs.constants.X_OK)
+ fs.accessSync(options.root)
+ fs.mkdirSync(options.home, { recursive: true })
+ fs.mkdirSync(options['user-data'], { recursive: true })
+ const launch = resolveSmokeLaunch(options)
+ fs.mkdirSync(launch.env.HOME!, { recursive: true })
+ selectLocal(options['user-data'])
+ if (!options['mock-url']) { mock = await startMockServer() }
+ const mockUrl = validateMockUrl(options['mock-url'] ?? mock!.url)
+ writeMockProviderConfig(options.home, mockUrl)
+ writeEnvFile(options.home)
+ app = await _electron.launch({ ...launch, timeout: 120_000 })
+ app.process().stdout?.on('data', (chunk: Buffer): void => { consoleLines.push(redact(chunk.toString())) })
+ app.process().stderr?.on('data', (chunk: Buffer): void => { consoleLines.push(redact(chunk.toString())) })
+
+ page = await pickAppWindow(app, (message: string): void => { consoleLines.push(redact(message)) })
+ page.on('pageerror', (error: Error): void => { consoleLines.push(redact(error.message)) })
+ await prepareWindowForInput(app, page)
+ await waitForChatReady(page)
+ const running = await verifyRunningDesktop(app, options, launch)
+ const connection = await backendConnection(page)
+ const base = new URL(connection.baseUrl)
+ if (connection.mode !== 'local' || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname)) {
+ throw new Error('Required local backend was replaced by a remote connection')
+ }
+ const identity = await readChatIdentity(page)
+ if (options.origin === 'source' && fs.realpathSync(identity.hermesRoot) !== fs.realpathSync(options.root)) {
+ throw new Error('Desktop resolved a different source installation')
+ }
+ const backend = localBackendProcess(Number(base.port), running.pid)
+ assertBackendOrigin(backend, options.root, options.origin)
+ const provenanceCommit = readInstallationCommit(options.root, options.origin)
+ if (provenanceCommit !== options['expect-commit']) { throw new Error('Installed commit differs from --expect-commit') }
+ fs.writeFileSync(path.join(out, `desktop-backend-${options.phase}.log`), connection.logs.map(redact).join('\n'))
+ // Trace only chat actions. Connection probes can return credential-bearing logs.
+ await app.context().tracing.start({ screenshots: true, snapshots: false, sources: false })
+ const chat = await runDesktopChatSmoke(page, { mockUrl, phase: options.phase, outDir: out, expectCommit: options['expect-commit'], provenanceCommit })
+ fs.writeFileSync(receiptPath, `${JSON.stringify({ ...chat, status: 'closing' }, null, 2)}\n`)
+ const result = { ...chat, origin: options.origin, root: options.root, executable: options.exe, running,
+ localModeConfigured: true, backend: { ...backend, command: redact(backend.command) }, launchKind: options.phase === 'new' ? 'post-update-launch' : 'installed-launch' }
+ await app.context().tracing.stop({ path: path.join(out, `desktop-chat-${options.phase}.zip`) })
+ await gracefulClose(app)
+ app = undefined
+ fs.writeFileSync(receiptPath, `${JSON.stringify(result, null, 2)}\n`)
+ } catch (error) {
+ if (page) { await page.screenshot({ path: path.join(out, `desktop-chat-${options.phase}-failed.png`) }).catch((): void => {}) }
+ if (app) { await app.context().tracing.stop({ path: path.join(out, `desktop-chat-${options.phase}-failed.zip`) }).catch((): void => {}) }
+ fs.writeFileSync(receiptPath, `${JSON.stringify({ status: 'failed', phase: options.phase, origin: options.origin, root: options.root,
+ executable: options.exe, expectedCommit: options['expect-commit'], error: redact(String(error)) }, null, 2)}\n`)
+ throw error
+ } finally {
+ fs.writeFileSync(path.join(out, `desktop-app-${options.phase}.log`), consoleLines.join('\n'))
+ try {
+ captureBackendLogs(options.home, out, options.phase)
+ } finally {
+ if (app) { await gracefulClose(app).catch((error: Error): void => { console.error(redact(error.message)) }) }
+ if (mock) { await mock.close() }
+ }
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const { values } = parseArgs({ options: {
+ exe: { type: 'string' }, root: { type: 'string' }, origin: { type: 'string' }, home: { type: 'string' },
+ 'user-data': { type: 'string' }, out: { type: 'string' }, phase: { type: 'string' },
+ 'expect-commit': { type: 'string' }, 'launch-spec': { type: 'string' }, 'mock-url': { type: 'string' },
+ } })
+ try {
+ await runInstalledDesktopSmoke(optionsSchema.parse(values))
+ } catch (error) {
+ console.error(redact(String(error)))
+ process.exitCode = 1
+ }
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/drive-update.cjs b/tests/install/e2e-assets/drive-update.cjs
index fb8663ce1df..1eeff0b8ddb 100644
--- a/tests/install/e2e-assets/drive-update.cjs
+++ b/tests/install/e2e-assets/drive-update.cjs
@@ -2,11 +2,10 @@
// app) under Playwright's Electron driver and perform the update the way a
// user does: Settings -> About -> "Update now". Screenshots at every step.
//
-// Run from the installed checkout's apps/desktop directory (so
-// @playwright/test resolves from ITS node_modules — the same deps the
-// installed app was built with):
+// Run the current CI checkout's entrypoint with its locked driver deps:
//
-// node <this file> <path-to-Hermes.exe> <proof-dir>
+// node <this file> <path-to-Hermes.exe> <proof-dir> <old-sha> [--native-handoff]
+// --native-handoff leaves the native UIA caller in charge of clicking Update.
//
// Exit codes: 0 = update hand-off started and the app quit (the detached
// updater takes it from there — the PowerShell driver polls for the result);
@@ -26,9 +25,11 @@ const { pickAppWindow, openAbout, waitForUpdate } = require('./update-ui.cjs')
const exePath = process.argv[2]
const proofDir = process.argv[3]
+const oldSha = process.argv[4]
+const nativeHandoff = process.argv[5] === '--native-handoff'
-if (!exePath || !proofDir) {
- console.error('usage: node drive-update.cjs <Hermes.exe> <proof-dir>')
+if (!exePath || !proofDir || !oldSha || !process.env.HERMES_E2E_MOCK_URL) {
+ console.error('usage: node drive-update.cjs <Hermes.exe> <proof-dir> <old-sha> [--native-handoff]; HERMES_E2E_MOCK_URL required')
process.exit(1)
}
@@ -59,37 +60,47 @@ const killer = setTimeout(() => {
killer.unref()
async function main() {
+ const { runUpdateWindowChat, updateWindowEnvironment } = await import('./update-window-chat.mjs')
+ const origin = nativeHandoff ? 'bundled' : 'source'
+ const root = nativeHandoff ? path.join(path.dirname(exePath), 'resources', 'agent-payload') : path.join(process.env.HERMES_HOME, 'hermes-agent')
log(`launching ${exePath}`)
const app = await _electron.launch({
executablePath: exePath,
- args: ['--disable-gpu', '--no-sandbox'],
+ args: ['--disable-gpu', '--no-sandbox', '--force-renderer-accessibility'],
+ cwd: path.dirname(exePath),
// Inherit the driver's env: HERMES_HOME (isolated install) and
// GIT_CONFIG_GLOBAL (URL redirect to the staged serve repo) MUST reach
// the main process so its update check fetches from the staged repo.
- env: { ...process.env },
+ env: updateWindowEnvironment(process.env, root, origin),
timeout: 120_000
})
const child = app.process()
const waitForProcessClose = observeProcessClose(child)
- log(`launched Electron pid=${child.pid}`)
+ // On Windows Playwright's child is a shell wrapper, not Hermes.exe.
+ const appPid = await app.evaluate(() => process.pid)
+ log(`launched Electron pid=${appPid}`)
const page = await pickAppWindow(app, log)
await prepareWindowForInput(app, page)
log('[zoom] app window prepared at 100%')
- // Boot: wait for the composer to exist — the shell is mounted by then.
- // The real backend (`hermes serve`) is booting underneath; give it time.
- await page.waitForSelector('textarea, [contenteditable="true"]', {
- state: 'attached',
- timeout: 300_000
+ await runUpdateWindowChat(app, page, {
+ mockUrl: process.env.HERMES_E2E_MOCK_URL, outDir: proofDir,
+ expectCommit: oldSha,
+ origin, root, executable: exePath,
})
- log('renderer booted (composer attached)')
- await page.waitForTimeout(3000)
await shot(page, '01-app-booted')
+ if (nativeHandoff) {
+ fs.writeFileSync(path.join(proofDir, 'old-chat-ready.json'), JSON.stringify({ pid: appPid, exe: exePath, oldSha }) + '\n')
+ await waitForProcessClose(15 * 60 * 1000)
+ log('native OLD process closed; the OS updater owns relaunch')
+ return
+ }
+
await openAbout(page, { log, shot, prepare: () => prepareWindowForInput(app, page) })
const updateNow = await waitForUpdate(page, { log, shot })
diff --git a/tests/install/e2e-assets/launch-from-spec.mjs b/tests/install/e2e-assets/launch-from-spec.mjs
index cdd8a29996f..422a0ac1a56 100644
--- a/tests/install/e2e-assets/launch-from-spec.mjs
+++ b/tests/install/e2e-assets/launch-from-spec.mjs
@@ -10,12 +10,12 @@
* real executable, and the electron npm shim would re-spawn out of our
* control).
*
- * Usage (from the scratch dir where the driver installed @playwright/test):
+ * Usage (current CI checkout with locked driver dependencies):
* node launch-from-spec.mjs --spec /path/launch-spec.json \
* [--result $HERMES_HOME/.hermes-update-result.json] \
* [--expect-sha <sha> --repo-dir <install dir>] [--no-update]
*
- * --no-update: launch + wait for the window + close. The smoke arm.
+ * --no-update: require a real desktop chat, then close gracefully.
* Otherwise: click Update now, then require a new successful handoff result
* or source-update receipt, the expected checkout, and marker removal.
* A checkout reset alone is not completion. No driver-assisted relaunch,
@@ -32,6 +32,7 @@ import { _electron } from '@playwright/test';
import { prepareWindowForInput } from './window-input.cjs';
import { pickAppWindow, openAbout, waitForUpdate } from './update-ui.cjs';
import { observeSourceUpdate } from './source-update-observer.mjs';
+import { runUpdateWindowChat, updateWindowEnvironment } from './update-window-chat.mjs';
/**
* @typedef {{argv: string[], cwd: string, env: Record<string, string>,
@@ -106,11 +107,17 @@ async function main() {
result: { type: 'string' },
'expect-sha': { type: 'string' },
'repo-dir': { type: 'string' },
+ 'old-sha': { type: 'string' },
+ 'chat-out': { type: 'string' },
+ 'mock-url': { type: 'string' },
'no-update': { type: 'boolean', default: false },
'timeout-ms': { type: 'string', default: '600000' },
},
});
if (!values.spec) throw new Error('--spec is required');
+ if (!values['old-sha'] || !values['chat-out'] || !values['mock-url'] || !values['repo-dir']) {
+ throw new Error('--old-sha, --chat-out, --mock-url and --repo-dir are required for OLD chat');
+ }
/** @type {LaunchSpec} */
const spec = JSON.parse(fs.readFileSync(values.spec, 'utf8'));
const launch = resolveLaunch(spec);
@@ -121,7 +128,7 @@ async function main() {
executablePath: launch.executablePath,
args: launch.args,
cwd: launch.cwd,
- env: launch.env,
+ env: updateWindowEnvironment(launch.env, values['repo-dir'], 'source'),
});
const window = await pickAppWindow(app, log);
await window.screenshot({ path: `${values.spec}.window.png` }).catch(() => {});
@@ -129,9 +136,16 @@ async function main() {
await prepareWindowForInput(app, window);
log('[zoom] app window prepared at 100%');
+ phase('old-chat');
+ await runUpdateWindowChat(app, window, {
+ mockUrl: values['mock-url'], outDir: values['chat-out'],
+ expectCommit: values['old-sha'],
+ root: values['repo-dir'], origin: 'source', executable: launch.executablePath,
+ });
+
if (values['no-update']) {
- log('smoke mode: window proven, closing');
- await app.close().catch(() => {});
+ log('smoke mode: OLD desktop chat proven, closing');
+ await app.close();
process.exit(0);
}
diff --git a/tests/install/e2e-assets/mac-bundled-update-driver.mjs b/tests/install/e2e-assets/mac-bundled-update-driver.mjs
index c537d99448f..c17e316bd0b 100644
--- a/tests/install/e2e-assets/mac-bundled-update-driver.mjs
+++ b/tests/install/e2e-assets/mac-bundled-update-driver.mjs
@@ -23,6 +23,7 @@ import path from 'node:path';
import { parseArgs } from 'node:util';
import { _electron } from '@playwright/test';
import { createRequire } from 'node:module';
+import { runUpdateWindowChat, updateWindowEnvironment } from './update-window-chat.mjs';
const require = createRequire(import.meta.url);
const { observeProcessClose } = require('./process-close.cjs');
@@ -33,6 +34,9 @@ const { values } = parseArgs({
options: {
'app-bin': { type: 'string' },
shots: { type: 'string', default: '.' },
+ 'old-sha': { type: 'string' },
+ 'chat-out': { type: 'string' },
+ 'mock-url': { type: 'string' },
'close-timeout-ms': { type: 'string', default: '420000' },
},
});
@@ -43,31 +47,37 @@ const shot = async (page, name) => {
};
const appBin = values['app-bin'];
+if (!appBin || !values['old-sha'] || !values['chat-out'] || !values['mock-url']) {
+ throw new Error('--app-bin, --old-sha, --chat-out and --mock-url are required');
+}
fs.mkdirSync(values.shots, { recursive: true });
+fs.mkdirSync(values['chat-out'], { recursive: true });
log(`launching ${appBin}`);
const app = await _electron.launch({
executablePath: appBin,
+ cwd: path.dirname(appBin),
// Inherit the driver env: HERMES_HOME / HOME / updates feed config must
// reach the main process exactly as a user's double-click would.
- env: { ...process.env },
+ env: updateWindowEnvironment(process.env, path.resolve(path.dirname(appBin), '..', 'Resources', 'agent-payload'), 'bundled'),
timeout: 120_000,
});
const child = app.process();
-const oldPid = child.pid;
-log(`launched Electron pid=${oldPid}`);
-fs.writeFileSync(path.join(values.shots, 'old-pid'), `${oldPid}\n`);
-
const waitForProcessClose = observeProcessClose(child);
+const oldPid = await app.evaluate(() => process.pid);
+log(`launched Electron pid=${oldPid}`);
+fs.writeFileSync(path.join(values['chat-out'], 'old-pid'), `${oldPid}\n`);
const page = await pickAppWindow(app, log);
await prepareWindowForInput(app, page);
-// Boot: the shell is mounted once the composer exists.
-await page.waitForSelector('textarea, [contenteditable="true"]', { state: 'attached', timeout: 300_000 });
-log('renderer booted (composer attached)');
-await page.waitForTimeout(3_000);
+await runUpdateWindowChat(app, page, {
+ mockUrl: values['mock-url'], outDir: values['chat-out'],
+ expectCommit: values['old-sha'],
+ origin: 'bundled', executable: appBin,
+ root: path.resolve(path.dirname(appBin), '..', 'Resources', 'agent-payload'),
+});
await shot(page, '01-app-booted');
await openAbout(page, { log, shot, prepare: () => prepareWindowForInput(app, page) });
@@ -85,5 +95,5 @@ await shot(page, '05-updating-overlay');
// observeProcessClose released our pipes, so ShipIt's relaunch survives.
await waitForProcessClose(Number(values['close-timeout-ms']));
log('old Electron process closed — Squirrel.Mac owns the swap and relaunch');
-fs.writeFileSync(path.join(values.shots, 'old-exited'), new Date().toISOString() + '\n');
+fs.writeFileSync(path.join(values['chat-out'], 'old-exited'), new Date().toISOString() + '\n');
process.exit(0);
diff --git a/tests/install/e2e-assets/mock-provider.mjs b/tests/install/e2e-assets/mock-provider.mjs
index d56ca9a9c65..c252e213802 100644
--- a/tests/install/e2e-assets/mock-provider.mjs
+++ b/tests/install/e2e-assets/mock-provider.mjs
@@ -5,27 +5,28 @@
//
// Usage: node mock-provider.mjs <url-file>
// Writes "<url-file>" with the base URL (http://127.0.0.1:<port>) once
-// the server is listening, then stays alive until stdin closes.
+// the server is listening, then stays alive until SIGINT or SIGTERM.
// @ts-check
import fs from 'node:fs';
import process from 'node:process';
-import { fileURLToPath } from 'node:url';
-
-const mockUrl = fileURLToPath(new URL('../../../tests-js/scripts/mock-server.ts', import.meta.url));
-
-const { startMockServer } = await import(mockUrl);
-const mock = await startMockServer();
+import { startMockServer } from '../../../tests-js/scripts/mock-server.ts';
const urlFile = process.argv[2];
if (!urlFile) {
console.error('usage: node mock-provider.mjs <url-file>');
process.exit(1);
}
+const mock = await startMockServer();
fs.writeFileSync(urlFile, mock.url);
console.log(`[mock-provider] listening at ${mock.url}`);
-// Live until killed. NOT gated on stdin closing: a backgrounded process's
-// stdin is already at EOF, so an end-event exit would fire immediately
-// and the server would die right after writing its URL.
+for (const signal of ['SIGINT', 'SIGTERM']) {
+ process.once(signal, async () => {
+ await mock.close();
+ process.exit(0);
+ });
+}
+
+// A background shell starts with stdin at EOF; signals own this lifetime.
await new Promise(() => {});
diff --git a/tests/install/e2e-assets/mock-provider.sh b/tests/install/e2e-assets/mock-provider.sh
index 14adbcabc86..0b127fbed80 100755
--- a/tests/install/e2e-assets/mock-provider.sh
+++ b/tests/install/e2e-assets/mock-provider.sh
@@ -41,25 +41,10 @@ mock_start() {
fi
local url
url="$(cat "$MOCK_URLFILE")"
+ export HERMES_E2E_MOCK_URL="$url"
ok "mock inference server: $url"
- # The provider config, byte-compatible with writeMockConfig() in
- # tests-js/scripts/mock-server.ts.
- cat > "$HERMES_HOME/config.yaml" <<EOF
-model:
- default: mock-model
- provider: mock
-providers:
- mock:
- api: $url/v1
- name: Mock
- api_mode: chat_completions
- key_env: MOCK_API_KEY
- models:
- mock-model: {}
- context_length: 64000
-EOF
- printf 'MOCK_API_KEY=e2e-mock-key\n' >> "$HERMES_HOME/.env"
+ node "$ASSETS/../../../tests-js/scripts/mock-provider-config.ts" "$HERMES_HOME" "$url" || fail "mock provider config failed"
ok "provider 'mock' configured in $HERMES_HOME (api $url/v1)"
}
diff --git a/tests/install/e2e-assets/source-build-env.ps1 b/tests/install/e2e-assets/source-build-env.ps1
new file mode 100644
index 00000000000..394110c0ef2
--- /dev/null
+++ b/tests/install/e2e-assets/source-build-env.ps1
@@ -0,0 +1,17 @@
+# Child installers/builds stamp their checkout; restore the workflow identity even on failure.
+function Invoke-SourceBuild([scriptblock]$Action) {
+ $saved = @{}
+ $names = @('GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME', 'GITHUB_HEAD_REF', 'GITHUB_BASE_REF',
+ 'HERMES_BUILD_COMMIT', 'HERMES_PAYLOAD_TAG', 'HERMES_PAYLOAD_VERSION', 'HERMES_DESKTOP_VARIANT')
+ try {
+ foreach ($name in $names) {
+ $saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
+ [Environment]::SetEnvironmentVariable($name, $null, 'Process')
+ }
+ & $Action
+ } finally {
+ foreach ($name in $names) {
+ [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process')
+ }
+ }
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/source-build-env.sh b/tests/install/e2e-assets/source-build-env.sh
new file mode 100644
index 00000000000..a229afa1515
--- /dev/null
+++ b/tests/install/e2e-assets/source-build-env.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# OLD and NEW must stamp the checked-out source, not the CI driver's ref.
+# A subshell preserves the workflow's identity and the git URL redirect.
+source_build_env() (
+ unset GITHUB_SHA GITHUB_REF GITHUB_REF_NAME GITHUB_HEAD_REF GITHUB_BASE_REF
+ unset HERMES_BUILD_COMMIT HERMES_PAYLOAD_TAG HERMES_PAYLOAD_VERSION HERMES_DESKTOP_VARIANT
+ "$@"
+)
\ No newline at end of file
diff --git a/tests/install/e2e-assets/source-desktop-smoke.mjs b/tests/install/e2e-assets/source-desktop-smoke.mjs
new file mode 100644
index 00000000000..b20f6aea6f3
--- /dev/null
+++ b/tests/install/e2e-assets/source-desktop-smoke.mjs
@@ -0,0 +1,54 @@
+// Read-only source checkpoint adapter. Tooling is resolved from the CI checkout,
+// never from the historical installation. The standalone driver owns the app.
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { parseArgs } from 'node:util';
+
+const { values } = parseArgs({ options: {
+ root: { type: 'string' }, home: { type: 'string' },
+ 'user-data': { type: 'string' }, out: { type: 'string' },
+ phase: { type: 'string' }, 'expect-commit': { type: 'string' },
+ desktop: { type: 'string' }, method: { type: 'string' },
+ 'mock-url': { type: 'string' },
+} });
+for (const key of ['root', 'home', 'user-data', 'out', 'phase', 'expect-commit', 'desktop', 'method']) {
+ if (!values[key]) throw new Error(`--${key} is required`);
+}
+if (!['old', 'new'].includes(values.phase)) throw new Error('expected --phase old|new');
+if (!['absent', 'present'].includes(values.desktop)) throw new Error('expected --desktop absent|present');
+fs.mkdirSync(values.out, { recursive: true });
+if (values.desktop === 'absent') {
+ fs.writeFileSync(path.join(values.out, `desktop-chat-${values.phase}.json`), JSON.stringify({
+ status: 'not-applicable', phase: values.phase, method: values.method,
+ expectedCommit: values['expect-commit'], origin: 'source', reason: 'selected route does not install desktop',
+ }, null, 2) + '\n');
+} else try {
+ fs.rmSync(path.join(values.out, `desktop-chat-${values.phase}.json`), { force: true });
+ const release = path.join(values.root, 'apps', 'desktop', 'release');
+ const candidates = {
+ linux: ['linux-unpacked/Hermes', 'linux-unpacked/hermes'],
+ darwin: [process.arch === 'arm64' ? 'mac-arm64/Hermes.app/Contents/MacOS/Hermes' : 'mac/Hermes.app/Contents/MacOS/Hermes'],
+ win32: [process.arch === 'arm64' ? 'win-arm64-unpacked/Hermes.exe' : 'win-unpacked/Hermes.exe'],
+ }[process.platform];
+ if (!candidates) throw new Error(`unsupported source smoke host: ${process.platform}`);
+ const executables = candidates.map(p => path.join(release, p)).filter(p => fs.existsSync(p));
+ if (executables.length !== 1) throw new Error(`expected exactly one installed desktop executable, found ${executables.length} under ${release}`);
+ const driver = fileURLToPath(new URL('./desktop-smoke.ts', import.meta.url));
+ const args = [driver, '--exe', executables[0], '--origin', 'source'];
+ for (const key of ['root', 'home', 'user-data', 'out', 'phase', 'expect-commit']) args.push(`--${key}`, values[key]);
+ const mockUrl = values['mock-url'] || process.env.HERMES_E2E_MOCK_URL;
+ if (mockUrl) args.push('--mock-url', mockUrl);
+ const result = spawnSync(process.execPath, args, { stdio: 'inherit', cwd: values.root });
+ if (result.error) throw result.error;
+ if (result.status !== 0) throw new Error(`Desktop smoke process failed: exit=${result.status}, signal=${result.signal}`);
+} catch (error) {
+ const receiptPath = path.join(values.out, `desktop-chat-${values.phase}.json`);
+ const prior = fs.existsSync(receiptPath) ? JSON.parse(fs.readFileSync(receiptPath, 'utf8')) : {};
+ fs.writeFileSync(receiptPath, JSON.stringify({ ...prior, status: 'failed', phase: values.phase,
+ origin: 'source', expectedCommit: values['expect-commit'], method: values.method,
+ error: String(error) }, null, 2) + '\n');
+ console.error(error);
+ process.exitCode = 1;
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/update-window-chat.mjs b/tests/install/e2e-assets/update-window-chat.mjs
new file mode 100644
index 00000000000..b35eb49473e
--- /dev/null
+++ b/tests/install/e2e-assets/update-window-chat.mjs
@@ -0,0 +1,103 @@
+// The caller owns OLD's lifetime. Record backend provenance in the same receipt
+// as the shared chat assertion without launching a second app or provider.
+import fs from 'node:fs';
+import path from 'node:path';
+import { readChatIdentity, runDesktopChatSmoke, waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke.ts';
+import { assertBackendOrigin, localBackendProcess, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts';
+import { smokeEnvironment } from './desktop-smoke.ts';
+
+// Source updater processes still need the git redirect; smokeEnvironment keeps
+// it while removing driver activation, credentials and remote/backend overrides.
+/** @param {NodeJS.ProcessEnv} inherited @param {string} root @param {'source'|'bundled'} origin */
+export function updateWindowEnvironment(inherited, root, origin) {
+ const home = inherited.HERMES_HOME;
+ const userData = inherited.HERMES_DESKTOP_USER_DATA_DIR;
+ if (!home || !userData) throw new Error('Update chat requires isolated HERMES_HOME and HERMES_DESKTOP_USER_DATA_DIR');
+ const env = smokeEnvironment(inherited, home, userData);
+ // The detached source updater builds NEW in this environment too.
+ for (const key of ['GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME', 'GITHUB_HEAD_REF', 'GITHUB_BASE_REF']) {
+ delete env[key];
+ }
+ fs.mkdirSync(env.HOME, { recursive: true });
+ fs.mkdirSync(userData, { recursive: true });
+ for (const [filename, local] of [
+ ['connection.json', { mode: 'local' }],
+ ['connections.json', { primary: 'local', launchMode: 'primary', lastUsed: 'local' }],
+ ]) {
+ const file = path.join(userData, filename);
+ if (filename === 'connections.json' && !fs.existsSync(file)) continue;
+ const prior = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
+ fs.writeFileSync(file, JSON.stringify({ ...prior, ...local }), { mode: 0o600 });
+ }
+ if (origin === 'source') {
+ const editableRoot = inherited.HERMES_PYTHON_SRC_ROOT;
+ if (editableRoot) {
+ if (!path.isAbsolute(editableRoot) || fs.realpathSync(editableRoot) !== fs.realpathSync(root)) {
+ throw new Error('Captured HERMES_PYTHON_SRC_ROOT differs from the installed source');
+ }
+ env.HERMES_PYTHON_SRC_ROOT = editableRoot;
+ }
+ for (const key of ['HERMES_DESKTOP_PYTHON', 'HERMES_DESKTOP_HERMES', 'HERMES_DESKTOP_HERMES_ROOT']) {
+ if (inherited[key]) {
+ if (!path.isAbsolute(inherited[key]) || (key !== 'HERMES_DESKTOP_PYTHON' && !within(root, inherited[key]))) throw new Error(`Captured ${key} escapes the installed source`);
+ fs.accessSync(inherited[key]);
+ env[key] = inherited[key];
+ }
+ }
+ }
+ return env;
+}
+
+/**
+ * @param {import('@playwright/test').ElectronApplication} app
+ * @param {import('@playwright/test').Page} page
+ * @param {{mockUrl: string, outDir: string, expectCommit: string,
+ * origin: 'source'|'bundled', root: string, executable: string}} options
+ */
+export async function runUpdateWindowChat(app, page, options) {
+ const receiptPath = path.join(options.outDir, 'desktop-chat-old.json');
+ fs.mkdirSync(options.outDir, { recursive: true });
+ try {
+ const running = await app.evaluate(({ app: electronApp }) => ({
+ pid: process.pid, executable: process.execPath, resources: process.resourcesPath,
+ userData: electronApp.getPath('userData'),
+ }));
+ const { userData } = running;
+ if (!process.env.HERMES_DESKTOP_USER_DATA_DIR || fs.realpathSync(userData) !== fs.realpathSync(process.env.HERMES_DESKTOP_USER_DATA_DIR)) {
+ throw new Error('OLD update window did not honor isolated userData');
+ }
+ if (fs.realpathSync(running.executable) !== fs.realpathSync(options.executable)) {
+ throw new Error('OLD update window executable differs from the installed app');
+ }
+ if (options.origin === 'bundled' && fs.realpathSync(path.join(running.resources, 'agent-payload')) !== fs.realpathSync(options.root)) {
+ throw new Error('OLD update window resources differ from the installed payload');
+ }
+ await waitForChatReady(page);
+ const identity = await readChatIdentity(page);
+ const connection = await page.evaluate(() => window.hermesDesktop.getConnection());
+ const base = new URL(connection.baseUrl);
+ if (connection.mode !== 'local' || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname)) {
+ throw new Error('OLD update-window chat did not use the local installed backend');
+ }
+ if (options.origin === 'source' && fs.realpathSync(identity.hermesRoot) !== fs.realpathSync(options.root)) {
+ throw new Error('OLD update-window chat resolved another source installation');
+ }
+ const backend = localBackendProcess(Number(base.port), running.pid);
+ assertBackendOrigin(backend, options.root, options.origin);
+ const provenanceCommit = readInstallationCommit(options.root, options.origin);
+ if (provenanceCommit !== options.expectCommit) throw new Error('Installed OLD commit differs from the expected commit');
+ const chat = await runDesktopChatSmoke(page, { ...options, phase: 'old', provenanceCommit });
+ const result = { ...chat, origin: options.origin, root: options.root,
+ executable: options.executable, appPid: running.pid,
+ backend: { pid: backend.pid, parentPid: backend.parentPid, executable: backend.executable },
+ localModeConfigured: true, userData,
+ launchKind: 'pre-update-window' };
+ fs.writeFileSync(receiptPath, JSON.stringify(result, null, 2) + '\n');
+ } catch (error) {
+ await page.screenshot({ path: path.join(options.outDir, 'desktop-chat-old-failed.png') }).catch(() => {});
+ fs.writeFileSync(receiptPath, JSON.stringify({ status: 'failed', phase: 'old',
+ expectedCommit: options.expectCommit, origin: options.origin, root: options.root,
+ error: String(error) }, null, 2) + '\n');
+ throw error;
+ }
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/windows-bundle-metadata.ps1 b/tests/install/e2e-assets/windows-bundle-metadata.ps1
new file mode 100644
index 00000000000..74fbcfc75a4
--- /dev/null
+++ b/tests/install/e2e-assets/windows-bundle-metadata.ps1
@@ -0,0 +1,71 @@
+# Metadata-only readers shared by native admission and pure XML/archive tests.
+function Read-SmokeXmlEntry($Zip, [string]$Name) {
+ $entries = @($Zip.Entries | Where-Object { $_.FullName -ceq $Name })
+ if ($entries.Count -ne 1) { throw "Expected exactly one $Name" }
+ $settings = [Xml.XmlReaderSettings]::new()
+ $settings.DtdProcessing = [Xml.DtdProcessing]::Prohibit
+ $settings.XmlResolver = $null
+ $stream = $entries[0].Open()
+ $reader = [Xml.XmlReader]::Create($stream, $settings)
+ try {
+ $xml = [Xml.XmlDocument]::new()
+ $xml.XmlResolver = $null
+ $xml.Load($reader)
+ return ,$xml
+ } finally { $reader.Dispose(); $stream.Dispose() }
+}
+
+function Assert-SmokeIdentity($Identity, $Expected) {
+ if (-not $Identity -or $Identity.GetAttribute('Name') -cne $Expected.msixIdentity -or
+ $Identity.GetAttribute('Publisher') -cne $Expected.publisher) { throw 'Package identity/publisher mismatch' }
+ $version = $Identity.GetAttribute('Version')
+ if ($version -cnotmatch '^\d+\.\d+\.\d+\.\d+$' -or
+ @($version.Split('.') | Where-Object { [int]$_ -gt 65535 }).Count) { throw 'Invalid package version' }
+ return $version
+}
+
+function Assert-SmokeRelativePath([string]$Path) {
+ if (-not $Path -or $Path -match '^[\\/]|:|(^|[\\/])\.\.?([\\/]|$)') {
+ throw "Unsafe package relative path: $Path"
+ }
+}
+
+function Read-SmokePackageManifest([xml]$Xml, [string]$Arch, $Expected) {
+ $identities = @($Xml.SelectNodes('/*[local-name()="Package"]/*[local-name()="Identity"]'))
+ if ($identities.Count -ne 1) { throw 'Expected one package identity' }
+ $identity = $identities[0]
+ $version = Assert-SmokeIdentity $identity $Expected
+ if ($identity.GetAttribute('ProcessorArchitecture') -cne $Arch) { throw 'Package lacks requested native architecture' }
+ $applications = @($Xml.SelectNodes('/*[local-name()="Package"]/*[local-name()="Applications"]/*[local-name()="Application"]') |
+ Where-Object { $_.GetAttribute('Id') -ceq $Expected.applicationId })
+ if ($applications.Count -ne 1) { throw 'Expected exactly one desktop applicationId' }
+ $exe = $applications[0].GetAttribute('Executable')
+ Assert-SmokeRelativePath $exe
+ return [pscustomobject]@{ Version=$version; Architecture=$Arch; Executable=$exe; Slice=$null }
+}
+
+function Read-BundleSmokeMetadata([string]$Artifact, [string]$Arch, $Expected) {
+ $zip = [IO.Compression.ZipFile]::OpenRead($Artifact)
+ try {
+ switch ([IO.Path]::GetExtension($Artifact).ToLowerInvariant()) {
+ '.msix' {
+ return Read-SmokePackageManifest (Read-SmokeXmlEntry $zip 'AppxManifest.xml') $Arch $Expected
+ }
+ '.msixbundle' {
+ $xml = Read-SmokeXmlEntry $zip 'AppxMetadata/AppxBundleManifest.xml'
+ $identities = @($xml.SelectNodes('/*[local-name()="Bundle"]/*[local-name()="Identity"]'))
+ if ($identities.Count -ne 1) { throw 'Expected one bundle identity' }
+ $version = Assert-SmokeIdentity $identities[0] $Expected
+ $slices = @($xml.SelectNodes('/*[local-name()="Bundle"]/*[local-name()="Packages"]/*[local-name()="Package"]') |
+ Where-Object { $_.GetAttribute('Type') -ceq 'application' -and $_.GetAttribute('Architecture') -ceq $Arch })
+ if ($slices.Count -ne 1) { throw 'Expected exactly one native application slice (no emulation fallback)' }
+ $slice = $slices[0].GetAttribute('FileName')
+ Assert-SmokeRelativePath $slice
+ if (@($zip.Entries | Where-Object { $_.FullName -ceq $slice }).Count -ne 1) { throw 'Native package bytes missing or ambiguous' }
+ if ($slices[0].GetAttribute('Version') -cne $version) { throw 'Native slice and bundle version mismatch' }
+ return [pscustomobject]@{ Version=$version; Architecture=$Arch; Executable=$null; Slice=$slice }
+ }
+ default { throw 'Expected a receipt-selected MSIX or MSIXBUNDLE' }
+ }
+ } finally { $zip.Dispose() }
+}
\ No newline at end of file
diff --git a/tests/install/e2e-assets/windows-bundle-metadata.test.ps1 b/tests/install/e2e-assets/windows-bundle-metadata.test.ps1
new file mode 100644
index 00000000000..7fb39abd7ca
--- /dev/null
+++ b/tests/install/e2e-assets/windows-bundle-metadata.test.ps1
@@ -0,0 +1,45 @@
+# Pure archive/XML admission tests: no package deployment or host impersonation.
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+. (Join-Path $PSScriptRoot 'windows-bundle-metadata.ps1')
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+$temp = Join-Path ([IO.Path]::GetTempPath()) ('bundle-metadata-' + [Guid]::NewGuid())
+New-Item -ItemType Directory -Path $temp | Out-Null
+$expected = [pscustomobject]@{ msixIdentity='Fixture.Hermes'; publisher='CN=Fixture'; applicationId='Hermes' }
+function Archive([string]$Name, [string]$Entry, [string]$Xml, [string[]]$Extra = @()) {
+ $file = Join-Path $temp $Name
+ $zip = [IO.Compression.ZipFile]::Open($file, [IO.Compression.ZipArchiveMode]::Create)
+ try {
+ $writer = [IO.StreamWriter]::new($zip.CreateEntry($Entry).Open())
+ try { $writer.Write($Xml) } finally { $writer.Dispose() }
+ foreach ($name in $Extra) { $zip.CreateEntry($name) | Out-Null }
+ } finally { $zip.Dispose() }
+ return $file
+}
+function Reject([scriptblock]$Action) {
+ $rejected = $false
+ try { & $Action | Out-Null } catch { $rejected = $true }
+ if (-not $rejected) { throw 'Admission unexpectedly accepted invalid metadata' }
+}
+try {
+ $xml = '<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"><Identity Name="Fixture.Hermes" Publisher="CN=Fixture" Version="1.2.3.0" ProcessorArchitecture="arm64"/><Applications><Application Id="Hermes" Executable="app\Hermes.exe"/></Applications></Package>'
+ $file = Archive 'native.msix' 'AppxManifest.xml' $xml
+ $got = Read-BundleSmokeMetadata $file 'arm64' $expected
+ if ($got.Version -cne '1.2.3.0' -or $got.Executable -cne 'app\Hermes.exe') { throw 'MSIX metadata lost' }
+ Reject { Read-BundleSmokeMetadata $file 'x64' $expected }
+ $wrong = Archive 'wrong.msix' 'AppxManifest.xml' ($xml.Replace('CN=Fixture', 'CN=Other'))
+ Reject { Read-BundleSmokeMetadata $wrong 'arm64' $expected }
+ $escape = Archive 'escape.msix' 'AppxManifest.xml' ($xml.Replace('app\Hermes.exe', '..\outside.exe'))
+ Reject { Read-BundleSmokeMetadata $escape 'arm64' $expected }
+ $bundle = '<Bundle xmlns="http://schemas.microsoft.com/appx/2013/bundle"><Identity Name="Fixture.Hermes" Publisher="CN=Fixture" Version="1.2.3.0"/><Packages><Package Type="application" Architecture="x64" Version="1.2.3.0" FileName="x64.msix"/><Package Type="application" Architecture="arm64" Version="1.2.3.0" FileName="arm64.msix"/></Packages></Bundle>'
+ $file = Archive 'universal.msixbundle' 'AppxMetadata/AppxBundleManifest.xml' $bundle @('x64.msix','arm64.msix')
+ foreach ($arch in @('arm64','x64')) {
+ $got = Read-BundleSmokeMetadata $file $arch $expected
+ if ($got.Slice -cne "$arch.msix") { throw 'Wrong native slice selected' }
+ }
+ $missing = Archive 'missing.msixbundle' 'AppxMetadata/AppxBundleManifest.xml' ($bundle.Replace('Architecture="arm64"', 'Architecture="x86"')) @('x64.msix','arm64.msix')
+ Reject { Read-BundleSmokeMetadata $missing 'arm64' $expected }
+ $duplicate = Archive 'duplicate.msixbundle' 'AppxMetadata/AppxBundleManifest.xml' ($bundle.Replace('Architecture="x64"', 'Architecture="arm64"')) @('x64.msix','arm64.msix')
+ Reject { Read-BundleSmokeMetadata $duplicate 'arm64' $expected }
+ Write-Output 'PASS: MSIX identity/executable and MSIXBUNDLE native-slice admission'
+} finally { Remove-Item -LiteralPath $temp -Recurse -Force }
\ No newline at end of file
diff --git a/tests/install/installer-script-e2e.sh b/tests/install/installer-script-e2e.sh
index 2eecf3d0096..74c60e867b2 100755
--- a/tests/install/installer-script-e2e.sh
+++ b/tests/install/installer-script-e2e.sh
@@ -85,6 +85,9 @@ case "$UPDATE_METHOD" in
esac
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+ASSETS="$REPO_ROOT/tests/install/e2e-assets"
+# Pin driver tooling before an installer changes PATH. CI prepares locked deps.
+export HERMES_E2E_NODE="${HERMES_E2E_NODE:-$(command -v node)}"
# Everything lives OUTSIDE the checkout; an untracked dir inside the repo
# would make later dirty-tree checks lie.
@@ -103,6 +106,8 @@ source "$(dirname "$0")/e2e-assets/preserve-plugins.sh"
source "$(dirname "$0")/e2e-assets/source-driver.sh"
# shellcheck source=e2e-assets/installer-common.sh
source "$(dirname "$0")/e2e-assets/installer-common.sh"
+# shellcheck source=e2e-assets/source-build-env.sh
+source "$ASSETS/source-build-env.sh"
# Full transcript in the job log, collapsed (GitHub renders ::group:: as a
# fold; plain text anywhere else). Win or lose -- a green install's log is
# how you diagnose the leg that fails next.
@@ -162,6 +167,7 @@ export HOME="$WORK_ROOT/home"
mkdir -p "$HOME/.local/bin"
export PATH="$HOME/.local/bin:$PATH"
export HERMES_HOME="$HOME/.hermes"
+export HERMES_DESKTOP_USER_DATA_DIR="$WORK_ROOT/electron-user-data"
mkdir -p "$HERMES_HOME"
INSTALL_DIR="$HERMES_HOME/hermes-agent"
@@ -199,24 +205,32 @@ assert_checkout() {
python3 -B "$REPO_ROOT/tests/install/e2e-assets/source_driver.py" \
--root "$INSTALL_DIR" --launcher "$hermes" --desktop "$EXPECT_DESKTOP" \
|| fail "read-only verification failed at $2; no repair was attempted"
- HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 "$hermes" --version 2>&1 | ts_prefix > "$LOG_DIR/version-$2.log" \
+ HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 source_build_env "$hermes" --version 2>&1 | ts_prefix > "$LOG_DIR/version-$2.log" \
|| fail "hermes --version failed after $2; log in $LOG_DIR/version-$2.log"
ok "hermes --version works: $(head -c 120 "$LOG_DIR/version-$2.log" | tr -d '\n')"
}
+desktop_checkpoint() { # phase, expected commit, selected method
+ source_build_env "$HERMES_E2E_NODE" "$ASSETS/source-desktop-smoke.mjs" \
+ --root "$INSTALL_DIR" --home "$HERMES_HOME" --user-data "$HERMES_DESKTOP_USER_DATA_DIR" \
+ --out "$LOG_DIR" --phase "$1" --expect-commit "$2" \
+ --desktop "$EXPECT_DESKTOP" --method "$3"
+}
+
# --- install OLD ---------------------------------------------------------------
step "installing OLD ($INSTALL_REF) via its own scripts/install.sh ($INSTALL_METHOD)"
EXPECT_DESKTOP=absent
if [ "$INSTALL_METHOD" = "installer-script+desktop" ]; then
EXPECT_DESKTOP=present
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" old desktop
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" old desktop
assert_checkout "$OLD_SHA" OLD
assert_desktop_artifact OLD
else
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" old
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" old
assert_checkout "$OLD_SHA" OLD
fi
+desktop_checkpoint old "$OLD_SHA" "$INSTALL_METHOD"
preserve_before_upgrade
# --- update OLD -> HEAD ----------------------------------------------------------
@@ -232,24 +246,24 @@ case "$UPDATE_METHOD" in
# argparse rejects the whole invocation when it does not exist. Ask the
# installed hermes; older ones read the prompt from stdin, so close it.
HERMES="$(source_hermes "$INSTALL_DIR")" || fail "no installed update command"
- help="$("$HERMES" update --help 2>&1)" || fail "installed update --help failed: $help"
+ help="$(source_build_env "$HERMES" update --help 2>&1)" || fail "installed update --help failed: $help"
if grep -qF -- --yes <<< "$help"; then
update_cmd=("$HERMES" update --yes)
else
update_cmd=("$HERMES" update)
fi
rc=0
- (cd "$INSTALL_DIR" && "${update_cmd[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/update.log") || rc=$?
+ (cd "$INSTALL_DIR" && source_build_env "${update_cmd[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/update.log") || rc=$?
log_group "hermes update transcript" "$LOG_DIR/update.log"
[ "$rc" -eq 0 ] || fail "hermes update exited $rc; transcript above, log at $LOG_DIR/update.log"
;;
installer-script)
# A user re-running the one-liner today gets the CURRENT script.
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL"
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL"
;;
installer-script+desktop)
EXPECT_DESKTOP=present
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL" desktop
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL" desktop
assert_desktop_artifact "$TARGET_LABEL"
;;
hermes-desktop-app-update)
@@ -271,7 +285,7 @@ case "$UPDATE_METHOD" in
# overlay (a fullscreen div that intercepts every click) - and the chat
# surface is real too.
source "$ASSETS/mock-provider.sh"
- mock_start "$WORK_ROOT"
+ PATH="$(dirname "$HERMES_E2E_NODE"):$PATH" mock_start "$WORK_ROOT"
trap mock_stop EXIT
step "capturing the hermes desktop launch spec (build runs for real)"
@@ -279,7 +293,7 @@ case "$UPDATE_METHOD" in
(cd "$INSTALL_DIR" && \
PYTHONPATH="$ASSETS/launch-capture${PYTHONPATH:+:$PYTHONPATH}" \
HERMES_E2E_CAPTURE_LAUNCH="$SPEC" \
- "$HERMES" desktop < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/desktop-launch-capture.log") || rc=$?
+ source_build_env "$HERMES" desktop < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/desktop-launch-capture.log") || rc=$?
log_group "hermes desktop (launch capture) transcript" "$LOG_DIR/desktop-launch-capture.log"
[ "$rc" -eq 0 ] || fail "hermes desktop exited $rc during launch capture; transcript above"
# Exit 0 without a capture means a version that never reached its
@@ -288,18 +302,11 @@ case "$UPDATE_METHOD" in
ok "captured $(cat "$SPEC.captured") launch spec"
step "driving the app under Playwright: Settings -> About -> Update now"
- # Driver tooling comes from the driver: a scratch dir with our own
- # pinned @playwright/test, never resolved from the installed tree
- # (older OLD refs predate the dependency; hoisting moves it around).
- PW_DIR="$WORK_ROOT/playwright"
- mkdir -p "$PW_DIR"
- (cd "$PW_DIR" && npm install --no-save --no-audit --no-fund \
- "@playwright/[email protected]" 2>&1 | ts_prefix > "$LOG_DIR/playwright-install.log") \
- || { log_group "playwright install transcript" "$LOG_DIR/playwright-install.log"; fail "playwright install failed"; }
- cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" "$PW_DIR/"
+ # Use the checkout module closure and current driver Node, not OLD tooling.
rc=0
- (cd "$PW_DIR" && node launch-from-spec.mjs \
+ (cd "$WORK_ROOT" && "$HERMES_E2E_NODE" "$ASSETS/launch-from-spec.mjs" \
--spec "$SPEC" \
+ --old-sha "$OLD_SHA" --chat-out "$LOG_DIR/update-window" --mock-url "$HERMES_E2E_MOCK_URL" \
--result "$HERMES_HOME/.hermes-update-result.json" \
--expect-sha "$TARGET_SHA" \
--repo-dir "$INSTALL_DIR" 2>&1 \
@@ -329,5 +336,6 @@ ok "collected install-side logs to $ildest"
assert_checkout "$TARGET_SHA" "$TARGET_LABEL"
preserve_after_upgrade
+desktop_checkpoint new "$TARGET_SHA" "$UPDATE_METHOD"
step "PASS: $INSTALL_REF -> $TARGET_LABEL via $UPDATE_METHOD"
diff --git a/tests/install/macos-bundle-smoke.sh b/tests/install/macos-bundle-smoke.sh
new file mode 100644
index 00000000000..c7b62076d6d
--- /dev/null
+++ b/tests/install/macos-bundle-smoke.sh
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+# Consumes receipt-verified bytes; never builds, repairs, or relaxes Gatekeeper.
+set -euo pipefail
+fail() { printf '%s\n' "bundle smoke: $*" >&2; exit 1; }
+[[ ${GITHUB_ACTIONS:-} == true && ${RUNNER_ENVIRONMENT:-} == github-hosted && $(uname -s) == Darwin ]] ||
+ fail 'Disposable native GitHub-hosted macOS runner required'
+
+artifact= arch= commit= tag= work= out=
+while (($#)); do
+ (($# >= 2)) || fail "Missing value for $1"
+ case "$1" in
+ --artifact) artifact=$2;; --arch) arch=$2;; --commit) commit=$2;;
+ --tag) tag=$2;; --work) work=$2;; --out) out=$2;;
+ *) fail "Unknown argument: $1";;
+ esac
+ shift 2
+done
+[[ -f $artifact && $artifact == /* && -n $work && -n $out ]] || fail 'Absolute artifact, work and out are required'
+[[ $arch == arm64 || $arch == x64 ]] || fail 'Expected arm64 or x64'
+[[ $commit =~ ^[a-f0-9]{40}$ ]] || fail 'Expected exact lowercase full commit SHA'
+
+# uname can report x86_64 under Rosetta; inspect the physical host as well.
+host=x64
+if [[ $(/usr/sbin/sysctl -in hw.optional.arm64) == 1 ]]; then host=arm64; fi
+[[ $host == "$arch" ]] || fail "Requested $arch on native $host host"
+[[ $(uname -m) == "${arch/x64/x86_64}" ]] || fail 'Adapter must not run under Rosetta'
+
+assets=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/e2e-assets" && pwd -P)
+node=$(command -v node)
+[[ $("$node" -p 'process.arch') == "$arch" ]] || fail 'Driver Node must also use the native architecture'
+metadata=$assets/bundle-smoke-metadata.mjs
+identity_args=(--commit "$commit")
+if [[ -n $tag ]]; then identity_args+=(--tag "$tag"); fi
+"$node" "$metadata" identity "${identity_args[@]}" >/dev/null
+"$node" "$metadata" prepare --work "$work" --out "$out"
+exec > >(tee "$out/native-install.log") 2>&1
+mountpoint=
+cleanup() {
+ status=$?
+ trap - EXIT
+ if [[ -n $mountpoint ]]; then
+ if ! /usr/bin/hdiutil detach "$mountpoint"; then status=1; fi
+ fi
+ printf '{"exitCode":%s}\n' "$status" > "$out/native-install-exit.json"
+ exit "$status"
+}
+trap cleanup EXIT
+trap 'exit 130' INT
+trap 'exit 143' TERM
+
+/usr/bin/shasum -a 256 "$artifact" > "$out/artifact-before.sha256"
+mkdir "$work/install" "$work/home" "$work/user-data"
+shopt -s nullglob
+case "$artifact" in
+ *.dmg)
+ mountpoint=$work/mount
+ mkdir "$mountpoint"
+ /usr/bin/hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$mountpoint" "$artifact"
+ apps=("$mountpoint"/*.app)
+ ((${#apps[@]} == 1)) || fail 'DMG must contain exactly one top-level .app'
+ [[ -d ${apps[0]} && ! -L ${apps[0]} ]] || fail 'Application must be a directory, not a link'
+ /usr/bin/ditto --rsrc --extattr --acl "${apps[0]}" "$work/install/$(basename "${apps[0]}")"
+ /usr/bin/hdiutil detach "$mountpoint"
+ mountpoint=
+ ;;
+ *.zip) /usr/bin/ditto -x -k --rsrc --extattr --acl "$artifact" "$work/install";;
+ *) fail 'Expected a receipt-selected DMG or ZIP';;
+esac
+apps=("$work/install"/*.app)
+((${#apps[@]} == 1)) || fail 'Installed artifact must contain exactly one top-level .app'
+[[ -d ${apps[0]} && ! -L ${apps[0]} ]] || fail 'Installed application must not be a link'
+"$node" "$metadata" verify-mac --app "${apps[0]}" --arch "$arch" "${identity_args[@]}" --out "$out/installed-identity.json"
+exe=$("$node" -e 'console.log(require(process.argv[1]).exe)' "$out/installed-identity.json")
+root=$("$node" -e 'console.log(require(process.argv[1]).root)' "$out/installed-identity.json")
+/usr/bin/shasum -a 256 "$artifact" > "$out/artifact-after.sha256"
+cmp "$out/artifact-before.sha256" "$out/artifact-after.sha256"
+cd "$work"
+"$node" "$assets/desktop-smoke.ts" --exe "$exe" --root "$root" --origin bundled \
+ --home "$work/home" --user-data "$work/user-data" --out "$out" --phase installed --expect-commit "$commit"
\ No newline at end of file
diff --git a/tests/install/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.sh
index 0e660b19d57..3c4bebc01ce 100644
--- a/tests/install/macos-bundled-e2e.sh
+++ b/tests/install/macos-bundled-e2e.sh
@@ -41,7 +41,6 @@ set -euo pipefail
PHASE="all"
MANIFEST_URL=""
ARCH="arm64"
-PLAYWRIGHT_VERSION="1.58.2"
UPDATE_WATCH_TIMEOUT_MS=900000
while [ "$#" -gt 0 ]; do
@@ -69,7 +68,8 @@ case "$ARCH" in arm64|x64) ;; *) echo "error: --arch must be arm64 or x64" >&2;
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
ASSETS="$REPO_ROOT/tests/install/e2e-assets"
export TS_BASE=$SECONDS
-NODE_BIN="$(command -v node)"
+NODE_BIN="${HERMES_E2E_NODE:-$(command -v node)}"
+export HERMES_E2E_NODE="$NODE_BIN"
WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-bundled-e2e}"
LOG_DIR="${HERMES_E2E_LOG_DIR:-$WORK_ROOT/logs}"
@@ -77,6 +77,7 @@ HOME_SANDBOX="$WORK_ROOT/home"
export HOME_SANDBOX
export HERMES_HOME="$HOME_SANDBOX/.hermes"
export HOME="$HOME_SANDBOX" # the app must see the ISOLATED home, not the runner's
+export HERMES_DESKTOP_USER_DATA_DIR="$WORK_ROOT/electron-user-data"
mkdir -p "$WORK_ROOT" "$LOG_DIR" "$HOME_SANDBOX" "$HERMES_HOME"
step() { printf '\n=== %s ===\n' "$*"; }
@@ -222,16 +223,6 @@ phase_install() {
ok "isolated user state seeded at $HERMES_HOME"
}
-ensure_playwright() {
- local pw_dir="$WORK_ROOT/playwright"
- [ -d "$pw_dir/node_modules/@playwright/test" ] && { printf '%s' "$pw_dir"; return 0; }
- mkdir -p "$pw_dir"
- (cd "$pw_dir" && npm install --no-save --no-audit --no-fund \
- "@playwright/test@$PLAYWRIGHT_VERSION" 2>&1 | ts_prefix > "$LOG_DIR/playwright-install.log") \
- || { log_group "playwright install transcript" "$LOG_DIR/playwright-install.log"; fail "playwright install failed"; }
- printf '%s' "$pw_dir"
-}
-
phase_update() {
require_manifest
[ -f "$INSTALL_RECEIPT" ] || fail "no install receipt at $INSTALL_RECEIPT — run the install phase first"
@@ -257,7 +248,7 @@ phase_update() {
# $HERMES_HOME/config.yaml; the feed base URL below is appended after.
# shellcheck source=../e2e-assets/mock-provider.sh
source "$ASSETS/mock-provider.sh"
- mock_start "$WORK_ROOT"
+ PATH="$(dirname "$HERMES_E2E_NODE"):$PATH" mock_start "$WORK_ROOT"
# ── the controlled loopback feed ──────────────────────────────────────
step "building the loopback feed from the REAL NEW signed zip"
@@ -314,15 +305,10 @@ phase_update() {
# ── the real user trigger ─────────────────────────────────────────────
step "launching the OLD app and clicking About -> Update now"
- local pw_dir
- pw_dir="$(ensure_playwright)"
- cp "$ASSETS/mac-bundled-update-driver.mjs" \
- "$ASSETS/process-close.cjs" \
- "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" \
- "$pw_dir/"
local rc=0
- (cd "$pw_dir" && node mac-bundled-update-driver.mjs \
+ (cd "$WORK_ROOT" && "$NODE_BIN" "$ASSETS/mac-bundled-update-driver.mjs" \
--app-bin "$old_app_bin" \
+ --old-sha "$(manifest_side old commit)" --chat-out "$LOG_DIR" --mock-url "$HERMES_E2E_MOCK_URL" \
--shots "$LOG_DIR/shots" \
--close-timeout-ms 420000 2>&1 | ts_prefix | tee "$LOG_DIR/app-update.log") || rc=$?
log_group "in-app update (Playwright) transcript" "$LOG_DIR/app-update.log"
@@ -402,6 +388,28 @@ phase_update() {
|| fail "isolated user-state marker did not survive the update"
ok "isolated user state survived"
+ # Only now may the driver reopen NEW; automatic relaunch already passed.
+ step "post-update-launch chat: gracefully quit verified NEW, then reopen the same binary"
+ # NSRunningApplication sends a normal Quit to this PID without accessibility
+ # permission or a LaunchServices lookup that could itself start another app.
+ osascript -l JavaScript -e 'ObjC.import("AppKit"); function run(args) {
+ const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(args[0]));
+ if (!app || !app.terminate) throw new Error("normal Quit refused");
+ }' "$new_pid" || fail "could not request normal Quit of the automatically relaunched NEW app"
+ for _ in $(seq 1 60); do
+ kill -0 "$new_pid" 2>/dev/null || break
+ sleep 0.5
+ done
+ if kill -0 "$new_pid" 2>/dev/null; then
+ fail "NEW did not quit normally; no force-kill or smoke relaunch attempted"
+ fi
+ printf '{"phase":"new","launch":"post-update-launch","automaticRelaunchProof":"relaunch-proof.json"}\n' > "$LOG_DIR/desktop-chat-new-launch.json"
+ "$NODE_BIN" "$ASSETS/desktop-smoke.ts" --exe "$old_app_bin" \
+ --root "$old_app/Contents/Resources/agent-payload" --origin bundled \
+ --home "$HERMES_HOME" --user-data "$HERMES_DESKTOP_USER_DATA_DIR" \
+ --out "$LOG_DIR" --phase new --expect-commit "$new_commit" --mock-url "$HERMES_E2E_MOCK_URL" \
+ 2>&1 | ts_prefix | tee "$LOG_DIR/desktop-chat-new.log"
+
step "PASS: packaged $(manifest_side old tag) -> $new_tag via the real About -> Update now route"
}
diff --git a/tests/install/macos-desktop-e2e.sh b/tests/install/macos-desktop-e2e.sh
index b105fab6cf6..b26a3c04149 100755
--- a/tests/install/macos-desktop-e2e.sh
+++ b/tests/install/macos-desktop-e2e.sh
@@ -47,7 +47,6 @@ UPDATE_METHOD=""
INSTALL_REF=""
UPDATE_REF=""
DMG_URL="https://hermes-assets.nousresearch.com/Hermes-Setup.dmg"
-PLAYWRIGHT_VERSION="1.58.2"
while [ "$#" -gt 0 ]; do
case "$1" in
--phase)
@@ -77,6 +76,7 @@ esac
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
ASSETS="$REPO_ROOT/tests/install/e2e-assets"
+export HERMES_E2E_NODE="${HERMES_E2E_NODE:-$(command -v node)}"
WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-macos-desktop-e2e}"
LOG_DIR="${HERMES_E2E_LOG_DIR:-$WORK_ROOT/logs}"
@@ -95,6 +95,8 @@ source "$(dirname "$0")/e2e-assets/preserve-plugins.sh"
source "$(dirname "$0")/e2e-assets/source-driver.sh"
# shellcheck source=e2e-assets/installer-common.sh
source "$(dirname "$0")/e2e-assets/installer-common.sh"
+# shellcheck source=e2e-assets/source-build-env.sh
+source "$ASSETS/source-build-env.sh"
log_group() {
printf '::group::%s\n' "$1"
cat "$2"
@@ -109,6 +111,13 @@ arm_redirect() {
export PATH="$HOME/.local/bin:$PATH"
export HERMES_HOME="$HOME/.hermes"
export INSTALL_DIR="$HERMES_HOME/hermes-agent"
+ export HERMES_DESKTOP_USER_DATA_DIR="$WORK_ROOT/electron-user-data"
+}
+
+desktop_checkpoint() { # phase, expected commit, selected method
+ source_build_env "$HERMES_E2E_NODE" "$ASSETS/source-desktop-smoke.mjs" \
+ --root "$INSTALL_DIR" --home "$HERMES_HOME" --user-data "$HERMES_DESKTOP_USER_DATA_DIR" \
+ --out "$LOG_DIR" --phase "$1" --expect-commit "$2" --desktop present --method "$3"
}
phase_stage() {
@@ -194,7 +203,7 @@ phase_install() {
# `open`: launchd inherits NONE of the redirect env) and drive the
# "Install Hermes" button with native input.
local rc=0
- bash "$ASSETS/drive-dmg-install.sh" \
+ source_build_env bash "$ASSETS/drive-dmg-install.sh" \
--app-bin "$app_bin" \
--install-dir "$INSTALL_DIR" \
--proof-dir "$LOG_DIR" 2>&1 \
@@ -212,35 +221,36 @@ phase_install() {
hermes="$(source_hermes "$INSTALL_DIR")" || fail "no installed command after install"
python3 -B "$ASSETS/source_driver.py" --root "$INSTALL_DIR" --launcher "$hermes" --desktop present \
|| fail "read-only verification failed after install"
- HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 "$hermes" --version 2>&1 | ts_prefix > "$LOG_DIR/version-old.log" || fail "hermes --version failed after install"
+ HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 source_build_env "$hermes" --version 2>&1 | ts_prefix > "$LOG_DIR/version-old.log" || fail "hermes --version failed after install"
ok "hermes --version works: $(head -c 120 "$LOG_DIR/version-old.log" | tr -d '\n')"
find_installed_app >/dev/null || fail "no installed Hermes.app after the dmg bootstrap"
ok "installed app: $(find_installed_app)"
+ # The bootstrap can leave its launched app running. Preserve that handoff,
+ # then request normal Quit of only this installed binary before smoke owns it.
+ local installed_bin
+ installed_bin="$(find_installed_app)/Contents/MacOS/Hermes"
+ osascript -l JavaScript -e 'ObjC.import("AppKit"); function run(args) {
+ const apps = $.NSWorkspace.sharedWorkspace.runningApplications;
+ for (let i = 0; i < apps.count; i++) {
+ const app = apps.objectAtIndex(i);
+ if (app.executableURL && ObjC.unwrap(app.executableURL.path) === args[0]) {
+ if (!app.terminate) throw new Error("normal Quit refused");
+ const deadline = Date.now() + 30000;
+ while (!app.terminated && Date.now() < deadline) delay(0.2);
+ if (!app.terminated) throw new Error("installed app did not quit normally");
+ }
+ }
+ }' "$installed_bin" || fail "installed app did not close normally; no smoke launch attempted"
+ desktop_checkpoint old "$OLD_SHA" desktop-installer@latest
}
-ensure_playwright() {
- # Install the driver's OWN pinned @playwright/test into a scratch dir
- # (never the installed tree's copy). Idempotent across phases.
- local pw_dir="$WORK_ROOT/playwright"
- [ -d "$pw_dir/node_modules/@playwright/test" ] && { printf '%s' "$pw_dir"; return 0; }
- mkdir -p "$pw_dir"
- (cd "$pw_dir" && npm install --no-save --no-audit --no-fund \
- "@playwright/test@$PLAYWRIGHT_VERSION" 2>&1 | ts_prefix > "$LOG_DIR/playwright-install.log") \
- || { log_group "playwright install transcript" "$LOG_DIR/playwright-install.log"; fail "playwright install failed"; }
- printf '%s' "$pw_dir"
-}
-
-
-
run_playwright_update() {
# $1: spec file to launch from.
local spec="$1"
- local pw_dir
- pw_dir="$(ensure_playwright)"
- cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" "$pw_dir/"
local rc=0
- (cd "$pw_dir" && node launch-from-spec.mjs \
+ (cd "$WORK_ROOT" && "$HERMES_E2E_NODE" "$ASSETS/launch-from-spec.mjs" \
--spec "$spec" \
+ --old-sha "$OLD_SHA" --chat-out "$LOG_DIR/update-window" --mock-url "$HERMES_E2E_MOCK_URL" \
--result "$HERMES_HOME/.hermes-update-result.json" \
--expect-sha "$TARGET_SHA" \
--repo-dir "$INSTALL_DIR" 2>&1 \
@@ -266,7 +276,7 @@ phase_update() {
# the dev:mock flow does, so the app is genuinely configured.
# shellcheck source=../install/e2e-assets/mock-provider.sh
source "$ASSETS/mock-provider.sh"
- mock_start "$WORK_ROOT"
+ PATH="$(dirname "$HERMES_E2E_NODE"):$PATH" mock_start "$WORK_ROOT"
trap mock_stop EXIT
case "$UPDATE_METHOD" in
hermes-update)
@@ -275,21 +285,21 @@ phase_update() {
local hermes help
hermes="$(source_hermes "$INSTALL_DIR")" || fail "no installed update command"
local update_cmd=("$hermes" update)
- help="$("$hermes" update --help 2>&1)" || fail "installed update --help failed: $help"
+ help="$(source_build_env "$hermes" update --help 2>&1)" || fail "installed update --help failed: $help"
if grep -qF -- --yes <<< "$help"; then
update_cmd=("$hermes" update --yes)
fi
local rc=0
- (cd "$INSTALL_DIR" && "${update_cmd[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/update.log") || rc=$?
+ (cd "$INSTALL_DIR" && source_build_env "${update_cmd[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/update.log") || rc=$?
log_group "hermes update transcript" "$LOG_DIR/update.log"
[ "$rc" -eq 0 ] || fail "hermes update exited $rc; transcript above"
;;
installer-script)
# A dmg user re-running today's install one-liner.
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head
;;
installer-script+desktop)
- run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head desktop
+ source_build_env run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head desktop
# The desktop stage is this leg's claim: the rebuilt app must exist.
head_app=""
for cand in \
@@ -329,7 +339,7 @@ PYEOF
(cd "$INSTALL_DIR" && \
PYTHONPATH="$ASSETS/launch-capture${PYTHONPATH:+:$PYTHONPATH}" \
HERMES_E2E_CAPTURE_LAUNCH="$spec" \
- "$hermes" desktop < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/desktop-launch-capture.log") || rc=$?
+ source_build_env "$hermes" desktop < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/desktop-launch-capture.log") || rc=$?
log_group "hermes desktop (launch capture) transcript" "$LOG_DIR/desktop-launch-capture.log"
[ "$rc" -eq 0 ] || fail "hermes desktop exited $rc during launch capture"
[ -f "$spec.captured" ] || fail "hermes desktop exited 0 but no launch was captured"
@@ -364,10 +374,11 @@ PYEOF
command="$(source_hermes "$INSTALL_DIR")" || fail "no installed command after update"
python3 -B "$ASSETS/source_driver.py" --root "$INSTALL_DIR" --launcher "$command" --desktop present \
|| fail "read-only verification failed after update; no repair was attempted"
- HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 "$command" --version 2>&1 | ts_prefix > "$LOG_DIR/version-head.log" \
+ HERMES_DISABLE_LAZY_INSTALLS=1 PYTHONDONTWRITEBYTECODE=1 source_build_env "$command" --version 2>&1 | ts_prefix > "$LOG_DIR/version-head.log" \
|| fail "hermes --version failed after update"
ok "hermes --version works post-update"
preserve_after_upgrade
+ desktop_checkpoint new "$TARGET_SHA" "$UPDATE_METHOD"
step "PASS: $OLD_REF -> $TARGET_LABEL via $UPDATE_METHOD"
}
diff --git a/tests/install/windows-bundle-smoke.ps1 b/tests/install/windows-bundle-smoke.ps1
new file mode 100644
index 00000000000..f105240bc1f
--- /dev/null
+++ b/tests/install/windows-bundle-smoke.ps1
@@ -0,0 +1,115 @@
+# Real deployment of receipt-verified bytes. Never run on a developer desktop.
+param(
+ [Parameter(Mandatory=$true)][string]$Artifact,
+ [Parameter(Mandatory=$true)][ValidateSet('x64','arm64')][string]$Arch,
+ [Parameter(Mandatory=$true)][string]$Commit,
+ [string]$Tag = '',
+ [Parameter(Mandatory=$true)][string]$Work,
+ [Parameter(Mandatory=$true)][string]$Out
+)
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+if ($env:GITHUB_ACTIONS -cne 'true' -or $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or $env:OS -cne 'Windows_NT') {
+ throw 'Disposable native GitHub-hosted Windows runner required'
+}
+if ($Commit -cnotmatch '^[a-f0-9]{40}$') { throw 'Expected exact lowercase full commit SHA' }
+if (-not [IO.Path]::IsPathRooted($Artifact) -or -not (Test-Path -LiteralPath $Artifact -PathType Leaf)) { throw 'Absolute artifact path required' }
+$Artifact = (Resolve-Path -LiteralPath $Artifact).Path
+$processors = @(Get-CimInstance Win32_Processor)
+$nativeCode = @{ x64=9; arm64=12 }[$Arch]
+if (-not $processors.Count -or @($processors | Where-Object { $_.Architecture -ne $nativeCode }).Count) {
+ throw "Host is not native $Arch; emulated x64 on ARM is not coverage"
+}
+$Assets = Join-Path $PSScriptRoot 'e2e-assets'
+$Node = (Get-Command node.exe -ErrorAction Stop).Source
+$Metadata = Join-Path $Assets 'bundle-smoke-metadata.mjs'
+function Run-Node([string[]]$Argv) {
+ & $Node @Argv
+ if ($LASTEXITCODE -ne 0) { throw "Node exited $LASTEXITCODE ($($Argv[0]))" }
+}
+$nodeArch = Run-Node @('-p', 'process.arch')
+if ($nodeArch -cne $Arch) { throw 'Driver Node must also use the native architecture' }
+$identityArgs = @('--commit', $Commit)
+if ($Tag) { $identityArgs += @('--tag', $Tag) }
+$Expected = (Run-Node (@($Metadata, 'identity') + $identityArgs)) | ConvertFrom-Json
+Run-Node @($Metadata, 'prepare', '--work', $Work, '--out', $Out)
+. (Join-Path $Assets 'windows-bundle-metadata.ps1')
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+$HomeDir = Join-Path $Work 'home'
+$UserData = Join-Path $Work 'user-data'
+New-Item -ItemType Directory -Path $HomeDir, $UserData | Out-Null
+Start-Transcript -Path (Join-Path $Out 'native-install.log') | Out-Null
+$attempted = $false
+$installedFullName = $null
+$failed = $false
+try {
+ $beforeHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $Artifact).Hash.ToLowerInvariant()
+ @{ path=$Artifact; sha256=$beforeHash } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Out 'artifact.json')
+ $signature = Get-AuthenticodeSignature -LiteralPath $Artifact
+ if ($signature.Status -ne 'Valid' -or -not $signature.SignerCertificate -or
+ $signature.SignerCertificate.Subject -cne $Expected.publisher) { throw 'Artifact signature/publisher invalid' }
+ $inputMetadata = Read-BundleSmokeMetadata $Artifact $Arch $Expected
+ $inputMetadata | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Out 'artifact-metadata.json')
+ if (@(Get-AppxPackage -AllUsers -Name $Expected.msixIdentity).Count) { throw 'Package identity already exists; refusing to replace it' }
+ $attempted = $true
+ Add-AppxPackage -Path $Artifact -ErrorAction Stop
+ $packages = @(Get-AppxPackage -Name $Expected.msixIdentity)
+ if ($packages.Count -ne 1) { throw 'Expected exactly one deployed package' }
+ $pkg = $packages[0]
+ $installedFullName = $pkg.PackageFullName
+ if ($pkg.Publisher -cne $Expected.publisher -or $pkg.Architecture.ToString() -ine $Arch -or
+ $pkg.Version.ToString() -cne $inputMetadata.Version -or $pkg.Status.ToString() -cne 'Ok') {
+ throw 'Deployed package identity/version/native architecture/status mismatch'
+ }
+ $manifest = Get-AppxPackageManifest -Package $pkg.PackageFullName
+ $installed = Read-SmokePackageManifest $manifest $Arch $Expected
+ if ($installed.Version -cne $inputMetadata.Version) { throw 'Installed manifest version mismatch' }
+ if ($inputMetadata.Executable -and $installed.Executable -cne $inputMetadata.Executable) { throw 'Installed executable differs from input manifest' }
+ $exe = [IO.Path]::GetFullPath((Join-Path $pkg.InstallLocation $installed.Executable))
+ if (-not $exe.StartsWith($pkg.InstallLocation.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -or
+ -not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw 'Installed manifest executable is absent or outside package' }
+ $resources = Join-Path (Split-Path -Parent $exe) 'resources'
+ $root = Join-Path $resources 'agent-payload'
+ if (-not (Test-Path -LiteralPath $root -PathType Container)) { throw 'Installed agent-payload missing' }
+ $stampPath = Join-Path $resources 'install-stamp.json'
+ $stamp = Get-Content -Raw -LiteralPath $stampPath | ConvertFrom-Json
+ $displayVersion = (Run-Node (@($Metadata, 'stamp', '--platform', 'win32', '--stamp', $stampPath) + $identityArgs)) | ConvertFrom-Json
+ $semverBase = ($displayVersion -split '-')[0]
+ if (-not $pkg.Version.ToString().StartsWith($semverBase + '.', [StringComparison]::Ordinal)) { throw 'Package version disagrees with stamped semver' }
+ if (-not $Tag -and $pkg.Version.ToString() -cne ($displayVersion + '.0')) { throw 'Commit package must use stamped semver with zero revision' }
+ @{ packageFullName=$pkg.PackageFullName; publisher=$pkg.Publisher; architecture=$pkg.Architecture.ToString();
+ version=$pkg.Version.ToString(); exe=$exe; root=$root; stamp=$stamp } |
+ ConvertTo-Json -Depth 12 | Set-Content -LiteralPath (Join-Path $Out 'installed-identity.json')
+ if ((Get-FileHash -Algorithm SHA256 -LiteralPath $Artifact).Hash.ToLowerInvariant() -cne $beforeHash) { throw 'Input artifact changed during installation' }
+ Push-Location $Work
+ try {
+ Run-Node @((Join-Path $Assets 'desktop-smoke.ts'), '--exe', $exe, '--root', $root, '--origin', 'bundled',
+ '--home', $HomeDir, '--user-data', $UserData, '--out', $Out, '--phase', 'installed', '--expect-commit', $Commit)
+ } finally { Pop-Location }
+} catch {
+ $failed = $true
+ $_ | Out-String | Set-Content -LiteralPath (Join-Path $Out 'native-install-error.txt')
+ Write-Error $_ -ErrorAction Continue
+} finally {
+ try {
+ # A failed deployment can still have registered the package. Admission
+ # ruled out prior identities, so only this invocation's exact package is eligible.
+ if ($attempted) {
+ $remaining = @(Get-AppxPackage -Name $Expected.msixIdentity)
+ foreach ($pkg in $remaining) {
+ if ($pkg.Publisher -cne $Expected.publisher -or $pkg.Version.ToString() -cne $inputMetadata.Version -or
+ ($installedFullName -and $pkg.PackageFullName -cne $installedFullName)) { throw 'Refusing cleanup of an unowned package' }
+ Remove-AppxPackage -Package $pkg.PackageFullName -ErrorAction Stop
+ if (Get-AppxPackage -Name $Expected.msixIdentity) { throw 'Package removal did not complete' }
+ }
+ }
+ } catch {
+ $failed = $true
+ $_ | Out-String | Set-Content -LiteralPath (Join-Path $Out 'native-cleanup-error.txt')
+ Write-Error $_ -ErrorAction Continue
+ } finally {
+ @{ exitCode=[int]$failed } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Out 'native-install-exit.json')
+ Stop-Transcript | Out-Null
+ }
+}
+if ($failed) { exit 1 }
\ No newline at end of file
diff --git a/tests/install/windows-bundled-e2e.ps1 b/tests/install/windows-bundled-e2e.ps1
index 718bda39d9c..1395e2a7b37 100644
--- a/tests/install/windows-bundled-e2e.ps1
+++ b/tests/install/windows-bundled-e2e.ps1
@@ -14,9 +14,12 @@ $Proof = Join-Path $Work 'proof'
New-Item -ItemType Directory -Path $Proof -Force | Out-Null
$env:HERMES_HOME = Join-Path $Work 'home'
New-Item -ItemType Directory -Path $env:HERMES_HOME | Out-Null
-$env:HERMES_DESKTOP_USER_DATA = Join-Path $Work 'electron-user-data'
+$env:HERMES_DESKTOP_USER_DATA_DIR = Join-Path $Work 'electron-user-data'
+$env:HOME = Join-Path $Work 'os-home'
+New-Item -ItemType Directory -Path $env:HOME | Out-Null
+. (Join-Path $Assets 'desktop-smoke-windows.ps1')
$env:HERMES_DESKTOP_FEED_BASE_URL = ''
-$Node = (Get-Command node.exe).Source
+$Node = if ($env:HERMES_E2E_NODE) { $env:HERMES_E2E_NODE } else { (Get-Command node.exe).Source }
function Run-Node([string[]]$Argv) {
& $Node @Argv
if ($LASTEXITCODE -ne 0) { throw "Node failed: $($Argv[0])" }
@@ -61,7 +64,7 @@ function Installed($Side) {
return @{ package=$pkg; exe=$exe; stamp=$stamp }
}
function Main-Processes([string]$Exe) {
- return @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $Exe })
+ return @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $Exe -and $_.CommandLine -notmatch '(?:^|\s)--type(?:=|\s)' })
}
$Feed = Join-Path $Work 'feed'
New-Item -ItemType Directory -Path $Feed | Out-Null
@@ -71,6 +74,8 @@ $PortFile = Join-Path $Work 'feed-url'
$Helper = Join-Path $Assets 'windows-bundled-helpers.mjs'
$server = Start-Process -FilePath $Node -ArgumentList @('"'+$Helper+'"', 'serve', '--feed', '"'+$Feed+'"', '--port-file', '"'+$PortFile+'"') -PassThru -RedirectStandardOutput (Join-Path $Proof 'feed.log') -RedirectStandardError (Join-Path $Proof 'feed-error.log')
$installed = $false
+$mock = $null
+$oldDriver = $null
try {
$deadline = (Get-Date).AddSeconds(20)
while (-not (Test-Path $PortFile)) {
@@ -97,15 +102,26 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Plugin seed failed' }
& $python $verifier snapshot --home $env:HERMES_HOME --out (Join-Path $Work 'plugins-before.json')
if ($LASTEXITCODE -ne 0) { throw 'Plugin snapshot failed' }
- # This is the only app launch performed by the driver: OLD, from its registered package.
- Start-Process -FilePath $old.exe -ArgumentList '--force-renderer-accessibility' | Out-Null
- $deadline = (Get-Date).AddMinutes(3)
- do {
- $oldRows = Main-Processes $old.exe
- if ($oldRows.Count) { break }
- Start-Sleep -Seconds 1
- } while ((Get-Date) -lt $deadline)
- if ($oldRows.Count -ne 1) { throw 'Could not identify the old installed app process' }
+ $mock = Start-DesktopJourneyMock $Node $Assets $Work $env:HERMES_HOME $Proof
+ # Keep Playwright's actual OLD window alive across chat and the native UIA
+ # trigger. The NEW descriptor is not published until OLD chat has passed.
+ $oldChatReady = Join-Path $Proof 'old-chat-ready.json'
+ $oldDriver = Start-Process -FilePath $Node -ArgumentList @(
+ ('"' + (Join-Path $Assets 'drive-update.cjs') + '"'), ('"' + $old.exe + '"'),
+ ('"' + $Proof + '"'), $m.old.commit, '--native-handoff'
+ ) -PassThru -RedirectStandardOutput (Join-Path $Proof 'old-chat-driver.log') -RedirectStandardError (Join-Path $Proof 'old-chat-driver-error.log')
+ $deadline = (Get-Date).AddMinutes(6)
+ while (-not (Test-Path -LiteralPath $oldChatReady)) {
+ if ($oldDriver.HasExited -or (Get-Date) -ge $deadline) { throw 'Mandatory OLD desktop chat failed before the update trigger' }
+ Start-Sleep -Milliseconds 200
+ }
+ $ready = Get-Content -LiteralPath $oldChatReady -Raw | ConvertFrom-Json
+ $oldRows = Main-Processes $old.exe
+ if ($oldRows.Count -ne 1 -or $oldRows[0].ProcessId -ne $ready.pid -or $ready.exe -cne $old.exe -or $ready.oldSha -cne $m.old.commit) {
+ throw 'OLD chat did not run in the identified installed app process'
+ }
+ $oldChat = Get-Content -LiteralPath (Join-Path $Proof 'desktop-chat-old.json') -Raw | ConvertFrom-Json
+ if ($oldChat.status -ne 'passed') { throw 'Mandatory OLD chat receipt failed' }
$oldProcess = $oldRows[0]
$oldProcess | Select-Object ProcessId, CreationDate, ExecutablePath | ConvertTo-Json | Set-Content (Join-Path $Proof 'old-process.json')
Descriptor $m.new 'new.msixbundle'
@@ -113,6 +129,7 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Real in-app update trigger failed' }
$click = Get-Content -Raw (Join-Path $Proof 'click.json') | ConvertFrom-Json
if (-not $click.ok -or -not $click.exited) { throw 'In-app trigger receipt is not successful' }
+ if (-not $oldDriver.WaitForExit(30000) -or $oldDriver.ExitCode -ne 0) { throw 'OLD Playwright ownership did not release after native process close' }
$deadline = (Get-Date).AddMinutes(15)
$new = $null; $newRows = @()
do {
@@ -149,8 +166,19 @@ try {
& $python $verifier verify --home $env:HERMES_HOME --snapshot (Join-Path $Work 'plugins-before.json') --report (Join-Path $Proof 'plugin-preservation.json')
if ($LASTEXITCODE -ne 0) { throw 'Plugin preservation failed' }
if ((Get-Content -Raw $marker).Trim() -cne $witness) { throw 'User-state witness changed' }
+ # Record automatic relaunch before ANY driver-owned NEW launch.
+ @{ oldPid=$oldProcess.ProcessId; oldBirth=$oldProcess.CreationDate; newPid=$newProcess.ProcessId; newBirth=$newProcess.CreationDate; newPath=$newProcess.ExecutablePath; automaticRelaunch=$true } |
+ ConvertTo-Json -Depth 8 | Set-Content (Join-Path $Proof 'relaunch-proof.json')
+ Close-VerifiedDesktop $new.exe $newProcess.ProcessId
+ @{ phase='new'; launch='post-update-launch'; automaticRelaunchProof='relaunch-proof.json' } |
+ ConvertTo-Json | Set-Content (Join-Path $Proof 'desktop-chat-new-launch.json')
+ Run-Node @((Join-Path $Assets 'desktop-smoke.ts'), '--exe', $new.exe, '--root', $payloadRoot, '--origin', 'bundled',
+ '--home', $env:HERMES_HOME, '--user-data', $env:HERMES_DESKTOP_USER_DATA_DIR, '--out', $Proof,
+ '--phase', 'new', '--expect-commit', $m.new.commit, '--mock-url', $env:HERMES_E2E_MOCK_URL)
@{ ok=$true; oldVersion=$m.old.version; newVersion=$m.new.version; oldPid=$oldProcess.ProcessId; oldBirth=$oldProcess.CreationDate; newPid=$newProcess.ProcessId; newBirth=$newProcess.CreationDate; newPath=$newProcess.ExecutablePath; stamp=$new.stamp; automaticRelaunch=$true } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $Proof 'acceptance.json')
} finally {
+ if ($mock -and -not $mock.HasExited) { Stop-Process -Id $mock.Id -ErrorAction SilentlyContinue }
+ if ($oldDriver -and -not $oldDriver.HasExited) { Stop-Process -Id $oldDriver.Id -ErrorAction SilentlyContinue }
if (-not $server.HasExited) { Stop-Process -Id $server.Id -ErrorAction SilentlyContinue }
# Disposable runner teardown only, scoped to the package installed by this leg.
if ($installed) {
diff --git a/tests/install/windows-e2e.ps1 b/tests/install/windows-e2e.ps1
index 26795a004d3..b745fa89e38 100644
--- a/tests/install/windows-e2e.ps1
+++ b/tests/install/windows-e2e.ps1
@@ -110,11 +110,8 @@ param(
[string]$SetupExeUrl = "https://hermes-assets.nousresearch.com/Hermes-Setup.exe",
- # Pinned @playwright/test for the update-gui driver. Installed fresh
- # into a scratch dir every run -- never resolved from the installed
- # tree -- so the driver behaves identically for every OLD ref. Bump
- # deliberately; keep roughly in step with the repo's own lockfile.
- [string]$PlaywrightVersion = "1.58.2"
+ # Driver dependencies come from the current checkout lockfile.
+ [string]$DriverNode = $env:HERMES_E2E_NODE
)
$ErrorActionPreference = "Stop"
@@ -136,6 +133,40 @@ $StatePath = Join-Path $WorkRoot "shas.json"
$ProofRoot = Join-Path $WorkRoot "proof"
$AhkDir = Join-Path $WorkRoot "ahk"
$AssetsDir = Join-Path $PSScriptRoot "e2e-assets"
+if (-not $DriverNode) { $DriverNode = (Get-Command node.exe -ErrorAction Stop).Source }
+$env:HERMES_E2E_NODE = $DriverNode
+$env:HERMES_DESKTOP_USER_DATA_DIR = Join-Path $WorkRoot 'electron-user-data'
+$script:ChatMock = $null
+$script:ChatFailure = $false
+. (Join-Path $AssetsDir 'desktop-smoke-windows.ps1')
+
+function Start-JourneyChat {
+ if (-not $script:ChatMock) {
+ $script:ChatFailure = $true
+ $script:ChatMock = Start-DesktopJourneyMock $DriverNode $AssetsDir $WorkRoot $HermesHome $ProofRoot
+ $script:ChatFailure = $false
+ }
+}
+
+function Invoke-DesktopCheckpoint([string]$ChatPhase, [string]$Commit, [string]$Method) {
+ $script:ChatFailure = $true
+ $prevEap = $ErrorActionPreference
+ try {
+ $ErrorActionPreference = 'Continue'
+ & $DriverNode (Join-Path $AssetsDir 'source-desktop-smoke.mjs') `
+ --root $InstallDir --home $HermesHome --user-data $env:HERMES_DESKTOP_USER_DATA_DIR `
+ --out $ProofRoot --phase $ChatPhase --expect-commit $Commit --desktop $script:ExpectedDesktop --method $Method
+ $chatExit = $LASTEXITCODE
+ } finally { $ErrorActionPreference = $prevEap }
+ if ($chatExit -ne 0) { throw "Mandatory desktop chat $ChatPhase failed (exit $chatExit)" }
+ $script:ChatFailure = $false
+}
+
+function Confirm-OldChat([string]$Out) {
+ $receipt = Get-Content -LiteralPath (Join-Path $Out 'desktop-chat-old.json') -Raw | ConvertFrom-Json
+ if ($receipt.status -ne 'passed') { throw 'Mandatory OLD update-window chat failed' }
+ $script:ChatFailure = $false
+}
$RepoUrlHttps = "https://github.com/NousResearch/hermes-agent.git"
$RepoUrlSsh = "[email protected]:NousResearch/hermes-agent.git"
@@ -349,6 +380,7 @@ function Test-HermesRuns([string]$Label) {
# shellcheck source=../e2e-assets/ts-prefix.ps1
. (Join-Path $PSScriptRoot "e2e-assets\ts-prefix.ps1")
. (Join-Path $PSScriptRoot "e2e-assets\source-driver.ps1")
+. (Join-Path $AssetsDir 'source-build-env.ps1')
function Write-LogGroup([string]$Title, [string]$LogPath) {
Write-Host "::group::$Title"
@@ -443,29 +475,15 @@ function Invoke-HermesDesktopAppUpdate([string]$TargetSha) {
Assert-True ($capExit -eq 0) "hermes desktop exited 0 during launch capture"
Assert-True (Test-Path -LiteralPath "$spec.captured") "a launch was actually captured (exit 0 without a launch must not pass)"
- $node = Get-ManagedNode
- $driverDir = Join-Path $WorkRoot "pw-driver"
- New-Item -ItemType Directory -Path $driverDir -Force | Out-Null
- $npmCli = Join-Path (Split-Path -Parent $node) "node_modules\npm\bin\npm-cli.js"
- Assert-True (Test-Path -LiteralPath $npmCli) "managed npm exists beside the managed node"
- Push-Location $driverDir
- try {
- & $node $npmCli install --no-save --no-audit --no-fund "@playwright/test@$PlaywrightVersion" 2>&1 |
- Select-Object -Last 5 | ForEach-Object { Write-Host " npm| $_" }
- $npmExit = $LASTEXITCODE
- } finally {
- Pop-Location
- }
- Assert-True ($npmExit -eq 0) "npm install @playwright/test@$PlaywrightVersion into the driver dir"
-
- Copy-Item (Join-Path $AssetsDir "launch-from-spec.mjs") (Join-Path $driverDir "launch-from-spec.mjs") -Force
- Copy-Item (Join-Path $AssetsDir "source-update-observer.mjs") (Join-Path $driverDir "source-update-observer.mjs") -Force
- Copy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force
- Copy-Item (Join-Path $AssetsDir "update-ui.cjs") (Join-Path $driverDir "update-ui.cjs") -Force
+ $node = $DriverNode
+ $chatOut = Join-Path $ProofRoot 'update-window'
+ Remove-Item -LiteralPath (Join-Path $chatOut 'desktop-chat-old.json') -Force -ErrorAction SilentlyContinue
+ $script:ChatFailure = $true
$prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"
- Push-Location $driverDir
+ Push-Location $WorkRoot
try {
- & $node "launch-from-spec.mjs" --spec $spec `
+ & $node (Join-Path $AssetsDir "launch-from-spec.mjs") --spec $spec `
+ --old-sha (Read-State).old --chat-out $chatOut --mock-url $env:HERMES_E2E_MOCK_URL `
--result (Join-Path $HermesHome ".hermes-update-result.json") `
--expect-sha $TargetSha --repo-dir $InstallDir 2>&1 |
ForEach-Object { Write-Host " pw| $_" }
@@ -474,6 +492,7 @@ function Invoke-HermesDesktopAppUpdate([string]$TargetSha) {
Pop-Location
$ErrorActionPreference = $prevEap
}
+ Confirm-OldChat $chatOut
Assert-True ($driveExit -eq 0) "app driven via captured hermes desktop spec; update completed"
}
@@ -542,22 +561,6 @@ function Stop-HermesAppProcesses([string]$Label) {
}
}
-function Get-ManagedNode {
- # `hermes update`/desktop builds use the Hermes-managed Node; use the same
- # one to run the Playwright driver so no system Node is required.
- $candidates = @(
- (Join-Path $HermesHome "node\node.exe"),
- (Join-Path $HermesHome "bin\node\node.exe"),
- (Join-Path $InstallDir "node\node.exe")
- )
- foreach ($c in $candidates) {
- if (Test-Path -LiteralPath $c) { return $c }
- }
- $fromPath = Get-Command node -ErrorAction SilentlyContinue
- if ($fromPath) { return $fromPath.Source }
- throw "No node.exe found (managed or on PATH)"
-}
-
# ----------------------------------------------------------------------------
# Phase: stage -- serve.git with `main` at OLD (advanced to HEAD by update-gui)
# ----------------------------------------------------------------------------
@@ -713,9 +716,6 @@ function Invoke-PhaseInstallGui {
}
}
- # Close the freshly launched app (user quits after first look).
- Stop-HermesAppProcesses "post-install"
-
# The installer cloned/updated from serve.git's `main`; the phase's
# expected sha says where that must land (install: OLD; update: HEAD).
$installedSha = Get-InstalledHead
@@ -727,13 +727,13 @@ function Invoke-PhaseInstallGui {
Test-HermesRuns "post-$Mode-gui"
Assert-True ($null -ne (Get-DesktopExe)) "packaged Desktop Hermes.exe exists"
- # Seed a provider so the update leg meets the ready app shell, not the
- # onboarding overlay (an updating user has a configured provider).
- $envFile = Join-Path $HermesHome ".env"
- if (-not (Test-Path -LiteralPath $envFile) -or -not ((Get-Content $envFile -Raw -ErrorAction SilentlyContinue) -match "OPENROUTER_API_KEY")) {
- Add-Content -LiteralPath $envFile -Value "OPENROUTER_API_KEY=sk-or-...-key"
- }
- Write-Host " seeded placeholder provider key for the update leg"
+ # The installer Launch proof above must pass before a test-owned launch.
+ $script:ChatFailure = $true
+ Close-VerifiedDesktop (Get-DesktopExe)
+ $chatPhase = if ($Mode -eq 'install') { 'old' } else { 'new' }
+ @{ phase=$chatPhase; launch='post-installer-launch'; handoffProof=$proof } | ConvertTo-Json |
+ Set-Content (Join-Path $ProofRoot "desktop-chat-$chatPhase-launch.json")
+ Invoke-DesktopCheckpoint $chatPhase $ExpectedSha 'desktop-installer@latest'
}
# ----------------------------------------------------------------------------
@@ -758,52 +758,27 @@ function Invoke-GuiUpdateDesktopRoute([string]$TargetSha) {
$markerPath = Join-Path $HermesHome ".hermes-update-in-progress"
Remove-Item -LiteralPath $resultPath -Force -ErrorAction SilentlyContinue
- $node = Get-ManagedNode
- # The Playwright driver gets its OWN pinned @playwright/test in a
- # scratch dir -- NEVER the installed tree's copy. The driver talks to
- # the app over Playwright's inspection pipe, so its Playwright version
- # is independent of the app under test; installing it ourselves makes
- # the leg identical for every OLD ref (older releases predate the
- # dependency entirely, and hoisting moves it around in newer ones).
- $driverDir = Join-Path $WorkRoot "pw-driver"
- New-Item -ItemType Directory -Path $driverDir -Force | Out-Null
- $npmCli = Join-Path (Split-Path -Parent $node) "node_modules\npm\bin\npm-cli.js"
- Assert-True (Test-Path -LiteralPath $npmCli) "managed npm exists beside the managed node"
- Push-Location $driverDir
- try {
- & $node $npmCli install --no-save --no-audit --no-fund "@playwright/test@$PlaywrightVersion" 2>&1 |
- Select-Object -Last 5 | ForEach-Object { Write-Host " npm| $_" }
- $npmExit = $LASTEXITCODE
- } finally {
- Pop-Location
- }
- Assert-True ($npmExit -eq 0) "npm install @playwright/test@$PlaywrightVersion into the driver dir"
+ $node = $DriverNode
$recorder = Start-DesktopRecorder (Join-Path $proof "desktop-frames")
try {
# Launch the installed app and click through Settings -> About ->
# Update now. Exit 0 = the app quit for the updater hand-off.
- # Copy the driver INTO $driverDir first: Node resolves
- # require('@playwright/test') from the SCRIPT's own directory upward,
- # so running it from the CI checkout would resolve the wrong (or no)
- # node_modules.
- $driver = Join-Path $driverDir "e2e-drive-update.cjs"
- Copy-Item (Join-Path $AssetsDir "drive-update.cjs") $driver -Force
- Copy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force
- Copy-Item (Join-Path $AssetsDir "update-ui.cjs") (Join-Path $driverDir "update-ui.cjs") -Force
- Copy-Item (Join-Path $AssetsDir "process-close.cjs") (Join-Path $driverDir "process-close.cjs") -Force
- Push-Location $driverDir
+ $driver = Join-Path $AssetsDir 'drive-update.cjs'
+ Remove-Item -LiteralPath (Join-Path $proof 'desktop-chat-old.json') -Force -ErrorAction SilentlyContinue
+ $script:ChatFailure = $true
+ Push-Location $WorkRoot
$prevEap = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try {
- & $node $driver $desktopExe $proof 2>&1 |
+ & $node $driver $desktopExe $proof (Read-State).old 2>&1 |
ForEach-Object { Write-Host " $_" }
$driveExit = $LASTEXITCODE
} finally {
Pop-Location
$ErrorActionPreference = $prevEap
- Remove-Item -LiteralPath $driver -Force -ErrorAction SilentlyContinue
}
+ Confirm-OldChat $proof
Assert-True ($driveExit -eq 0) "GUI driver clicked Update now and the app quit for hand-off"
# The detached updater (spawned by the app, NOT by us) now runs
@@ -893,6 +868,12 @@ function Invoke-GuiUpdateDesktopRoute([string]$TargetSha) {
}
} catch {}
Save-DesktopScreenshot (Join-Path $proof "99-relaunched-desktop.png")
+ # Native relaunch and read-only product verification already passed.
+ $script:ChatFailure = $true
+ Close-VerifiedDesktop (Get-DesktopExe)
+ @{ phase='new'; launch='post-update-launch'; automaticRelaunch=$true } | ConvertTo-Json |
+ Set-Content (Join-Path $ProofRoot 'desktop-chat-new-launch.json')
+ Invoke-DesktopCheckpoint 'new' $TargetSha $Route
}
finally {
Stop-DesktopRecorder $recorder (Join-Path $proof "desktop-frames")
@@ -971,6 +952,9 @@ function Invoke-PhaseInstall {
Assert-DesktopArtifact "OLD"
}
}
+ if ($InstallMethod -ne 'desktop-installer@latest') {
+ Invoke-DesktopCheckpoint 'old' $state.old $InstallMethod
+ }
}
function Invoke-PhaseUpdate {
@@ -992,6 +976,7 @@ function Invoke-PhaseUpdate {
Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $state.current) | Out-Null
Write-Host " serve.git main advanced to $($state.current)"
+ if ($Route -in @('open-app-update', 'hermes-desktop-app-update')) { Start-JourneyChat }
switch ($Route) {
"open-app-update" {
# Meaningful only where an OS entry point exists - install.ps1
@@ -1035,6 +1020,9 @@ function Invoke-PhaseUpdate {
Assert-True ((Get-InstalledHead) -eq $state.current) "checkout landed on HEAD"
Test-HermesRuns "post-update"
Invoke-PreserveVerify
+ if ($Route -notin @('open-app-update', 'desktop-installer@latest')) {
+ Invoke-DesktopCheckpoint 'new' $state.current $Route
+ }
}
function Invoke-CheckedPhaseUpdate {
@@ -1047,7 +1035,8 @@ function Invoke-CheckedPhaseUpdate {
Invoke-PhaseUpdate
} catch {
$failure = $_
- $node = Get-ManagedNode
+ if ($script:ChatFailure) { throw $failure }
+ $node = $DriverNode
$classification = & $node (Join-Path $AssetsDir "known-failures.cjs") $WorkRoot $InstallMethod $Route $failure.Exception.Message
$classificationExit = $LASTEXITCODE
if ($classificationExit -ne 0) { throw $failure }
@@ -1077,16 +1066,22 @@ $script:RealGitExe = (Get-Command git.exe -ErrorAction Stop).Source
Set-GitRedirect
+try {
switch ($Phase) {
"stage" { Invoke-PhaseStage }
- "install" { Invoke-PhaseInstall }
- "update" { Invoke-CheckedPhaseUpdate }
+ "install" { Invoke-SourceBuild { Invoke-PhaseInstall } }
+ "update" { Invoke-SourceBuild { Invoke-CheckedPhaseUpdate } }
"all" {
Invoke-PhaseStage
- Invoke-PhaseInstall
- Invoke-CheckedPhaseUpdate
+ Invoke-SourceBuild { Invoke-PhaseInstall }
+ Invoke-SourceBuild { Invoke-CheckedPhaseUpdate }
}
}
+} finally {
+ if ($script:ChatMock -and -not $script:ChatMock.HasExited) {
+ Stop-Process -Id $script:ChatMock.Id -ErrorAction SilentlyContinue
+ }
+}
Write-Host ""
Write-Host "Phase '$Phase' completed successfully."
diff --git a/tests/scripts/test_release_artifacts.py b/tests/scripts/test_release_artifacts.py
index df933d0b3e1..237df7f8b00 100644
--- a/tests/scripts/test_release_artifacts.py
+++ b/tests/scripts/test_release_artifacts.py
@@ -2,9 +2,16 @@
import hashlib
import copy
import json
+import os
+import shlex
+import shutil
+import subprocess
+import sys
import zipfile
import xml.etree.ElementTree as ET
+from pathlib import Path
+import hermes_yaml
import pytest
from scripts.bundles.release_artifacts import materialize, record, stamp_matches
@@ -13,6 +20,10 @@ from tests.scripts.test_stable_release import https_origin # noqa: F401
from tests.scripts.test_release_darwin import _inputs
from scripts.bundles import release_artifacts as artifacts
+ROOT = Path(__file__).resolve().parents[2]
+SMOKE_RESULTS = {name: {'result': 'success'} for name in (
+ 'smoke-darwin', 'smoke-win32', 'smoke-win32-universal')}
+
def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_path):
tag, commit = 'v1.2.3', 'a' * 40
@@ -30,7 +41,7 @@ def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_p
out = root / 'metadata-windows-x64.json'
original = package.read_bytes()
record('windows', 'x64', root, tag, commit, out)
- metadata = json.loads(out.read_text(encoding='utf-8'))
+ metadata = json.loads(out.read_text(encoding='utf-8-sig'))
assert metadata['identity'] == 'Product'
assert metadata['version'] == '1.2.3.0'
assert metadata['publisher'] == 'CN=Test'
@@ -58,7 +69,7 @@ def staged_candidate(tmp_path, r2_server, https_origin):
row = {'platform': platform, 'arch': arch, 'tag': tag, 'commit': commit, 'identity': 'Product'}
if platform == 'windows':
row.update(version='1.2.3.0', publisher='CN=Test', applicationId='App')
- package = f'Product-win-{arch}.msix'
+ package = f'HermesBundled-1.2.3-win-{arch}.msix'
handoff_name = f'win32-{arch}'
elif platform == 'macos':
package = f'HermesBundled-1.2.3-mac-{arch}.zip'
@@ -94,7 +105,7 @@ def staged_candidate(tmp_path, r2_server, https_origin):
names = ['win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64', 'termux', 'windows-universal']
handoff.fetch(tag, commit, names, fetched, ['metadata-*.json', '*.msixbundle'])
r2_server.requests.clear()
- manifest = assemble(fetched, tag, commit, base, tmp_path / 'release-candidates.json')
+ manifest = assemble(fetched, tag, commit, base, tmp_path / 'release-candidates.json', smoke_results=SMOKE_RESULTS)
assert {row['platform'] + '/' + row['arch'] for row in manifest['packages']} == {
'windows/x64', 'windows/arm64', 'macos/x64', 'macos/arm64', 'termux/aarch64'}
assert all(not file['path'].startswith(('handoff-', 'metadata-')) for file in manifest['files'])
@@ -113,11 +124,11 @@ def test_assemble_rejects_missing_and_changed_receipts(tmp_path, staged_candidat
original = receipt.read_bytes()
receipt.unlink()
with pytest.raises(ValueError, match='handoff'):
- assemble(fetched, tag, commit, base, tmp_path / 'missing.json')
+ assemble(fetched, tag, commit, base, tmp_path / 'missing.json', smoke_results=SMOKE_RESULTS)
receipt.write_bytes(original)
(fetched / 'metadata-windows-x64.json').write_text('{}', encoding='utf-8')
with pytest.raises(ValueError, match='digest'):
- assemble(fetched, tag, commit, base, tmp_path / 'changed.json')
+ assemble(fetched, tag, commit, base, tmp_path / 'changed.json', smoke_results=SMOKE_RESULTS)
def test_candidate_publication_and_store_selection(tmp_path, monkeypatch, r2_server, staged_candidate):
@@ -175,3 +186,147 @@ def test_candidate_publication_and_store_selection(tmp_path, monkeypatch, r2_ser
artifacts.promote(manifest, tmp_path / 'broken', base)
assert not any(method == 'PUT' for method, _, _ in r2_server.requests)
assert all(value == r2_server.store[key] for key, value in before.items() if not key.startswith('releases/tag/'))
+
+
+def candidate_workflow_step(tmp_path, r2_server, staged_candidate):
+ """Run real workflow shell/CLIs; replace only service endpoints and tool setup."""
+ manifest, fetched, base = staged_candidate
+ jobs = hermes_yaml.safe_load((ROOT / '.github/workflows/desktop-bundled-release.yml').read_text(encoding='utf-8-sig'))['jobs']
+ shutil.copytree(fetched, tmp_path / 'candidates')
+ bin_dir = tmp_path / 'bin'
+ bin_dir.mkdir()
+ driver = bin_dir / 'python-driver.py'
+ driver.write_text(
+ 'import runpy,sys\n'
+ f'sys.path.insert(0, {str(ROOT)!r})\n'
+ 'from scripts.releases import r2\n'
+ f'r2.s3_endpoint=lambda _: "http://127.0.0.1:{r2_server.server_port}"\n'
+ 'args=sys.argv[1:]\n'
+ 'if args[:2] == ["-m", "scripts.ci.python_packages"]:\n'
+ ' import ruamel.yaml # already provided by the test environment\n'
+ ' args=args[args.index("--")+1:]\n'
+ 'sys.argv=args[1:] if args[0] == "-m" else args\n'
+ 'if args[0] == "-m":\n'
+ ' runpy.run_module(args[1],run_name="__main__")\n'
+ 'else:\n'
+ f' runpy.run_path(str({str(ROOT)!r}+"/"+args[0]),run_name="__main__")\n',
+ encoding='utf-8')
+ body_file = tmp_path / 'release-body'
+ body_file.write_text('<!-- HERMES_BUILDS_TABLE -->', encoding='utf-8')
+ gh = bin_dir / 'gh'
+ gh.write_text(
+ f'#!{sys.executable}\nimport json,sys\nfrom pathlib import Path\n'
+ f'body=Path({str(body_file)!r})\n'
+ 'if sys.argv[1:3] == ["release", "view"]:\n'
+ ' print(json.dumps({"body":body.read_text(encoding="utf-8-sig")}))\n'
+ 'else:\n'
+ ' assert sys.argv[1:3] == ["release", "edit"], sys.argv\n'
+ ' body.write_text(sys.stdin.read(), encoding="utf-8")\n', encoding='utf-8')
+ gh.chmod(0o755)
+ for name in ('python', 'python3'):
+ command = bin_dir / name
+ command.write_text(f'#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(driver))} "$@"\n', encoding='utf-8')
+ command.chmod(0o755)
+ digest = artifacts.sha256_file(tmp_path / 'release-candidates.json')
+
+ def run(job_name, step, needs, *, pinned=digest, ambient_needs=None):
+ expressions = {
+ '${{ inputs.tag }}': manifest['tag'], '${{ inputs.manifest-sha256 }}': pinned,
+ '${{ needs.validate.outputs.sha }}': manifest['commit'], '${{ github.token }}': 'inert',
+ '${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}': base, '${{ toJSON(needs) }}': json.dumps(needs),
+ }
+ for key in ('CLOUDFLARE_R2_ACCOUNT_ID', 'CLOUDFLARE_R2_ACCESS_KEY_ID', 'CLOUDFLARE_R2_SECRET_ACCESS_KEY', 'CLOUDFLARE_R2_BUCKET'):
+ expressions['${{ ' + ('vars.' if key.endswith('_BUCKET') else 'secrets.') + key + ' }}'] = os.environ[key]
+ env = {**os.environ, 'GITHUB_SHA': manifest['commit'], 'GITHUB_REPOSITORY': 'fixture/release',
+ 'PATH': str(bin_dir) + os.pathsep + os.environ['PATH'], 'GITHUB_OUTPUT': str(tmp_path / 'outputs')}
+ env.pop('RELEASE_NEEDS', None)
+ if ambient_needs is not None:
+ env['RELEASE_NEEDS'] = json.dumps(ambient_needs)
+ for key, value in {**jobs[job_name].get('env', {}), **step.get('env', {})}.items():
+ env[key] = expressions.get(value, value)
+ assert '${{' not in env[key], (key, value)
+ return subprocess.run(['bash', '-e', '-o', 'pipefail', '-c', step['run']], cwd=tmp_path,
+ env=env, capture_output=True, text=True, encoding='utf-8', timeout=60)
+
+ return jobs, run, body_file
+
+
[email protected]('ambient_needs', [None, {job: {'result': 'skipped'} for job in SMOKE_RESULTS}])
+def test_candidate_smoke_survives_real_promotion_and_renderer(tmp_path, r2_server, staged_candidate,
+ candidate_workflow_step, ambient_needs, https_origin):
+ manifest, _, base = staged_candidate
+ jobs, run, body_file = candidate_workflow_step
+ candidate = next(step for step in jobs['candidate-manifest']['steps'] if step.get('id') == 'manifest')
+ needs = {name: {'result': 'success'} for name in jobs['candidate-manifest']['needs']}
+ result = run('candidate-manifest', candidate, needs)
+ assert result.returncode == 0, result.stdout + result.stderr
+ stored = json.loads(r2_server.store[f"releases/tag/{manifest['tag']}/release-candidates.json"][0])
+ assert stored['smoke_results'] == SMOKE_RESULTS
+ assert f'manifest-sha256={artifacts.sha256_file(tmp_path / "release-candidates.json")}' in (tmp_path / 'outputs').read_text(encoding='utf-8-sig')
+ # An unrelated orphan object must not acquire the candidate's Passed label.
+ orphan = f"releases/tag/{manifest['tag']}/HermesBundled-1.2.3-linux-x64.AppImage"
+ r2_server.store[orphan] = (b'orphan transport fixture', '"e"')
+ for step in jobs['stable-promote']['steps']:
+ if 'run' in step:
+ result = run('stable-promote', step, {'validate': {'result': 'success'}}, ambient_needs=ambient_needs)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert 'releases/win32/stable/stable.appinstaller' in r2_server.store
+ page = r2_server.store['releases/stable/index.html'][0].decode()
+ for output in (page, body_file.read_text(encoding='utf-8-sig')):
+ assert output.count('Passed') == len(SMOKE_RESULTS)
+ assert 'Not run' not in output and 'Build incomplete' not in output
+ assert orphan not in output
+ assert base + f"/releases/tag/{manifest['tag']}/HermesBundled-1.2.3-win-x64.msix" in output
+ with https_origin.opener(base + '/releases/stable/index.html', timeout=5) as response:
+ assert response.read().decode() == page
+
+
+def test_candidate_smoke_admission_fails_before_publication(tmp_path, r2_server, staged_candidate, candidate_workflow_step):
+ manifest, _, _ = staged_candidate
+ jobs, run, body_file = candidate_workflow_step
+ candidate = next(step for step in jobs['candidate-manifest']['steps'] if step.get('id') == 'manifest')
+ needs = {name: {'result': 'success'} for name in jobs['candidate-manifest']['needs']}
+ for name in SMOKE_RESULTS:
+ for outcome in ('failure', 'cancelled', 'skipped', None):
+ failed = copy.deepcopy(needs)
+ if outcome is None:
+ del failed[name]
+ else:
+ failed[name]['result'] = outcome
+ r2_server.requests.clear()
+ result = run('candidate-manifest', candidate, failed)
+ assert result.returncode != 0 and name in result.stderr, result.stdout + result.stderr
+ assert not any(method == 'PUT' for method, _, _ in r2_server.requests)
+ key = f"releases/tag/{manifest['tag']}/release-candidates.json"
+ raw = r2_server.store[key][0]
+ for fault, message in [('legacy', 'Legacy candidate'), ('missing', 'Candidate smoke results'),
+ ('failed', 'smoke-win32=failure'), ('identity', 'release identity'),
+ ('tampered', 'digest mismatch')]:
+ invalid = copy.deepcopy(manifest)
+ if fault == 'legacy':
+ invalid['schema'] = 1
+ invalid.pop('smoke_results', None)
+ elif fault == 'missing':
+ invalid.pop('smoke_results', None)
+ elif fault == 'failed':
+ invalid['smoke_results'] = {**SMOKE_RESULTS, 'smoke-win32': {'result': 'failure'}}
+ else:
+ invalid['commit'] = 'b' * 40
+ data = json.dumps(invalid).encode()
+ r2_server.store[key] = (data, '"fault"')
+ digest = hashlib.sha256(raw if fault == 'tampered' else data).hexdigest()
+ before = dict(r2_server.store), body_file.read_bytes()
+ # Exercise both commands independently, not just shell short-circuiting.
+ for step in jobs['stable-promote']['steps']:
+ if 'run' not in step:
+ continue
+ r2_server.requests.clear()
+ result = run('stable-promote', step, {}, pinned=digest)
+ assert result.returncode != 0, (fault, step, result.stdout, result.stderr)
+ assert message in result.stderr, result.stdout + result.stderr
+ assert not any(method == 'PUT' for method, _, _ in r2_server.requests)
+ assert (dict(r2_server.store), body_file.read_bytes()) == before
+ r2_server.store[key] = (raw, '"original"')
diff --git a/tests/scripts/test_release_handoff.py b/tests/scripts/test_release_handoff.py
index 1f03117065e..6f33159657d 100644
--- a/tests/scripts/test_release_handoff.py
+++ b/tests/scripts/test_release_handoff.py
@@ -152,3 +152,101 @@ def test_commit_identity_and_simultaneous_namespaces(tmp_path, r2_server):
r2_server.store[f'releases/commit/{commit}/handoff-win32-x64.json'] = (b'not-json', '"e"')
with pytest.raises(json.JSONDecodeError):
handoff.read_commit_receipt(commit, 'win32-x64')
+
+
[email protected]('tag', ['v1.2.3', None])
+def test_public_handoff_downloads_exact_staged_bytes_without_credentials(tmp_path, monkeypatch, r2_server, tag):
+ import os
+ from pathlib import Path
+ import subprocess
+ import sys
+
+ commit = 'a' * 40
+ identity = ['--tag', tag, '--commit', commit] if tag else ['--commit-build', commit]
+ prefix = f'releases/tag/{tag}/' if tag else f'releases/commit/{commit}/'
+ built = tmp_path / 'built'
+ built.mkdir()
+ payload = b'public artifact transport fixture\n' * 90000
+ (built / 'app x64.msix').write_bytes(payload)
+ handoff.main(['stage', *identity, '--name', 'win32-x64', '--root', str(built), '--include', '*.msix'])
+ for key in ('CLOUDFLARE_R2_ACCOUNT_ID', 'CLOUDFLARE_R2_ACCESS_KEY_ID',
+ 'CLOUDFLARE_R2_SECRET_ACCESS_KEY', 'CLOUDFLARE_R2_BUCKET'):
+ monkeypatch.delenv(key)
+ r2_server.requests.clear()
+ download = tmp_path / 'downloaded'
+ base = f'http://127.0.0.1:{r2_server.server_port}/hermes-releases'
+ args = ['fetch', *identity, '--public-base', base, '--name', 'win32-x64',
+ '--root', str(download), '--include', '*.msix']
+ handoff.main(args)
+ assert (download / 'app x64.msix').read_bytes() == payload
+ receipt_file = download / 'handoff-win32-x64.json'
+ original_receipt = receipt_file.read_bytes()
+ assert json.loads(original_receipt)['commit'] == commit
+ assert all(method == 'GET' and not any(k.lower() == 'authorization' for k in headers)
+ for method, _, headers in r2_server.requests)
+ assert any(path.endswith('/app%20x64.msix') for _, path, _ in r2_server.requests)
+ result = subprocess.run([sys.executable, '-m', 'scripts.releases.handoff', *args],
+ cwd=Path(__file__).resolve().parents[2], env=os.environ,
+ capture_output=True, text=True, encoding='utf-8', timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert (download / 'app x64.msix').read_bytes() == payload
+ # A bad CDN object cannot replace a previously verified local download.
+ r2_server.store[prefix + 'app x64.msix'] = (b'corrupt', '"changed"')
+ with pytest.raises(ValueError, match='checksum mismatch'):
+ handoff.main(args)
+ assert (download / 'app x64.msix').read_bytes() == payload
+ assert receipt_file.read_bytes() == original_receipt
+ assert sorted(p.name for p in download.iterdir()) == ['app x64.msix', receipt_file.name]
+ bad = json.loads(original_receipt)
+ bad['commit'] = 'b' * 40
+ r2_server.store[prefix + receipt_file.name] = (json.dumps(bad).encode(), '"bad"')
+ r2_server.requests.clear()
+ with pytest.raises(ValueError, match='identity'):
+ handoff.main(args)
+ assert len(r2_server.requests) == 1
+ bad = json.loads(original_receipt)
+ bad['files'][0]['path'] = '../outside.msix'
+ r2_server.store[prefix + receipt_file.name] = (json.dumps(bad).encode(), '"bad"')
+ r2_server.requests.clear()
+ with pytest.raises(ValueError, match='path'):
+ handoff.main(args)
+ assert len(r2_server.requests) == 1
+ assert not (tmp_path / 'outside.msix').exists()
+
+
+def test_public_handoff_rejects_unsafe_origins_paths_and_redirects(tmp_path, r2_server):
+ import threading
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ commit = 'a' * 40
+ args = ['fetch', '--commit-build', commit, '--name', 'win32-x64', '--root', str(tmp_path / 'out')]
+ for base in ('http://cdn.example', 'https://user:[email protected]', 'file:///tmp',
+ 'https://cdn.example/?token=private', 'https://cdn.example/#fragment',
+ 'https://cdn.example/../escape', 'https://cdn.example/%2e%2e/escape'):
+ with pytest.raises(ValueError, match='public'):
+ handoff.main([*args, '--public-base', base])
+ assert r2_server.requests == []
+
+ class Redirect(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(302)
+ self.send_header('Location', f'http://127.0.0.1:{r2_server.server_port}/hermes-releases/unwanted')
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ def log_message(self, format, *args):
+ pass
+
+ server = ThreadingHTTPServer(('127.0.0.1', 0), Redirect)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ with pytest.raises(r2.R2RequestError) as error:
+ handoff.main([*args, '--public-base', f'http://127.0.0.1:{server.server_port}'])
+ assert error.value.status == 302
+ assert r2_server.requests == []
+ assert not (tmp_path / 'out').exists()
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
diff --git a/tests/scripts/test_render_builds_binding.py b/tests/scripts/test_render_builds_binding.py
index cbfbd798a46..95cd567861e 100644
--- a/tests/scripts/test_render_builds_binding.py
+++ b/tests/scripts/test_render_builds_binding.py
@@ -32,7 +32,7 @@ def test_commit_row_binding_faults(listed, objects, state, diagnostic):
for output in (summary, page):
assert diagnostic in output
assert ('https://cdn.example/' + PREFIX + PACKAGE in output) == (state == 'built')
- assert 'Store' not in output
+ assert 'Store-' not in output
assert rbt.recorded_build(page) == SHA
assert 'Bundle environment' not in page
@@ -45,3 +45,24 @@ def test_commit_row_binding_faults(listed, objects, state, diagnostic):
])
def test_failed_legs_from_release_needs(needs, expected):
assert rbt.failed_legs_from_release_needs(needs) == expected
+
+
[email protected]('state,status', [
+ ('success', 'Passed'), ('failure', 'Failed'), ('cancelled', 'Cancelled'),
+ ('skipped', 'Not run'), (None, 'Not run (no result)'),
+])
+def test_download_survives_smoke_failure_without_claiming_acceptance(state, status):
+ receipt = {'schema': 2, 'commit': SHA, 'name': 'win32-x64',
+ 'files': [{'path': PACKAGE, 'size': 1, 'sha256': '0' * 64}]}
+ needs = {} if state is None else {'smoke-win32': {'result': state}}
+ inputs = ([PREFIX + PACKAGE], 'https://cdn.example', SHA, {'win32-x64': receipt})
+ summary = rbt.render_commit_summary(*inputs, smoke_results=needs)
+ page = rbt.render_commit_page(SHA, inputs[0], inputs[1], inputs[3], smoke_results=needs)
+ assert f'| Windows MSIX (arm64 and x64) | {status} |' in summary
+ assert f'<td>Windows MSIX (arm64 and x64)</td><td>{status}</td>' in page
+ for output in (summary, page):
+ assert '✅ Built' in output and 'https://cdn.example/' + PREFIX + PACKAGE in output
+ assert 'unsigned Store envelopes are not install-smoked' in output
+ missing = rbt.render_commit_summary([], 'https://cdn.example', SHA, {},
+ failed_legs=['assemble-win32-bundle'])
+ assert 'failed: assemble-win32-bundle' in missing
diff --git a/tests/scripts/test_source_build_env.py b/tests/scripts/test_source_build_env.py
new file mode 100644
index 00000000000..4cb84b80f13
--- /dev/null
+++ b/tests/scripts/test_source_build_env.py
@@ -0,0 +1,128 @@
+"""Source E2E children stamp their own checkout, not the workflow's NEW ref."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+ASSETS = ROOT / "tests/install/e2e-assets"
+
+
+def _stamp_probe(tmp_path, shell):
+ repo = tmp_path / "installed source"
+ for relative in (
+ "scripts/write_install_stamp.py", "hermes_cli/__init__.py",
+ "hermes_cli/update_channel.py", "hermes_cli/runtime_paths.py",
+ "hermes_cli/steward.py", "hermes_constants.py",
+ ):
+ dest = repo / relative
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / relative, dest)
+ env = dict(os.environ, HOME=str(tmp_path), HERMES_HOME=str(tmp_path / "home"),
+ GIT_CONFIG_GLOBAL=str(tmp_path / "gitconfig"), GIT_CONFIG_NOSYSTEM="1")
+ (tmp_path / "gitconfig").write_text('[url "file:///staged/serve.git"]\n'
+ '\tinsteadOf = https://github.com/NousResearch/hermes-agent.git\n',
+ encoding="utf-8")
+
+ def git(*args):
+ return subprocess.run(["git", *args], cwd=repo, env=env, check=True,
+ capture_output=True, text=True, timeout=30).stdout.strip()
+
+ git("init", "-q", "-b", "installed")
+ git("config", "user.name", "Fixture")
+ git("config", "user.email", "[email protected]")
+ git("add", ".")
+ git("commit", "-qm", "OLD")
+ old = git("rev-parse", "HEAD")
+ git("commit", "--allow-empty", "-qm", "NEW")
+ new = git("rev-parse", "HEAD")
+ # Control: this is the real stamp writer's CI preference, not a source-text assertion.
+ stamp_command = [sys.executable, "-I", "-S", str(repo / "scripts/write_install_stamp.py"),
+ "--output", str(tmp_path / "contaminated.json"), "--update-mechanism", "self"]
+ git("checkout", "-q", "-B", "installed", old)
+ subprocess.run(stamp_command, env={**env, "GITHUB_SHA": new}, check=True,
+ capture_output=True, text=True, timeout=30)
+ assert json.loads((tmp_path / "contaminated.json").read_text(encoding="utf-8-sig"))["commit"] == new
+ overrides = dict(GITHUB_SHA=new, GITHUB_REF="refs/heads/workflow", GITHUB_REF_NAME="workflow",
+ GITHUB_HEAD_REF="workflow", GITHUB_BASE_REF="main", HERMES_BUILD_COMMIT=new,
+ HERMES_PAYLOAD_TAG="v1.2.3", HERMES_PAYLOAD_VERSION="1.2.3",
+ HERMES_DESKTOP_VARIANT="bundled")
+ env.update(overrides, ASSETS=str(ASSETS), PROBE_PYTHON=sys.executable,
+ PROBE_ROOT=str(repo), PROBE_OUT=str(tmp_path / "stamp.json"),
+ PROBE_ENV=str(tmp_path / "child-env.json"))
+ probe = tmp_path / "probe.py"
+ probe.write_text('''import json, os, runpy
+from pathlib import Path
+stamp = runpy.run_path(str(Path(os.environ['PROBE_ROOT']) / 'scripts/write_install_stamp.py'))
+stamp['write_stamp'](os.environ['PROBE_OUT'], update_mechanism='self')
+Path(os.environ['PROBE_ENV']).write_text(json.dumps(dict(os.environ)), encoding='utf-8')
+''', encoding="utf-8")
+ env["PROBE_SCRIPT"] = str(probe)
+ if shell == "bash":
+ command = [shell, "-euc", '''
+source "$ASSETS/source-build-env.sh"
+source_build_env "$PROBE_PYTHON" -I -S "$PROBE_SCRIPT"
+if source_build_env "$PROBE_PYTHON" -I -S -c 'raise SystemExit(23)'; then exit 99; else test "$?" = 23; fi
+"$PROBE_PYTHON" -I -S -c 'import json, os; print(json.dumps(dict(os.environ)))'
+''']
+ elif shell == "node":
+ env["HERMES_DESKTOP_USER_DATA_DIR"] = str(tmp_path / "user-data")
+ env["HERMES_PYTHON_SRC_ROOT"] = str(repo)
+ command = [shell, "--input-type=module", "-e", '''
+import { pathToFileURL } from 'node:url';
+import { spawnSync } from 'node:child_process';
+const { updateWindowEnvironment } = await import(pathToFileURL(process.env.ASSETS + '/update-window-chat.mjs'));
+const env = updateWindowEnvironment(process.env, process.env.PROBE_ROOT, 'source');
+const result = spawnSync(process.env.PROBE_PYTHON, ['-I', '-S', process.env.PROBE_SCRIPT], { env, stdio: 'inherit' });
+if (result.error || result.status !== 0) throw new Error(`stamp child failed: ${result.error || result.status}`);
+console.log(JSON.stringify(process.env));
+''']
+ else:
+ command = [shell, "-NoProfile", "-NonInteractive", "-Command", '''
+$ErrorActionPreference = 'Stop'
+. (Join-Path $env:ASSETS 'source-build-env.ps1')
+Invoke-SourceBuild { & $env:PROBE_PYTHON -I -S $env:PROBE_SCRIPT; if ($LASTEXITCODE) { throw 'stamp failed' } }
+try { Invoke-SourceBuild { throw 'child failure' }; throw 'lost exception' }
+catch { if ($_.Exception.Message -ne 'child failure') { throw } }
+& $env:PROBE_PYTHON -I -S -c 'import json, os; print(json.dumps(dict(os.environ)))'
+''']
+ for sha in (old, new):
+ git("checkout", "-q", "-B", "installed", sha)
+ result = subprocess.run(command, env=env, cwd=tmp_path, capture_output=True,
+ text=True, encoding="utf-8", timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ stamp = json.loads(Path(env["PROBE_OUT"]).read_text(encoding="utf-8-sig"))
+ assert (stamp["commit"], stamp["branch"], stamp["source"], stamp["payload"]) == (
+ sha, "installed", "local", "bootstrap")
+ child = json.loads(Path(env["PROBE_ENV"]).read_text(encoding="utf-8-sig"))
+ assert not overrides.keys() & child.keys()
+ assert child["GIT_CONFIG_GLOBAL"] == env["GIT_CONFIG_GLOBAL"]
+ redirect = subprocess.run(["git", "ls-remote", "--get-url",
+ "https://github.com/NousResearch/hermes-agent.git"], env=child,
+ cwd=tmp_path, check=True, capture_output=True, text=True, timeout=30)
+ assert redirect.stdout.strip() == "file:///staged/serve.git"
+ assert child["HERMES_HOME"] == env["HERMES_HOME"]
+ parent = json.loads(result.stdout.splitlines()[-1])
+ assert {key: parent[key] for key in overrides} == overrides
+
+
[email protected]("shell", ["bash", "node"])
+def test_posix_build_children_stamp_old_and_new_without_changing_parent(tmp_path, shell):
+ _stamp_probe(tmp_path, shell)
+
+
[email protected]("windows", "posix")
+def test_powershell_build_children_stamp_old_and_new_without_changing_parent(tmp_path):
+ path = os.pathsep.join(p for p in os.get_exec_path() if ".hermes" not in Path(p).parts)
+ shell = shutil.which("pwsh", path=path) or shutil.which("powershell", path=path)
+ if not shell:
+ if os.name == "nt":
+ pytest.fail("native Windows acceptance requires PowerShell")
+ pytest.skip("PowerShell is not available on this host")
+ _stamp_probe(tmp_path, shell)
\ No newline at end of file
diff --git a/tests/scripts/test_stable_release.py b/tests/scripts/test_stable_release.py
index 64df30081db..9daa481eca3 100644
--- a/tests/scripts/test_stable_release.py
+++ b/tests/scripts/test_stable_release.py
@@ -30,7 +30,9 @@ def candidates(tag, commit, digest):
"artifact": {"sha256": digest,
"url": f"{BASE}/releases/tag/{tag}/{arch}" + (".msixbundle" if platform == "windows" else ".zip")},
})
- return {"schema": 1, "tag": tag, "commit": commit, "packages": packages}
+ return {"schema": 2, "tag": tag, "commit": commit, "packages": packages,
+ "smoke_results": {name: {"result": "success"} for name in (
+ "smoke-darwin", "smoke-win32", "smoke-win32-universal")}}
def test_gate_requires_every_success_including_real_cli(tmp_path):
@@ -63,6 +65,10 @@ def test_gate_requires_every_success_including_real_cli(tmp_path):
def test_transitions_bind_all_arches_identity_version_and_archive():
old = candidates("v1.2.3", "a" * 40, "1" * 64)
+ old["schema"] = 1
+ del old["smoke_results"]
+ with pytest.raises(ValueError, match="Legacy candidate"):
+ validate_candidates(old, old["tag"], old["commit"], BASE)
new = candidates("v1.2.4", "b" * 40, "2" * 64)
require_stable_identity(new["tag"], new["commit"], "refs/tags/v1.2.4")
for tag, ref in [("v1.2.4", "refs/heads/main"), ("v1.2.4-canary.20260907143420", "refs/tags/v1.2.4-canary.20260907143420")]:
@@ -92,7 +98,7 @@ def test_transitions_bind_all_arches_identity_version_and_archive():
with pytest.raises(ValueError, match="path encoding"):
plan_transitions(old, traversal, BASE)
with pytest.raises(ValueError, match="increase"):
- plan_transitions(new, old, BASE)
+ plan_transitions(new, candidates("v1.2.3", "a" * 40, "1" * 64), BASE)
@pytest.fixture
@@ -204,7 +210,7 @@ def test_tag_movement_fails_closed(tmp_path, monkeypatch):
(repo / "input").write_text("first", encoding="utf-8")
subprocess.run(["git", "add", "input"], check=True)
subprocess.run(["git", "commit", "-m", "first"], check=True, capture_output=True)
- actual = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
+ actual = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, encoding="utf-8").strip()
subprocess.run(["git", "remote", "add", "origin", str(remote)], check=True)
subprocess.run(["git", "tag", "v1.2.3"], check=True)
subprocess.run(["git", "push", "origin", "main", "v1.2.3"], check=True, capture_output=True)