diff --git a/.github/workflows/ci-desktop.yml b/.github/workflows/ci-desktop.yml index d2f75717d..fd4c6f73e 100644 --- a/.github/workflows/ci-desktop.yml +++ b/.github/workflows/ci-desktop.yml @@ -6,7 +6,9 @@ on: source_sha: {type: string, required: true} runner: {type: string, required: true} target: {type: string, required: true} - package_artifact: {type: string, default: ''} + package_artifact_id: {type: string, default: ''} + crypto_artifact_id: {type: string, default: ''} + web_artifact_id: {type: string, default: ''} permissions: contents: read jobs: @@ -25,25 +27,39 @@ jobs: with: {node-version: '24', cache: pnpm, cache-dependency-path: pnpm-lock.yaml} - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: {python-version: '3.12'} + - name: Require exact producer artifact IDs + env: + PACKAGE_ARTIFACT_ID: ${{ inputs.package_artifact_id }} + CRYPTO_ARTIFACT_ID: ${{ inputs.crypto_artifact_id }} + WEB_ARTIFACT_ID: ${{ inputs.web_artifact_id }} + run: | + if [[ -n "$PACKAGE_ARTIFACT_ID" ]]; then + [[ "$PACKAGE_ARTIFACT_ID" =~ ^[1-9][0-9]*$ ]] + else + [[ "$CRYPTO_ARTIFACT_ID" =~ ^[1-9][0-9]*$ && "$WEB_ARTIFACT_ID" =~ ^[1-9][0-9]*$ ]] + fi - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 - if: inputs.package_artifact != '' + if: inputs.package_artifact_id != '' with: - name: ${{ inputs.package_artifact }} + artifact-ids: ${{ inputs.package_artifact_id }} + merge-multiple: true path: .artifacts/packages - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' with: - name: crypto-web-${{ inputs.source_sha }} + artifact-ids: ${{ inputs.crypto_artifact_id }} + merge-multiple: true path: apps/app/generated - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' with: - name: web-${{ inputs.source_sha }} + artifact-ids: ${{ inputs.web_artifact_id }} + merge-multiple: true path: apps/app/dist/client - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' with: key: desktop-native-${{ inputs.target }}${{ runner.os == 'Windows' && '-static-crt' || '' }} cache-on-failure: true @@ -53,7 +69,7 @@ jobs: - name: Select this platform's Python run: printf 'PY=%s\n' "$(command -v python3 || command -v python)" >> "$GITHUB_ENV" - name: Build this platform's native runtime - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' env: TARGET: ${{ inputs.target }} run: | @@ -64,7 +80,7 @@ jobs: bash scripts/package-node.sh --target "$TARGET" fi - name: Keep this platform's runtime independently reviewable - if: inputs.package_artifact == '' + if: inputs.package_artifact_id == '' uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: desktop-runtime-${{ inputs.target }}-${{ inputs.source_sha }} diff --git a/.github/workflows/ci-native.yml b/.github/workflows/ci-native.yml new file mode 100644 index 000000000..5112abd2d --- /dev/null +++ b/.github/workflows/ci-native.yml @@ -0,0 +1,41 @@ +name: ci-native +on: + workflow_call: + inputs: + runner: {type: string, required: true} + target: {type: string, required: true} + outputs: + artifact_id: + value: ${{ jobs.build.outputs.artifact_id }} + producer_attempt: + value: ${{ jobs.build.outputs.producer_attempt }} +permissions: + contents: read +jobs: + build: + runs-on: ${{ inputs.runner }} + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} + producer_attempt: ${{ github.run_attempt }} + env: + PACKAGE_TARGET: ${{ inputs.target }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 + with: + shared-key: package-${{ inputs.target }}-package + save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch' }} + - name: Build and seal native release input without Web dependencies + run: | + [[ "$(rustc -vV | sed -n 's/^host: //p')" == "$PACKAGE_TARGET" ]] + bash scripts/package-node.sh --target "$PACKAGE_TARGET" --native-output .artifacts/native-input.tar.gz + - id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: native-${{ inputs.target }}-${{ github.sha }}-${{ github.run_attempt }} + path: .artifacts/native-input.tar.gz + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/ci-package.yml b/.github/workflows/ci-package.yml new file mode 100644 index 000000000..f218f24dc --- /dev/null +++ b/.github/workflows/ci-package.yml @@ -0,0 +1,294 @@ +name: ci-package +on: + workflow_call: + inputs: + runner: {type: string, required: true} + target: {type: string, required: true} + native_artifact_id: {type: string, required: true} + producer_attempt: {type: string, required: true} + crypto_artifact_id: {type: string, required: true} + web_artifact_id: {type: string, required: true} + package_mode: {type: string, required: true} + delivery: {type: boolean, required: true} + secrets: + MACOS_CERTIFICATE_P12_BASE64: {required: false} + MACOS_CERTIFICATE_PASSWORD: {required: false} + APPLE_API_KEY_P8_BASE64: {required: false} + APPLE_API_KEY_ID: {required: false} + APPLE_API_ISSUER_ID: {required: false} + outputs: + artifact_id: + value: ${{ jobs.assemble.outputs.artifact_id }} +permissions: + contents: read +jobs: + assemble: + runs-on: ${{ inputs.runner }} + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} + env: + PACKAGE_TARGET: ${{ inputs.target }} + VIBEFACE_INPUT_ATTEMPT: ${{ inputs.producer_attempt }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ inputs.crypto_artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + artifact-ids: ${{ inputs.crypto_artifact_id }} + merge-multiple: true + path: apps/app/generated + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ inputs.web_artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + artifact-ids: ${{ inputs.web_artifact_id }} + merge-multiple: true + path: apps/app/dist/client + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ inputs.native_artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + artifact-ids: ${{ inputs.native_artifact_id }} + merge-multiple: true + path: .artifacts/native-download + - name: Restore verified same-run native input + run: python3 scripts/build-inputs.py restore native --input .artifacts/native-download/native-input.tar.gz --output .artifacts/native-input --target "$PACKAGE_TARGET" --producer-attempt "$VIBEFACE_INPUT_ATTEMPT" + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec + with: + components: rustfmt + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.12' + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 + if: inputs.target == 'x86_64-unknown-linux-gnu' + with: + version: 11.9.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: '24' + cache: ${{ inputs.target == 'x86_64-unknown-linux-gnu' && 'pnpm' || '' }} + cache-dependency-path: pnpm-lock.yaml + - name: Import Developer ID signing identity + if: inputs.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' + env: + MACOS_CERTIFICATE_P12_BASE64: ${{ secrets.MACOS_CERTIFICATE_P12_BASE64 }} + MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} + APPLE_API_KEY_P8_BASE64: ${{ secrets.APPLE_API_KEY_P8_BASE64 }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }} + run: bash scripts/import-mac-identity.sh + - name: Build native release package + run: | + [[ "$(rustc -vV | sed -n 's/^host: //p')" == "$PACKAGE_TARGET" ]] + bash scripts/package-node.sh --target "$PACKAGE_TARGET" --native-input "$PWD/.artifacts/native-input" + if [[ -n "${VIBEFACE_NOTARY_KEY:-}" ]]; then + security delete-keychain "$RUNNER_TEMP/vibeface-signing.keychain-db" + rm -f "$VIBEFACE_NOTARY_KEY" + fi + - name: Verify checksum and unpacked source identity + id: unpack + shell: bash + run: | + shopt -s nullglob + archives=(.artifacts/packages/*.tar.gz) + [[ "${#archives[@]}" == 1 ]] + archive="${archives[0]}" + name="$(basename "$archive" .tar.gz)" + (cd .artifacts/packages && shasum -a 256 -c "$name.tar.gz.sha256") + mkdir -p .artifacts/unpacked + tar -xzf "$archive" -C .artifacts/unpacked + package="$PWD/.artifacts/unpacked/$name" + python3 - "$package/BUILD-INFO.json" <<'PY' + import json, os, pathlib, re, subprocess, sys + info = json.load(open(sys.argv[1])) + config = pathlib.Path("crates/control/src/lib.rs").read_text() + protocol, epoch = (int(re.search(rf"^pub const {name}: u32 = (\d+);$", config, re.M)[1]) for name in ("UPDATE_PROTOCOL", "DATA_EPOCH")) + assert set(info) == {"version", "target", "source_commit", "update_protocol", "data_epoch", "core_version", "core_source_commit", "app_version", "app_source_commit"} + assert info["update_protocol"] == protocol and info["data_epoch"] == epoch + assert info["source_commit"] == os.environ["GITHUB_SHA"] + assert info["target"] == os.environ["PACKAGE_TARGET"] + binary = pathlib.Path(sys.argv[1]).parent / "vibeface" + web = binary.parent / "web" + assert (web / "_shell.html").stat().st_size > 0 + assert (web / "index.html").stat().st_size > 0 + assert (web / "_redirects").stat().st_size > 0 + assert (web / "_headers").stat().st_size > 0 + assert (web / ".vibeface-build.json").stat().st_size > 0 + assert (web / "vibeface_secure.js").stat().st_size > 0 + assert (web / "vibeface_secure_bg.wasm").read_bytes().startswith(b"\x00asm") + assert (binary.parent / "vibeface-core").stat().st_size > 0 + assert subprocess.check_output([str(binary), "--version"], text=True).strip() == f'vibeface {info["version"]}' + assert subprocess.check_output([str(binary.parent / "vibeface-core"), "--version"], text=True).strip() == f'vibeface-core {info["core_version"]}' + PY + "$package/vibeface" --help + "$package/vibeface-core" --help + printf 'package=%s\n' "$package" >> "$GITHUB_OUTPUT" + - name: Verify Developer ID signature + if: inputs.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: | + set -o pipefail + for binary in "$PACKAGE/vibeface" "$PACKAGE/vibeface-core"; do + codesign --verify --strict "$binary" + details="$(codesign -dvvv "$binary" 2>&1)" + printf '%s\n' "$details" + grep -qx 'Identifier=cn.leaperone.vibeface' <<< "$details" + grep -qx "TeamIdentifier=$VIBEFACE_CODESIGN_TEAM" <<< "$details" + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<< "$details" + binary_sha="$(shasum -a 256 "$binary" | cut -d ' ' -f 1)" + delays=(15 30 60 120 120 120 120 120 120) + for attempt in $(seq 0 "${#delays[@]}"); do + assessment="$RUNNER_TEMP/gatekeeper-assessment-$(basename "$binary")-$attempt.txt" + if spctl -a -vvv --ignore-cache --no-cache -t open --context context:primary-signature "$binary" >"$assessment" 2>&1; then + assessment_status=0 + else + assessment_status=$? + fi + cat "$assessment" + printf 'Gatekeeper assessment %s exited %s\n' "$attempt" "$assessment_status" + test "$(shasum -a 256 "$binary" | cut -d ' ' -f 1)" = "$binary_sha" + if test "$assessment_status" -eq 0; then + grep -qx 'source=Notarized Developer ID' "$assessment" + break + fi + if test "$assessment_status" -ne 3 || ! grep -qx 'source=Unnotarized Developer ID' "$assessment" || test "$attempt" -eq "${#delays[@]}"; then + exit "$assessment_status" + fi + sleep "${delays[$attempt]}" + done + done + - name: Verify packaged Web assets and process + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-web --web-only + - name: Verify packaged free discovery and charity delivery over real Node processes + if: inputs.delivery && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + VIBEFACE_PROBE_SOURCE_ROOT: ${{ github.workspace }} + CARGO_TARGET_DIR: ${{ github.workspace }}/.artifacts/delivery-probe/target + run: | + cargo fmt --manifest-path tests/fixtures/delivery-probe/Cargo.toml -- --check + cargo build --manifest-path tests/fixtures/delivery-probe/Cargo.toml --locked + python3 scripts/verify-node.py --delivery-charity --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts "$PWD/.artifacts/ci-delivery" --delivery-probe "$CARGO_TARGET_DIR/debug/vibeface-delivery-probe" --delivery-source-root "$PWD" --delivery-profile "$PWD/crates/delivery/proof/profile.json" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + if: ${{ !cancelled() && inputs.delivery && inputs.target == 'x86_64-unknown-linux-gnu' }} + with: + name: delivery-charity-${{ github.sha }}-${{ github.run_attempt }} + path: .artifacts/ci-delivery/delivery-charity-*/report.json + if-no-files-found: warn + retention-days: 7 + - name: Use official Ubuntu package mirror + if: inputs.target == 'x86_64-unknown-linux-gnu' + run: printf 'https://archive.ubuntu.com/ubuntu/\n' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null + - name: Cache Chromium binaries + if: inputs.target == 'x86_64-unknown-linux-gnu' + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 + with: + path: .artifacts/e2e/browsers + key: ${{ inputs.runner }}-${{ runner.arch }}-chromium-${{ hashFiles('pnpm-lock.yaml') }} + - name: Verify packaged Web onboarding in Chromium + if: inputs.target == 'x86_64-unknown-linux-gnu' + env: + VIBEFACE_E2E_BINARY: ${{ steps.unpack.outputs.package }}/vibeface + PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.artifacts/e2e/browsers + E2E_TELEMETRY_DISABLED: '1' + run: | + pnpm install --frozen-lockfile --filter . + pnpm test:e2e:check + pnpm exec e2e-web install chromium --with-deps + pnpm test:e2e + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + if: ${{ !cancelled() && inputs.target == 'x86_64-unknown-linux-gnu' }} + with: + name: e2e-${{ github.sha }}-${{ github.run_attempt }} + path: | + tests/e2e/.artifacts/results + !tests/e2e/.artifacts/results/**/downloads/** + if-no-files-found: warn + retention-days: 7 + - name: Verify unpacked Node scheduling and signed log without model calls + if: inputs.package_mode == 'node' && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-node --phase1 + - name: Verify multi-Node sync, entrances and delivery over iroh + if: inputs.package_mode == 'node' && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-multi-node + - name: Verify cross-device coordination, owner moves and attachments + if: inputs.package_mode == 'node' && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-phase4 --phase4 + - name: Verify the public entry and its relay token + if: inputs.package_mode == 'node' && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-public-entry --public-entry + - name: Verify discovery-only assistance and headless Nodes + if: inputs.package_mode == 'node' && inputs.target == 'x86_64-unknown-linux-gnu' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-discovery --discovery + - name: Verify independent macOS process suites + if: inputs.package_mode == 'node' && inputs.target == 'aarch64-apple-darwin' + env: + PACKAGE: ${{ steps.unpack.outputs.package }} + run: python3 scripts/ci.py macos-process --package "$PACKAGE" --artifacts .artifacts/macos-process + - name: Upload verified package + id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: node-package-${{ inputs.target }}-${{ github.sha }}-${{ github.run_attempt }} + path: | + .artifacts/packages/*.tar.gz + .artifacts/packages/*.tar.gz.sha256 + include-hidden-files: true + if-no-files-found: error + retention-days: 14 + - name: Upload Node failure diagnostics + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: node-process-failure-${{ inputs.target }}-${{ github.run_attempt }} + path: | + .artifacts/macos-process/results.json + .artifacts/macos-process/*.log + .artifacts/ci-web/web-process-*/report.json + .artifacts/ci-web/web-process-*/WEB/process.log + .artifacts/ci-multi-node/node-acceptance-*/C/startup-failure.json + .artifacts/ci-node/phase1-process-*/report.json + .artifacts/ci-node/phase1-process-*/A/process.log + .artifacts/ci-node/phase1-process-*/fixture-manager-*.stderr.log + .artifacts/macos-process/chat-agent/runs/chat-agent-process-*/report.json + .artifacts/macos-process/chat-agent/runs/chat-agent-process-*/A/process.log + .artifacts/macos-process/chat-agent/runs/chat-agent-process-*/fixture-manager-*.stderr.log + .artifacts/macos-process/chat-agent/runs/chat-agent-process-*/manager-tool-errors.jsonl + .artifacts/ci-phase4/phase4-*/report.json + .artifacts/ci-phase4/phase4-*/*/node.log + .artifacts/ci-discovery/discovery-*/report.json + .artifacts/ci-discovery/discovery-*/*/node.log + .artifacts/ci-public-entry/public-entry-*/report.json + .artifacts/ci-public-entry/public-entry-*/*/node.log + .artifacts/macos-process/phase5/runs/phase5-*/report.json + .artifacts/macos-process/phase5/runs/phase5-*/*/node.log + include-hidden-files: true + if-no-files-found: ignore + retention-days: 7 + - name: Remove signing keychain and notary key + if: always() && inputs.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' + run: | + security delete-keychain "$RUNNER_TEMP/vibeface-signing.keychain-db" 2> /dev/null || true + rm -f "$RUNNER_TEMP/vibeface-notary.p8" "$RUNNER_TEMP/vibeface-signing.p12" diff --git a/.github/workflows/ci-windows-native.yml b/.github/workflows/ci-windows-native.yml index bfc1a8046..bc3e7bd52 100644 --- a/.github/workflows/ci-windows-native.yml +++ b/.github/workflows/ci-windows-native.yml @@ -4,7 +4,7 @@ on: workflow_call: inputs: source_sha: {type: string, required: true} - package_artifact: {type: string, default: ''} + package_artifact_id: {type: string, default: ''} package_run_id: {type: string, default: ''} rust_checks: {type: boolean, default: true} permissions: @@ -65,7 +65,7 @@ jobs: "$PY" -B scripts/ci.py test --tier fast --packages "${selected[@]}" process: - if: inputs.package_artifact != '' || inputs.package_run_id != '' + if: inputs.package_artifact_id != '' || inputs.package_run_id != '' name: windows packaged processes runs-on: windows-2025 timeout-minutes: 60 @@ -81,12 +81,12 @@ jobs: with: {python-version: '3.12'} - name: Validate the package source mode env: - PACKAGE_ARTIFACT: ${{ inputs.package_artifact }} + PACKAGE_ARTIFACT_ID: ${{ inputs.package_artifact_id }} PACKAGE_RUN_ID: ${{ inputs.package_run_id }} RUST_CHECKS: ${{ inputs.rust_checks }} run: | if [[ -n "$PACKAGE_RUN_ID" ]]; then - [[ -z "$PACKAGE_ARTIFACT" && "$RUST_CHECKS" == false ]] || { + [[ -z "$PACKAGE_ARTIFACT_ID" && "$RUST_CHECKS" == false ]] || { echo '::error::A prior-run package diagnostic must select one run and skip native Rust checks.' exit 1 } @@ -95,6 +95,10 @@ jobs: exit 1 } else + [[ "$PACKAGE_ARTIFACT_ID" =~ ^[1-9][0-9]*$ ]] || { + echo '::error::This run requires an exact successful package producer artifact ID.' + exit 1 + } [[ "$RUST_CHECKS" == true ]] || { echo '::error::Native Rust checks can only be skipped for a prior-run package diagnostic.' exit 1 @@ -140,11 +144,12 @@ jobs: run-id: ${{ inputs.package_run_id }} github-token: ${{ github.token }} path: .artifacts/packages - - name: Download this run's package by name - if: inputs.package_run_id == '' && inputs.package_artifact != '' + - name: Download this run's package by artifact ID + if: inputs.package_run_id == '' && inputs.package_artifact_id != '' uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 with: - name: ${{ inputs.package_artifact }} + artifact-ids: ${{ inputs.package_artifact_id }} + merge-multiple: true path: .artifacts/packages - name: Select this platform's Python run: printf 'PY=%s\n' "$(command -v python3 || command -v python)" >> "$GITHUB_ENV" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce1b7097a..2f591ebde 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,10 @@ on: - cron: '23 */4 * * *' workflow_dispatch: inputs: + feedback: + description: 'Replace older ordinary feedback on this branch; keep the full acceptance scope' + type: boolean + default: false delivery_live: description: 'Run genuine local paid delivery proofs and settlement in the bounded Linux sandbox' type: boolean @@ -44,8 +48,8 @@ on: default: false concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.delivery_small && 'delivery-small' || format('{0}-{1}-{2}', github.event_name, github.ref, (github.event_name == 'workflow_dispatch' || github.run_attempt > 1) && github.run_id || '') }} - cancel-in-progress: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && github.run_attempt == 1 }} + group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.delivery_small && 'delivery-small' || format('{0}-{1}-{2}', github.event_name, github.ref, github.event_name == 'workflow_dispatch' && inputs.feedback && !inputs.delivery_live && !inputs.delivery_small && inputs.delivery_small_resume_run == '' && !inputs.desktop_only && !inputs.windows_only && inputs.mobile_apps == 'none' && !inputs.desktop && inputs.windows_package_run == '' && github.run_attempt == 1 && 'feedback' || (github.event_name == 'workflow_dispatch' || github.run_attempt > 1) && github.run_id || '') }} + cancel-in-progress: ${{ github.run_attempt == 1 && (github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch' && inputs.feedback && !inputs.delivery_live && !inputs.delivery_small && inputs.delivery_small_resume_run == '' && !inputs.desktop_only && !inputs.windows_only && inputs.mobile_apps == 'none' && !inputs.desktop && inputs.windows_package_run == '') }} permissions: contents: read @@ -165,7 +169,7 @@ jobs: pnpm --filter vibeface-www run check:static - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: www-${{ github.sha }} + name: www-${{ github.sha }}-${{ github.run_attempt }} path: apps/www/dist/client include-hidden-files: true if-no-files-found: error @@ -174,6 +178,8 @@ jobs: crypto-web: needs: plan if: needs.plan.outputs.web == 'true' + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -196,9 +202,10 @@ jobs: bash scripts/build-web-crypto.sh cargo build -p vibeface-secure --example secure-probe --locked node scripts/crypto-client.mjs --self-test --native-probe target/debug/examples/secure-probe - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: crypto-web-${{ github.sha }} + name: crypto-web-${{ github.sha }}-${{ github.run_attempt }} path: | apps/app/generated/vibeface_secure.js apps/app/generated/vibeface_secure_bg.wasm @@ -211,14 +218,21 @@ jobs: web: needs: [plan, crypto-web] if: needs.plan.outputs.web == 'true' + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.crypto-web.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: crypto-web-${{ github.sha }} + artifact-ids: ${{ needs.crypto-web.outputs.artifact_id }} + merge-multiple: true path: apps/app/generated - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 with: @@ -230,9 +244,10 @@ jobs: cache-dependency-path: pnpm-lock.yaml - name: Build and typecheck the static web client run: bash scripts/build-web.sh - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: web-${{ github.sha }} + name: web-${{ github.sha }}-${{ github.run_attempt }} path: apps/app/dist/client include-hidden-files: true if-no-files-found: error @@ -349,7 +364,7 @@ jobs: - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 if: ${{ !cancelled() }} with: - name: delivery-${{ github.sha }} + name: delivery-${{ github.sha }}-${{ github.run_attempt }} path: | .artifacts/vdp/host-info.json .artifacts/vdp/proof-results.json @@ -358,59 +373,125 @@ jobs: if-no-files-found: warn retention-days: 7 - package: + native-linux: + needs: plan + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'x86_64-unknown-linux-gnu') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-native.yml + with: + runner: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + + package-linux: + needs: [plan, native-linux, crypto-web, web] + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'x86_64-unknown-linux-gnu') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-package.yml + with: + runner: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + native_artifact_id: ${{ needs.native-linux.outputs.artifact_id }} + producer_attempt: ${{ needs.native-linux.outputs.producer_attempt }} + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} + package_mode: ${{ needs.plan.outputs.package_mode }} + delivery: ${{ needs.plan.outputs.delivery == 'true' }} + + native-linux-arm: + needs: plan + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'aarch64-unknown-linux-gnu') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-native.yml + with: + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + + package-linux-arm: + needs: [plan, native-linux-arm, crypto-web, web] + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'aarch64-unknown-linux-gnu') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-package.yml + with: + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + native_artifact_id: ${{ needs.native-linux-arm.outputs.artifact_id }} + producer_attempt: ${{ needs.native-linux-arm.outputs.producer_attempt }} + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} + package_mode: ${{ needs.plan.outputs.package_mode }} + delivery: ${{ needs.plan.outputs.delivery == 'true' }} + + native-macos: + needs: plan + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'aarch64-apple-darwin') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-native.yml + with: + runner: macos-15 + target: aarch64-apple-darwin + + package-macos: + needs: [plan, native-macos, crypto-web, web] + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'aarch64-apple-darwin') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + uses: ./.github/workflows/ci-package.yml + with: + runner: macos-15 + target: aarch64-apple-darwin + native_artifact_id: ${{ needs.native-macos.outputs.artifact_id }} + producer_attempt: ${{ needs.native-macos.outputs.producer_attempt }} + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} + package_mode: ${{ needs.plan.outputs.package_mode }} + delivery: ${{ needs.plan.outputs.delivery == 'true' }} + secrets: + MACOS_CERTIFICATE_P12_BASE64: ${{ secrets.MACOS_CERTIFICATE_P12_BASE64 }} + MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} + APPLE_API_KEY_P8_BASE64: ${{ secrets.APPLE_API_KEY_P8_BASE64 }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }} + + package-windows: + name: package (x86_64-pc-windows-msvc) needs: [plan, crypto-web, web] - if: ${{ (needs.plan.outputs.package == 'true') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) }} - name: package (${{ matrix.target }}) - runs-on: ${{ matrix.runner }} + if: contains(fromJSON(needs.plan.outputs.package_matrix).include.*.target, 'x86_64-pc-windows-msvc') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) + runs-on: windows-2025 defaults: run: shell: bash - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.plan.outputs.package_matrix) }} + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} env: - PACKAGE_TARGET: ${{ matrix.target }} + PACKAGE_TARGET: x86_64-pc-windows-msvc steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.crypto-web.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: crypto-web-${{ github.sha }} + artifact-ids: ${{ needs.crypto-web.outputs.artifact_id }} + merge-multiple: true path: apps/app/generated + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.web.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: web-${{ github.sha }} + artifact-ids: ${{ needs.web.outputs.artifact_id }} + merge-multiple: true path: apps/app/dist/client - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: - key: package-${{ matrix.target }}${{ runner.os == 'Windows' && '-static-crt' || '' }} + key: package-x86_64-pc-windows-msvc-static-crt save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch' }} - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: '3.12' - - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 - if: matrix.target == 'x86_64-unknown-linux-gnu' - with: - version: 11.9.0 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '24' - cache: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && 'pnpm' || '' }} - cache-dependency-path: pnpm-lock.yaml - - name: Import Developer ID signing identity - if: matrix.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' - env: - MACOS_CERTIFICATE_P12_BASE64: ${{ secrets.MACOS_CERTIFICATE_P12_BASE64 }} - MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} - APPLE_API_KEY_P8_BASE64: ${{ secrets.APPLE_API_KEY_P8_BASE64 }} - APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} - APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }} - run: bash scripts/import-mac-identity.sh - name: Select this platform's Python run: printf 'PY=%s\n' "$(command -v python3 || command -v python)" >> "$GITHUB_ENV" - uses: ./.github/actions/msvc-environment @@ -418,15 +499,7 @@ jobs: - name: Build native release package run: | [[ "$(rustc -vV | sed -n 's/^host: //p')" == "$PACKAGE_TARGET" ]] - if [[ "$PACKAGE_TARGET" == *-windows-* ]]; then - "$PY" scripts/package-node-windows.py - else - bash scripts/package-node.sh --target "$PACKAGE_TARGET" - fi - if [[ -n "${VIBEFACE_NOTARY_KEY:-}" ]]; then - security delete-keychain "$RUNNER_TEMP/vibeface-signing.keychain-db" - rm -f "$VIBEFACE_NOTARY_KEY" - fi + "$PY" scripts/package-node-windows.py - name: Verify checksum and unpacked source identity id: unpack run: | @@ -470,168 +543,17 @@ jobs: "$package/vibeface-core$exe" --help printf 'package=%s\n' "$package" >> "$GITHUB_OUTPUT" printf 'exe=%s\n' "$exe" >> "$GITHUB_OUTPUT" - - name: Verify Developer ID signature - if: matrix.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: | - set -o pipefail - for binary in "$PACKAGE/vibeface" "$PACKAGE/vibeface-core"; do - codesign --verify --strict "$binary" - details="$(codesign -dvvv "$binary" 2>&1)" - printf '%s\n' "$details" - grep -qx 'Identifier=cn.leaperone.vibeface' <<< "$details" - grep -qx "TeamIdentifier=$VIBEFACE_CODESIGN_TEAM" <<< "$details" - grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<< "$details" - binary_sha="$(shasum -a 256 "$binary" | cut -d ' ' -f 1)" - delays=(15 30 60 120 120 120 120 120 120) - for attempt in $(seq 0 "${#delays[@]}"); do - assessment="$RUNNER_TEMP/gatekeeper-assessment-$(basename "$binary")-$attempt.txt" - if spctl -a -vvv --ignore-cache --no-cache -t open --context context:primary-signature "$binary" >"$assessment" 2>&1; then - assessment_status=0 - else - assessment_status=$? - fi - cat "$assessment" - printf 'Gatekeeper assessment %s exited %s\n' "$attempt" "$assessment_status" - test "$(shasum -a 256 "$binary" | cut -d ' ' -f 1)" = "$binary_sha" - if test "$assessment_status" -eq 0; then - grep -qx 'source=Notarized Developer ID' "$assessment" - break - fi - if test "$assessment_status" -ne 3 || ! grep -qx 'source=Unnotarized Developer ID' "$assessment" || test "$attempt" -eq "${#delays[@]}"; then - exit "$assessment_status" - fi - sleep "${delays[$attempt]}" - done - done - - name: Verify packaged Web assets and process - if: matrix.target != 'x86_64-pc-windows-msvc' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-web --web-only - - name: Verify packaged free discovery and charity delivery over real Node processes - if: needs.plan.outputs.delivery == 'true' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - VIBEFACE_PROBE_SOURCE_ROOT: ${{ github.workspace }} - CARGO_TARGET_DIR: ${{ github.workspace }}/.artifacts/delivery-probe/target - run: | - cargo fmt --manifest-path tests/fixtures/delivery-probe/Cargo.toml -- --check - cargo build --manifest-path tests/fixtures/delivery-probe/Cargo.toml --locked - python3 scripts/verify-node.py --delivery-charity --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts "$PWD/.artifacts/ci-delivery" --delivery-probe "$CARGO_TARGET_DIR/debug/vibeface-delivery-probe" --delivery-source-root "$PWD" --delivery-profile "$PWD/crates/delivery/proof/profile.json" - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - if: ${{ !cancelled() && needs.plan.outputs.delivery == 'true' && matrix.target == 'x86_64-unknown-linux-gnu' }} - with: - name: delivery-charity-${{ github.sha }} - path: .artifacts/ci-delivery/delivery-charity-*/report.json - if-no-files-found: warn - retention-days: 7 - - name: Use official Ubuntu package mirror - if: matrix.target == 'x86_64-unknown-linux-gnu' - run: printf 'https://archive.ubuntu.com/ubuntu/\n' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null - - name: Cache Chromium binaries - if: matrix.target == 'x86_64-unknown-linux-gnu' - uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 - with: - path: .artifacts/e2e/browsers - key: ${{ matrix.runner }}-${{ runner.arch }}-chromium-${{ hashFiles('pnpm-lock.yaml') }} - - name: Verify packaged Web onboarding in Chromium - if: matrix.target == 'x86_64-unknown-linux-gnu' - env: - VIBEFACE_E2E_BINARY: ${{ steps.unpack.outputs.package }}/vibeface - PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.artifacts/e2e/browsers - E2E_TELEMETRY_DISABLED: '1' - run: | - pnpm install --frozen-lockfile --filter . - pnpm test:e2e:check - pnpm exec e2e-web install chromium --with-deps - pnpm test:e2e - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - if: ${{ !cancelled() && matrix.target == 'x86_64-unknown-linux-gnu' }} - with: - name: e2e-${{ github.sha }} - path: | - tests/e2e/.artifacts/results - !tests/e2e/.artifacts/results/**/downloads/** - if-no-files-found: warn - retention-days: 7 - - name: Verify unpacked Node scheduling and signed log without model calls - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-node --phase1 - - name: Verify multi-Node sync, entrances and delivery over iroh - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-multi-node - - name: Verify bot tools and startup event recovery - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'aarch64-apple-darwin' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-chat-agent --chat-agent - - name: Verify cross-device coordination, owner moves and attachments - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-phase4 --phase4 - - name: Verify the public entry and its relay token - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-public-entry --public-entry - - name: Verify discovery-only assistance and headless Nodes - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'x86_64-unknown-linux-gnu' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-discovery --discovery - - name: Verify write protection, status and diagnostics - if: needs.plan.outputs.package_mode == 'node' && matrix.target == 'aarch64-apple-darwin' - env: - PACKAGE: ${{ steps.unpack.outputs.package }} - run: python3 scripts/verify-node.py --binary "$PACKAGE/vibeface" --core-binary "$PACKAGE/vibeface-core" --crypto-module "$PACKAGE/web/vibeface_secure.js" --artifacts .artifacts/ci-phase5 --phase5 - name: Upload verified package + id: upload uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: node-package-${{ matrix.target }}-${{ github.sha }} + name: node-package-x86_64-pc-windows-msvc-${{ github.sha }} path: | .artifacts/packages/*.tar.gz .artifacts/packages/*.tar.gz.sha256 include-hidden-files: true if-no-files-found: error retention-days: 14 - - name: Upload Node failure diagnostics - if: failure() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: node-process-failure-${{ matrix.target }}-${{ github.run_attempt }} - path: | - .artifacts/ci-web/web-process-*/report.json - .artifacts/ci-web/web-process-*/WEB/process.log - .artifacts/ci-node/phase1-process-*/report.json - .artifacts/ci-node/phase1-process-*/A/process.log - .artifacts/ci-node/phase1-process-*/fixture-manager-*.stderr.log - .artifacts/ci-chat-agent/chat-agent-process-*/report.json - .artifacts/ci-chat-agent/chat-agent-process-*/A/process.log - .artifacts/ci-chat-agent/chat-agent-process-*/fixture-manager-*.stderr.log - .artifacts/ci-chat-agent/chat-agent-process-*/manager-tool-errors.jsonl - .artifacts/ci-phase4/phase4-*/report.json - .artifacts/ci-phase4/phase4-*/*/node.log - .artifacts/ci-discovery/discovery-*/report.json - .artifacts/ci-discovery/discovery-*/*/node.log - .artifacts/ci-public-entry/public-entry-*/report.json - .artifacts/ci-public-entry/public-entry-*/*/node.log - .artifacts/ci-phase5/phase5-*/report.json - .artifacts/ci-phase5/phase5-*/*/node.log - include-hidden-files: true - if-no-files-found: ignore - retention-days: 7 - - name: Remove signing keychain and notary key - if: always() && matrix.target == 'aarch64-apple-darwin' && github.event_name != 'merge_group' - run: | - security delete-keychain "$RUNNER_TEMP/vibeface-signing.keychain-db" 2> /dev/null || true - rm -f "$RUNNER_TEMP/vibeface-notary.p8" "$RUNNER_TEMP/vibeface-signing.p12" delivery-small-prepare: if: github.event_name == 'workflow_dispatch' && inputs.delivery_small @@ -741,28 +663,48 @@ jobs: delivery-live: if: ${{ (github.event_name == 'workflow_dispatch' && inputs.delivery_live && !inputs.delivery_small) && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) }} - needs: [plan, package, crypto-web, web, delivery-android] + needs: [plan, package-linux, crypto-web, web, delivery-android] runs-on: ubuntu-24.04 timeout-minutes: 360 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.package-linux.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: node-package-x86_64-unknown-linux-gnu-${{ github.sha }} + artifact-ids: ${{ needs.package-linux.outputs.artifact_id }} + merge-multiple: true path: .artifacts/vdp/live-package + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.crypto-web.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: crypto-web-${{ github.sha }} + artifact-ids: ${{ needs.crypto-web.outputs.artifact_id }} + merge-multiple: true path: apps/app/generated + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.web.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: web-${{ github.sha }} + artifact-ids: ${{ needs.web.outputs.artifact_id }} + merge-multiple: true path: apps/app/dist/client + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.delivery-android.outputs.android_artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: vibeface-android-${{ github.sha }} + artifact-ids: ${{ needs.delivery-android.outputs.android_artifact_id }} + merge-multiple: true path: .artifacts/vdp/live-android - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 with: @@ -870,8 +812,10 @@ jobs: retention-days: 14 npm-package: - needs: [plan, package] + needs: [plan, package-linux, package-linux-arm, package-macos, package-windows] if: ${{ (needs.plan.outputs.npm == 'true') && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) }} + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -880,18 +824,23 @@ jobs: - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '24' + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.package-linux.outputs.artifact_id }},${{ needs.package-linux-arm.outputs.artifact_id }},${{ needs.package-macos.outputs.artifact_id }},${{ needs.package-windows.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - pattern: node-package-*-${{ github.sha }} + artifact-ids: ${{ needs.package-linux.outputs.artifact_id }},${{ needs.package-linux-arm.outputs.artifact_id }},${{ needs.package-macos.outputs.artifact_id }},${{ needs.package-windows.outputs.artifact_id }} path: .artifacts/npm-input merge-multiple: true - name: Package verified native releases for npm env: SOURCE_COMMIT: ${{ github.sha }} run: node scripts/package-npm.mjs --input .artifacts/npm-input --source-commit "$SOURCE_COMMIT" - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: npm-package-${{ github.sha }} + name: npm-package-${{ github.sha }}-${{ github.run_attempt }} path: .artifacts/npm/leaperone-vibeface-*.tgz* if-no-files-found: error retention-days: 14 @@ -916,9 +865,14 @@ jobs: - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: '3.12' + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.npm-package.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: - name: npm-package-${{ github.sha }} + artifact-ids: ${{ needs.npm-package.outputs.artifact_id }} + merge-multiple: true path: .artifacts/npm - name: Install npm artifact without lifecycle scripts id: install @@ -951,7 +905,7 @@ jobs: python3 scripts/verify-node.py --binary "$prefix/bin/vibeface" --core-binary "$VENDOR/vibeface-core" --crypto-module "$VENDOR/web/vibeface_secure.js" --artifacts .artifacts/ci-npm --web-only windows-native: - needs: [plan, package] + needs: [plan, package-windows] if: ${{ github.event_name == 'workflow_dispatch' && inputs.desktop && contains(needs.plan.outputs.package_matrix, 'x86_64-pc-windows-msvc') }} uses: ./.github/workflows/ci-windows-native.yml permissions: @@ -959,27 +913,27 @@ jobs: actions: read with: source_sha: ${{ github.sha }} - package_artifact: node-package-x86_64-pc-windows-msvc-${{ github.sha }} + package_artifact_id: ${{ needs.package-windows.outputs.artifact_id }} desktop-macos: - needs: [plan, package] + needs: [plan, package-macos] if: ${{ github.event_name == 'workflow_dispatch' && inputs.desktop && contains(needs.plan.outputs.package_matrix, 'aarch64-apple-darwin') }} uses: ./.github/workflows/ci-desktop.yml with: source_sha: ${{ github.sha }} runner: macos-15 target: aarch64-apple-darwin - package_artifact: node-package-aarch64-apple-darwin-${{ github.sha }} + package_artifact_id: ${{ needs.package-macos.outputs.artifact_id }} desktop-windows: - needs: [plan, package] + needs: [plan, package-windows] if: ${{ github.event_name == 'workflow_dispatch' && inputs.desktop && contains(needs.plan.outputs.package_matrix, 'x86_64-pc-windows-msvc') }} uses: ./.github/workflows/ci-desktop.yml with: source_sha: ${{ github.sha }} runner: windows-2025 target: x86_64-pc-windows-msvc - package_artifact: node-package-x86_64-pc-windows-msvc-${{ github.sha }} + package_artifact_id: ${{ needs.package-windows.outputs.artifact_id }} desktop-only-macos: needs: [plan, crypto-web, web] @@ -989,6 +943,8 @@ jobs: source_sha: ${{ github.sha }} runner: macos-15 target: aarch64-apple-darwin + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} desktop-only-windows: needs: [plan, crypto-web, web] @@ -998,6 +954,8 @@ jobs: source_sha: ${{ github.sha }} runner: windows-2025 target: x86_64-pc-windows-msvc + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} desktop-only-linux-x64: needs: [plan, crypto-web, web] @@ -1007,6 +965,8 @@ jobs: source_sha: ${{ github.sha }} runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} desktop-only-linux-arm64: needs: [plan, crypto-web, web] @@ -1016,6 +976,8 @@ jobs: source_sha: ${{ github.sha }} runner: ubuntu-24.04-arm target: aarch64-unknown-linux-gnu + crypto_artifact_id: ${{ needs.crypto-web.outputs.artifact_id }} + web_artifact_id: ${{ needs.web.outputs.artifact_id }} mobile-plan: if: github.event_name == 'workflow_dispatch' && inputs.mobile_apps != 'none' @@ -1146,7 +1108,7 @@ jobs: ci-gate: name: ci-gate if: ${{ (always() && !(github.event_name == 'workflow_dispatch' && inputs.delivery_small)) && !(github.event_name == 'workflow_dispatch' && (inputs.desktop_only || inputs.windows_only || inputs.mobile_apps != 'none')) }} - needs: [plan, quick-check, crypto-web, web, www, rust-check, rust-fast, rust-slow, delivery, delivery-live, package, npm-package, npm-smoke, windows-native, desktop-macos, desktop-windows] + needs: [plan, quick-check, crypto-web, web, www, rust-check, rust-fast, rust-slow, delivery, delivery-live, native-linux, native-linux-arm, native-macos, package-linux, package-linux-arm, package-macos, package-windows, npm-package, npm-smoke, windows-native, desktop-macos, desktop-windows] runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index 8553e9a6e..2b8ff896a 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -4,20 +4,27 @@ name: mobile on: workflow_dispatch: inputs: + feedback: + description: 'Replace older ordinary mobile feedback on this branch' + type: boolean + default: false platforms: description: Native mobile platforms to build and verify type: choice options: [all, android, ios] default: all workflow_call: + outputs: + android_artifact_id: + value: ${{ jobs.android.outputs.artifact_id }} inputs: android_only: type: boolean default: false concurrency: - group: mobile-${{ github.ref }}-${{ github.event_name == 'workflow_dispatch' && github.run_id || 'automatic' }} - cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} + group: mobile-${{ github.ref }}-${{ inputs.android_only && 'android-only' || inputs.platforms || 'all' }}-${{ github.event_name == 'workflow_dispatch' && !inputs.android_only && inputs.feedback && github.run_attempt == 1 && 'feedback' || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'workflow_dispatch' && !inputs.android_only && inputs.feedback && github.run_attempt == 1 }} permissions: contents: read @@ -27,6 +34,8 @@ env: jobs: android: + outputs: + artifact_id: ${{ steps.upload.outputs.artifact-id }} if: inputs.android_only || (github.event_name == 'workflow_dispatch' && inputs.platforms != 'ios') runs-on: ubuntu-24.04 timeout-minutes: 60 @@ -67,16 +76,20 @@ jobs: env: SOURCE_COMMIT: ${{ github.sha }} run: python3 scripts/run-delivery-live.py --record-android-apk apps/mobile/android/app/build/outputs/apk/release --source-commit "$SOURCE_COMMIT" - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + - id: upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: vibeface-android-${{ github.sha }} + name: vibeface-android-${{ github.sha }}-${{ github.run_attempt }} path: .artifacts/mobile-android/ if-no-files-found: error - ios: + ios-build: + outputs: + artifact_id: ${{ steps.inputs.outputs.artifact-id }} + producer_attempt: ${{ github.run_attempt }} if: ${{ !inputs.android_only && github.event_name == 'workflow_dispatch' && inputs.platforms != 'android' }} runs-on: macos-26 - timeout-minutes: 60 + timeout-minutes: 75 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: @@ -86,7 +99,10 @@ jobs: targets: aarch64-apple-ios,aarch64-apple-ios-sim,wasm32-unknown-unknown - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: - cache-on-failure: true + key: ios-host-target-v1 + workspaces: | + . -> target + . -> .artifacts/native/target - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 with: version: 11.9.0 @@ -111,7 +127,7 @@ jobs: zip -qry "$GITHUB_WORKSPACE/.artifacts/native/vibeface-ios-simulator.zip" Vibeface.app - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: vibeface-ios-simulator-${{ github.sha }} + name: vibeface-ios-simulator-${{ github.sha }}-${{ github.run_attempt }} path: .artifacts/native/vibeface-ios-simulator.zip if-no-files-found: error - name: Build the same-source host Node and browser cryptography @@ -119,20 +135,62 @@ jobs: SOURCE_COMMIT: ${{ github.sha }} CARGO_TARGET_DIR: ${{ github.workspace }}/.artifacts/native/target run: | - umask 077 - mkdir -p .artifacts/native/private - chmod 700 .artifacts/native .artifacts/native/private - printf '%s\n' host-source > .artifacts/native/private/stage.txt test "$(git rev-parse HEAD)" = "$SOURCE_COMMIT" test -z "$(git status --porcelain --untracked-files=normal)" test "$(uname -m)" = arm64 - printf '%s\n' host-build > .artifacts/native/private/stage.txt cargo install wasm-bindgen-cli --version 0.2.129 --locked bash scripts/build-web-crypto.sh bash scripts/build-web.sh - CARGO_ENCODED_RUSTFLAGS="$(python3 scripts/release-rustflags.py)" cargo build --release -p vibeface -p vibeface-core --locked + bash scripts/package-node.sh --target aarch64-apple-darwin --native-output .artifacts/native/host.tar.gz + - name: Seal the complete public iOS acceptance input + run: python3 scripts/build-inputs.py seal ios --app .artifacts/native/vibeface-ios-simulator.zip --native .artifacts/native/host.tar.gz --output .artifacts/native/ios-input.tar.gz + - id: inputs + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: ios-input-${{ github.sha }}-${{ github.run_attempt }} + path: .artifacts/native/ios-input.tar.gz + if-no-files-found: error + retention-days: 7 + + ios-accept: + needs: ios-build + if: ${{ !inputs.android_only && github.event_name == 'workflow_dispatch' }} + runs-on: macos-26 + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 + with: + version: 11.9.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: '24' + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + - run: pnpm install --frozen-lockfile --filter . + - name: Require explicit producer artifact IDs + env: + ARTIFACT_IDS: ${{ needs.ios-build.outputs.artifact_id }} + run: '[[ "$ARTIFACT_IDS" =~ ^[1-9][0-9]*(,[1-9][0-9]*)*$ ]]' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + artifact-ids: ${{ needs.ios-build.outputs.artifact_id }} + merge-multiple: true + path: .artifacts/native-download + - name: Restore and verify the successful producer input + env: + PRODUCER_ATTEMPT: ${{ needs.ios-build.outputs.producer_attempt }} + run: | + python3 scripts/build-inputs.py restore ios --input .artifacts/native-download/ios-input.tar.gz --output .artifacts/ios-input --producer-attempt "$PRODUCER_ATTEMPT" + app=.artifacts/native/ios-build/Build/Products/Release-iphonesimulator/Vibeface.app + codesign --verify --strict "$app" + otool -l "$app/Vibeface" | grep -q 'sectname __entitlements' .artifacts/native/target/release/vibeface --version .artifacts/native/target/release/vibeface-core --version + umask 077 + mkdir -p .artifacts/native/private - name: Create the dedicated iOS Provider simulator env: VIBEFACE_E2E_SOURCE_COMMIT: ${{ github.sha }} @@ -189,9 +247,17 @@ jobs: raw_path = pathlib.Path(".artifacts/native/private/ios-runner-prepare.raw.json") error_path = pathlib.Path(".artifacts/native/private/ios-runner-prepare.stderr.log") summary_path = pathlib.Path(".artifacts/native/private/ios-runner-prepare.json") - def write_failure(reason, exit_code): - summary_path.write_text(json.dumps({"status": "failed", "reason": reason, - "exit_code": exit_code}) + "\n") + prepare_module = __import__("runpy").run_path("scripts/ios-runner-prepare.py") + prepare_error_detail = prepare_module["project_error"] + + def read_prepare_error(): + return prepare_module["read_error"](pathlib.Path.cwd(), raw_path) + + def write_failure(reason, exit_code, error=None): + summary = {"status": "failed", "reason": reason, "exit_code": exit_code} + if error is not None: + summary["error"] = error + summary_path.write_text(json.dumps(summary) + "\n") print("iOS XCTest runner preparation failed: " + reason, file=sys.stderr) raise SystemExit(1) @@ -212,7 +278,7 @@ jobs: ("runner did not accept connection", "runner_connect_failed"), ("daemon request timed out", "daemon_request_timeout"), ) if needle in text), "prepare_command_failed") - write_failure(reason, exit_code) + write_failure(reason, exit_code, read_prepare_error()) try: text = raw_path.read_text(encoding="utf-8") try: @@ -263,7 +329,9 @@ jobs: print("iOS XCTest runner healthy: " + json.dumps(summary, sort_keys=True)) PY - name: Check bounded iOS actor diagnostics - run: python3 scripts/ios-actor-census.py --self-test + run: | + python3 scripts/ios-actor-census.py --self-test + python3 scripts/ios-runner-prepare.py --self-test - name: Verify Provider settings and cancellation in the installed iOS app env: VIBEFACE_E2E_SOURCE_COMMIT: ${{ github.sha }} @@ -284,12 +352,13 @@ jobs: PY printf '%s\n' ui-run > .artifacts/native/private/stage.txt set +e - pnpm exec e2e run --config tests/e2e/e2e.native.config.ts --grep '^provider ' --action-timeout 240000 --trace off --video off --retries 0 > .artifacts/native/private/ui.log 2>&1 + pnpm exec e2e run --config tests/e2e/e2e.native.config.ts --grep '^provider ' --action-timeout 240000 --trace off --video off --retries 0 --reporter json > .artifacts/native/private/ui.json 2> .artifacts/native/private/ui.log result=$? set -e + printf '%s\n' "$result" > .artifacts/native/private/ui-exit-code.txt echo "Native Provider e2e exit code: $result" exit "$result" - - name: Remove only this task simulator and private acceptance state + - name: Clean up this task and require final UI acceptance id: native_cleanup if: always() env: @@ -362,6 +431,21 @@ jobs: except (OSError, ValueError, TypeError, AssertionError): diagnostics["navigation"] = {"stage": "invalid"} + clipboard_path = public / "provider-clipboard.json" + if clipboard_path.exists() or clipboard_path.is_symlink(): + try: + info = clipboard_path.lstat() + assert stat.S_ISREG(info.st_mode) and info.st_size <= 1024 + clipboard = json.loads(clipboard_path.read_text(encoding="utf-8")) + counts = {"started", "fulfilled", "rejected", "equal", "empty", "other"} + flags = {"capped", "inflight_at_poll_failure"} + assert isinstance(clipboard, dict) and set(clipboard) == counts | flags + assert all(type(clipboard[key]) is int and 0 <= clipboard[key] <= 4096 for key in counts) + assert all(type(clipboard[key]) is bool for key in flags) + diagnostics["clipboard"] = {key: clipboard[key] for key in counts | flags} + except (OSError, ValueError, TypeError, AssertionError): + diagnostics["clipboard"] = {"status": "invalid"} + def safe_error(error, source=None, api=None): if not isinstance(error, dict): return None @@ -377,7 +461,7 @@ jobs: if frame and len(frames) < 4: frames.append({"file": "verify-node.py", "line": int(frame[1]), "function": frame[2]}) result["fixture"] = {"error_type": fixture[1], "frames": frames} - if code == "ENGINE_FAILURE" and isinstance(message, str): + if code in {"ENGINE_FAILURE", "ENVIRONMENT_UNAVAILABLE"} and isinstance(message, str): lowered = message.lower() result["engine_timeout_kind"] = next((kind for needle, kind in ( ("timed out while reading snapshot viewport on the xctest main thread", "snapshot-viewport"), @@ -419,7 +503,7 @@ jobs: line = source.get("line") if type(line) is int and 1 <= line <= 100000: result.update(file=source["file"], line=line) - if api in {"app.open", "app.screenshot", "device.installApp", "device.clearKeychain", "device.openLink", "device.dismissKeyboard", + if api in {"app.open", "app.screenshot", "device.installApp", "device.clearKeychain", "device.openLink", "device.dismissKeyboard", "device.clipboard", "screen.scrollUntilVisible", "locator.click", "locator.tap", "locator.fill", "expect.toBeVisible", "expect.toBeHidden", "expect.toHaveAccessibleName", "expect.toEqual", "expect.toBe", "expect.poll"}: result["api"] = api @@ -503,12 +587,18 @@ jobs: except (OSError, ValueError, TypeError, AssertionError): return {"status": "unreadable"} + prepare_module = __import__("runpy").run_path("scripts/ios-runner-prepare.py") + prepare_error_detail = prepare_module["project_error"] + def safe_runner_prepare(): path = root / "private/ios-runner-prepare.json" if path.is_symlink() or not path.is_file(): return {"status": "missing"} try: - result = json.loads(path.read_text(encoding="utf-8")) + with path.open("rb") as stream: + raw = stream.read(8193) + assert len(raw) <= 8192 + result = json.loads(raw) assert isinstance(result, dict) if result.get("status") == "failed": reason = result.get("reason") @@ -518,7 +608,10 @@ jobs: "prepare_reported_failure", "runner_prepare_required_recovery"} or type(exit_code) is not int or not 0 <= exit_code <= 255): return {"status": "invalid"} - return {"status": "failed", "reason": reason, "exit_code": exit_code} + summary = {"status": "failed", "reason": reason, "exit_code": exit_code} + if "error" in result: + summary["error"] = prepare_error_detail(result["error"]) + return summary assert result.get("status") == "healthy" assert result.get("cache") in {"exact", "miss", "external", "unknown"} assert result.get("artifact") in {"valid", "rebuilt", "unknown"} @@ -532,7 +625,7 @@ jobs: return {"status": "invalid"} summary[key] = int(value) return summary - except (OSError, ValueError, TypeError, AssertionError, KeyError): + except (OSError, ValueError, TypeError, AssertionError, KeyError, RecursionError): return {"status": "invalid"} def safe_actor_census(): @@ -566,12 +659,29 @@ jobs: runner_root = pathlib.Path("tests/e2e/.artifacts/native") report_path = runner_root / "e2e/report.json" + canonical_report = report_path.exists() + exit_path = root / "private/ui-exit-code.txt" + ui_log = root / "private/ui.log" + if exit_path.exists(): + value = exit_path.read_text().strip() + if re.fullmatch(r"[0-9]{1,3}", value) and int(value) <= 255: + diagnostics["runner_exit_code"] = int(value) + if not canonical_report and ui_log.exists(): + logged = ui_log.read_text(errors="replace") + for code in ("ENVIRONMENT_UNAVAILABLE", "ENGINE_FAILURE", "CONFIG_LOAD_FAILED", "INVALID_CONFIG", "SESSION_UNAVAILABLE", "SESSION_CONTRACT", "INTERNAL_ERROR"): + match = re.search(r"(?m)^" + code + r": ([^\n]*)", logged) + if match: + diagnostics["failures"].append(safe_error({"code": code, "message": match[1]})) + break + + if not canonical_report: + report_path = root / "private/ui.json" if report_path.exists(): try: run = json.loads(report_path.read_text())["run"] - diagnostics["report"] = "present" + diagnostics["report"] = "present" if canonical_report else "stdout_only" summary = run["summary"] - selected_passed = run["exitCode"] == 0 and not run["errors"] and summary["selected"] == summary["passed"] == 1 and all( + selected_passed = canonical_report and run["exitCode"] == 0 and not run["errors"] and summary["selected"] == summary["passed"] == 1 and all( summary[key] == 0 for key in ("failed", "skipped", "interrupted", "flaky")) failures = [safe_error(error) for error in run["errors"]] for result in run["results"]: @@ -629,6 +739,7 @@ jobs: ("welcome", None, "连接你的网络"), ("ready", None, "已填入加入链接"), ("invitation", "textbox", "加入链接"), ("device_name", "textbox", "这台设备的名字"), ("join", "button", "加入"), ("invalid_link", None, "这不是有效的加入链接"), + ("add_device", None, "添加设备"), ("open_button", "button", "Open"), ("cancel_button", "button", "Cancel"), ("spent_link", None, "这条加入链接已用过或已过期。在已有设备上点“添加设备”重新生成。"), ): prefix = r"^\s*#\S+ " + (re.escape(role) + " " if role else r"(?:[a-z-]+ )?") @@ -691,7 +802,7 @@ jobs: - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 if: ${{ always() && !cancelled() && steps.native_cleanup.outputs.safe_public_artifacts == 'true' }} with: - name: native-provider-ios-${{ github.sha }} + name: native-provider-ios-${{ github.sha }}-${{ github.run_attempt }} path: | .artifacts/native/public/provider.json .artifacts/native/public/provider-probe.json @@ -702,3 +813,16 @@ jobs: .artifacts/native/public/terminology-device-kinds.png if-no-files-found: error retention-days: 7 + + mobile-gate: + if: always() + needs: [android, ios-build, ios-accept] + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - name: Require all selected mobile jobs + env: + MOBILE_NEEDS: ${{ toJSON(needs) }} + run: python3 scripts/ci.py mobile-gate --needs-env MOBILE_NEEDS --platforms "${{ inputs.platforms || 'all' }}" ${{ inputs.android_only && '--android-only' || '' }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index adb50611d..ea4d7c499 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -101,6 +101,7 @@ jobs: - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 with: {node-version: '24', cache: pnpm, cache-dependency-path: pnpm-lock.yaml} - run: pnpm install --frozen-lockfile + if: needs.identity.outputs.app == 'www' - name: Build and verify static application env: SCOPE: ${{ needs.identity.outputs.app }} diff --git a/apps/core/src/runtime.rs b/apps/core/src/runtime.rs index 893e5cc50..efc238dbc 100644 --- a/apps/core/src/runtime.rs +++ b/apps/core/src/runtime.rs @@ -598,7 +598,7 @@ impl Runtime { let store = Arc::new(Mutex::new(store)); let (events, _) = broadcast::channel(256); let (tx, rx) = mpsc::unbounded_channel(); - vibeface_bridge::agent::CursorAgent::kill_orphan(&dir.join(cursor::PIDFILE)); + vibeface_bridge::agent::CursorAgent::kill_orphan(&dir.join(cursor::PIDFILE))?; let mut local = crate::providers::Local { switches: config.providers.clone(), bins: config.bins.clone(), @@ -703,7 +703,7 @@ impl Runtime { .clone(); local.validate(codex_agent)?; let claude_env = local.env.get(Provider::Claude).clone(); - let claude = claude::Claude::open(dir, &claude_env); + let claude = claude::Claude::open(dir, &claude_env)?; let codex_target = local.codex_target(codex_agent); let codex = Arc::new(codex_server::CodexServer::open( codex_target, @@ -779,7 +779,7 @@ impl Runtime { maintenance: Arc::new(Gate::new(dir.join("update-pending.json").try_exists()?)), codex, claude, - pi: Arc::new(pi::Pi::new(dir)), + pi: Arc::new(pi::Pi::new(dir)?), opencode, progress_sequence: std::sync::atomic::AtomicU64::new(0), stop_retries: std::sync::Mutex::new(HashMap::new()), @@ -1010,12 +1010,22 @@ impl Runtime { if let Ok(net) = self.net() { net.close().await; } - self.codex.stop().await; - self.claude.stop().await; - self.pi.stop().await; - self.opencode.stop().await; - if let Some(bridge) = self.cursor.get() { - bridge.stop().await; + if let Err(error) = self.codex.stop().await { + tracing::warn!(%error, "Codex process-tree exit is unconfirmed during shutdown"); + } + if let Err(error) = self.claude.stop().await { + tracing::warn!(%error, "Claude process-tree exit is unconfirmed during shutdown"); + } + if let Err(error) = self.pi.stop().await { + tracing::warn!(%error, "pi process-tree exit is unconfirmed during shutdown"); + } + if let Err(error) = self.opencode.stop().await { + tracing::warn!(%error, "opencode process-tree exit is unconfirmed during shutdown"); + } + if let Some(bridge) = self.cursor.get() + && let Err(error) = bridge.stop().await + { + tracing::warn!(%error, "Cursor process-tree exit is unconfirmed during shutdown"); } } pub(crate) fn writable(&self) -> bool { diff --git a/apps/core/src/runtime/bootstrap_tests.rs b/apps/core/src/runtime/bootstrap_tests.rs index 915db7a0a..e523003a3 100644 --- a/apps/core/src/runtime/bootstrap_tests.rs +++ b/apps/core/src/runtime/bootstrap_tests.rs @@ -452,6 +452,7 @@ async fn grants_are_renewed_registered_and_survive_a_relay_restart() -> Result<( let wait = (first.grant_until_ms - now_ms()).max(0) as u64 + 200; tokio::time::sleep(Duration::from_millis(wait)).await; let mut status = node.net()?.endpoint.home_relay_status(); + status.update(); infra.entry.restart_relay().await?; wait_connected(&mut status, &relay, false).await?; assert!( @@ -462,6 +463,7 @@ async fn grants_are_renewed_registered_and_survive_a_relay_restart() -> Result<( // denial or simply renews on schedule, registers, and is admitted on the next retry. Either // way it is back without hammering the relay, and its registration is current again. let mut status = node.net()?.endpoint.home_relay_status(); + status.update(); admission.forget_all(); infra.entry.restart_relay().await?; wait_connected(&mut status, &relay, false).await?; diff --git a/apps/core/src/runtime/claude.rs b/apps/core/src/runtime/claude.rs index 3f63f3c04..92cbfdd35 100644 --- a/apps/core/src/runtime/claude.rs +++ b/apps/core/src/runtime/claude.rs @@ -124,13 +124,13 @@ impl Processes { } /// Ends the processes an earlier Node run left in `pidfile` before tracking this run's. - pub(super) fn open(pidfile: PathBuf) -> Self { - vibeface_bridge::agent::kill_recorded_programs(&pidfile); - Self::new(pidfile) + pub(super) fn open(pidfile: PathBuf) -> Result { + vibeface_bridge::agent::kill_recorded_programs(&pidfile)?; + Ok(Self::new(pidfile)) } /// Ends every recorded process; the Node calls this before it exits. - pub(super) async fn stop(&self) { + pub(super) async fn stop(self: &Arc) -> Result<()> { for input in self .inputs .lock() @@ -139,11 +139,18 @@ impl Processes { { input.open.store(false, Ordering::SeqCst); } - let pidfile = self.pidfile.clone(); - let _ = tokio::task::spawn_blocking(move || { - vibeface_bridge::agent::kill_recorded_programs(&pidfile) + let processes = self.clone(); + tokio::task::spawn_blocking(move || { + let mut running = processes + .running + .lock() + .unwrap_or_else(PoisonError::into_inner); + vibeface_bridge::agent::kill_recorded_programs(&processes.pidfile)?; + running.clear(); + Ok(()) }) - .await; + .await + .context("join the agent process-tree shutdown")? } pub(super) fn track(&self, token: &str, bin: &Path) -> Result<()> { @@ -1393,13 +1400,13 @@ impl Claude { } /// Ends the processes an earlier Node run left, so their turns are read back as they are. - pub(super) fn open(dir: &Path, env: &BTreeMap) -> Self { - Self { - processes: Arc::new(Processes::open(dir.join(PIDFILE))), + pub(super) fn open(dir: &Path, env: &BTreeMap) -> Result { + Ok(Self { + processes: Arc::new(Processes::open(dir.join(PIDFILE))?), live: Default::default(), starting: Default::default(), projects: std::sync::Mutex::new(projects_dir(env)), - } + }) } pub(super) fn processes(&self) -> Arc { @@ -1407,8 +1414,8 @@ impl Claude { } /// Ends every running Claude Code process; the Node calls this before it exits. - pub(super) async fn stop(&self) { - self.processes.stop().await; + pub(super) async fn stop(&self) -> Result<()> { + self.processes.stop().await } fn live(&self) -> std::sync::MutexGuard<'_, HashMap> { @@ -2454,7 +2461,7 @@ pub(super) mod tests { #[tokio::test] async fn bot_readback_requires_its_exact_message_and_explicit_ending() -> Result<()> { let place = Place::new()?; - let reader = Claude::open(&place.dir, &place.env()); + let reader = Claude::open(&place.dir, &place.env())?; let session = uuid::Uuid::new_v4().to_string(); let project = projects_dir(&place.env()) .context("projects")? @@ -2533,7 +2540,7 @@ pub(super) mod tests { error: None, } ); - let recovered = Claude::open(&place.dir, &place.env()); + let recovered = Claude::open(&place.dir, &place.env())?; assert_eq!( recovered .read_back( @@ -2637,7 +2644,7 @@ pub(super) mod tests { assistant("initial-reply", "initial result", json!("end_turn")), ]; write(&initial_rows)?; - let recovered = Claude::open(&place.dir, &place.env()); + let recovered = Claude::open(&place.dir, &place.env())?; assert_eq!( recovered .probe_reply(&session, Some(&initial), "tree-attempt") @@ -2738,7 +2745,7 @@ pub(super) mod tests { #[tokio::test] async fn bot_readback_keeps_the_transcript_root_used_before_config_changed() -> Result<()> { let place = Place::new()?; - let reader = Claude::open(&place.dir, &place.env()); + let reader = Claude::open(&place.dir, &place.env())?; let projects_a = reader.projects().context("initial transcript root")?; let (record, _) = recorder(); let mut config = bot_config(&place, record); @@ -2769,7 +2776,7 @@ pub(super) mod tests { reader.probe_reply(&session, None, "attempt-1").await?, expected ); - let reopened = Claude::open(&place.dir, &place.env()); + let reopened = Claude::open(&place.dir, &place.env())?; assert_eq!(reopened.projects(), Some(projects_a)); assert_eq!( reopened.native_directory(&session).await?.canonicalize()?, @@ -3430,7 +3437,7 @@ pub(super) mod tests { finished.text, format!("initial finished\n\ndone: {}", input.message("work-input")) ); - let recovered = Claude::open(&place.dir.join("node"), &place.env()); + let recovered = Claude::open(&place.dir.join("node"), &place.env())?; let pending = WorkRecord { state: WorkState::Starting { thread: Some(target.thread_id.clone()), diff --git a/apps/core/src/runtime/codex_server.rs b/apps/core/src/runtime/codex_server.rs index e55be4b4f..dfb05f505 100644 --- a/apps/core/src/runtime/codex_server.rs +++ b/apps/core/src/runtime/codex_server.rs @@ -644,29 +644,62 @@ impl Inner { /// epoch and its turns are settled by probes on the new App Server. Only a tree still /// running an App Server on the Node's own endpoint is touched, never the system App Server /// and never a program the recorded identifier was handed to since. - fn kill_orphan(&self) { - let Ok(token) = std::fs::read_to_string(&self.pidfile) else { - return; + fn kill_orphan(&self) -> Result<()> { + let token = match std::fs::read_to_string(&self.pidfile) { + Ok(token) => token, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).context("read the recorded App Server tree"), }; let endpoint = self.spawn_endpoint.to_string(); - match tree::stop_recorded(token.trim(), |member| { + if tree::stop_recorded(token.trim(), |member| { member.contains("app-server") && member.contains(&endpoint) - }) { - Ok(Some(_)) => tracing::info!( + }) + .context("App Server tree exit is unconfirmed; the journal was retained")? + .is_some() + { + tracing::info!( event = "app_server.leftover_stopped", "stopping App Server left by an earlier run" - ), - Ok(None) => {} - Err(error) => tracing::warn!( - event = "app_server.leftover_left_alone", - %error, - "the App Server left by an earlier run was not ended" - ), + ); + } + match std::fs::remove_file(&self.pidfile) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()), + _ => Ok(()), } - let _ = std::fs::remove_file(&self.pidfile); + } + + async fn stop_tree(self: &Arc) -> Result<()> { + let inner = self.clone(); + tokio::task::spawn_blocking(move || { + let mut spawned = inner.tree.lock().expect("tree lock"); + if let Some(tree) = spawned.as_mut() { + tree.stop()?; + } else { + ensure!( + !inner.pidfile.try_exists()?, + "App Server tree exit is unconfirmed; the journal was retained" + ); + } + match std::fs::remove_file(&inner.pidfile) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error.into()); + } + _ => {} + } + *spawned = None; + Ok(()) + }) + .await + .context("join the App Server process-tree shutdown")? } fn spawn(&self, launch: &CodexLaunch) -> Result { + let mut tree = self.tree.lock().expect("tree lock"); + ensure!(!self.stopping(), "the App Server is stopping"); + ensure!( + tree.is_none() && !self.pidfile.try_exists()?, + "the previous App Server tree exit is unconfirmed" + ); let mut command = std::process::Command::new(&launch.bin); command .envs(&launch.env) @@ -692,13 +725,13 @@ impl Inner { )); } config::private_write(&self.pidfile, spawned.token().as_bytes())?; - *self.tree.lock().expect("tree lock") = Some(spawned); + *tree = Some(spawned); Ok(child) } /// Runs the Node's own App Server once. `true` when a new target ended it; its turns are /// settled by probes on the next App Server, as after a crash. - async fn run_spawned(&self, launch: &CodexLaunch) -> bool { + async fn run_spawned(self: &Arc, launch: &CodexLaunch) -> Result { if self .target .lock() @@ -716,7 +749,7 @@ impl Inner { self.set_link(Link::LaunchFailed { reason: "could not reconnect Codex after its configuration changed".into(), }); - return false; + return Ok(false); } } self.point( @@ -732,7 +765,7 @@ impl Inner { self.set_link(Link::LaunchFailed { reason: format!("App Server could not start: {error}"), }); - return false; + return Ok(false); } }; if let Some(auth) = &launch.external_auth { @@ -759,13 +792,13 @@ impl Inner { _=child.wait()=>false, }; if !authenticated { - let tree = self.tree.lock().expect("tree lock").take(); - if let Some(mut tree) = tree { - vibeface_bridge::agent::terminate_process_tree(&mut child, &mut tree).await; - } - let _ = std::fs::remove_file(&self.pidfile); + self.stop_tree().await?; + child + .wait() + .await + .context("reap the unauthenticated App Server")?; self.set_link(Link::LaunchFailed {reason:"Codex external authentication could not be prepared; refresh the source CLI login or sign in for this Node".into()}); - return false; + return Ok(false); } self.point(Some(self.spawn_endpoint.path().to_owned())); } @@ -791,13 +824,9 @@ impl Inner { } } }; - let mut spawned = self.tree.lock().expect("tree lock").take(); + self.stop_tree().await?; let replaced = match status { Some(status) => { - if let Some(spawned) = &mut spawned { - // Tools the App Server started belong to its tree and end with it. - spawned.kill(); - } tracing::warn!(event = "app_server.exited", ?status, "App Server exited"); if !self.stopping() { self.set_link(Link::LaunchFailed { @@ -810,22 +839,18 @@ impl Inner { false } None => { - if let Some(spawned) = &mut spawned { - spawned.ask_to_stop(); - let _ = tokio::time::timeout(Duration::from_secs(3), child.wait()).await; - spawned.kill(); - } let _ = child.wait().await; - tracing::info!( - event = "app_server.restarted", - "App Server restarts with new provider settings" - ); + if !self.stopping() { + tracing::info!( + event = "app_server.restarted", + "App Server restarts with new provider settings" + ); + } true } }; - let _ = std::fs::remove_file(&self.pidfile); self.target.lock().expect("target lock").applied = None; - replaced + Ok(replaced) } async fn use_system(&self, socket: &Path) -> bool { @@ -878,7 +903,18 @@ impl Inner { self.changed.notified().await; true } - CodexTarget::Spawn(launch) => self.run_spawned(launch).await, + CodexTarget::Spawn(launch) => match self.run_spawned(launch).await { + Ok(replaced) => replaced, + Err(error) => { + self.stopping + .store(true, std::sync::atomic::Ordering::SeqCst); + self.point(None); + self.set_link(Link::LaunchFailed { + reason: format!("App Server tree exit is unconfirmed: {error}"), + }); + return; + } + }, CodexTarget::System(socket) => self.use_system(socket).await, }; if replaced || started.elapsed() > Duration::from_secs(60) { @@ -933,7 +969,7 @@ impl CodexServer { tree: std::sync::Mutex::new(None), stopping: std::sync::atomic::AtomicBool::new(false), }; - inner.kill_orphan(); + inner.kill_orphan()?; inner.point(named); Ok(Self { client, @@ -1145,17 +1181,13 @@ impl CodexServer { /// Stops the App Server the Node started; called on SIGTERM before the Node exits. The /// system App Server is never stopped. - pub(crate) async fn stop(&self) { + pub(crate) async fn stop(&self) -> Result<()> { self.inner .stopping .store(true, std::sync::atomic::Ordering::SeqCst); - let spawned = self.inner.tree.lock().expect("tree lock").take(); - if let Some(mut spawned) = spawned { - tokio::task::spawn_blocking(move || spawned.stop()) - .await - .ok(); - } - let _ = std::fs::remove_file(&self.inner.pidfile); + self.inner.changed.notify_one(); + self.inner.point(None); + self.inner.stop_tree().await } } @@ -1413,6 +1445,48 @@ mod tests { #[cfg(unix)] use std::os::unix::fs::PermissionsExt; + #[tokio::test] + async fn unconfirmed_stop_keeps_the_app_server_record_and_blocks_startup() -> Result<()> { + let dir = + std::env::temp_dir().join(format!("vibeface-codex-stop-{}", uuid::Uuid::new_v4())); + config::private_dir(&dir)?; + let identity = LocalIdentity::generate(); + let (events, _) = mpsc::unbounded_channel(); + let server = CodexServer::open(CodexTarget::Off, &identity, &dir, events)?; + let sockets = server + .socket() + .parent() + .context("App Server socket directory")? + .to_owned(); + config::private_write(&server.inner.pidfile, b"invalid-record")?; + assert!(server.stop().await.is_err()); + assert_eq!(std::fs::read(&server.inner.pidfile)?, b"invalid-record"); + let launch = CodexLaunch { + bin: dir.join("missing-fixture"), + env: BTreeMap::new(), + external_auth: None, + }; + assert!( + server + .inner + .spawn(&launch) + .err() + .context("stopped server refuses spawn")? + .to_string() + .contains("stopping") + ); + drop(server); + let (events, _) = mpsc::unbounded_channel(); + assert!(CodexServer::open(CodexTarget::Off, &identity, &dir, events).is_err()); + assert_eq!( + std::fs::read(dir.join("codex-app-server.pid"))?, + b"invalid-record" + ); + std::fs::remove_dir_all(sockets)?; + std::fs::remove_dir_all(dir)?; + Ok(()) + } + #[cfg(unix)] async fn lines(path: &Path, count: usize) -> Vec { for _ in 0..100 { @@ -1697,7 +1771,7 @@ mod tests { .all(|arguments| !arguments.contains("synthetic-")), "credentials never enter program arguments" ); - server.stop().await; + server.stop().await?; fixture.abort(); let _ = fixture.await; std::fs::remove_dir_all(server.socket().parent().unwrap())?; @@ -1738,7 +1812,7 @@ mod tests { server.configuration_pending(&next), server.lease("manager:new-fixture".into(), &next).is_ok(), )); - server.stop().await; + server.stop().await?; std::fs::remove_dir_all(server.socket().parent().unwrap())?; } assert!(!ran.exists()); @@ -1811,7 +1885,7 @@ mod tests { 2, "an unchanged request does not reload again" ); - server.stop().await; + server.stop().await?; std::fs::remove_dir_all(server.socket().parent().unwrap())?; std::fs::remove_dir_all(dir)?; Ok(()) @@ -1906,7 +1980,7 @@ mod tests { 2, "nothing starts while it is off" ); - server.stop().await; + server.stop().await?; std::fs::remove_dir_all(server.socket().parent().unwrap())?; std::fs::remove_dir_all(dir)?; Ok(()) @@ -2021,7 +2095,7 @@ mod tests { server.retarget(CodexTarget::Off); link_becomes(&server, |link| *link == Link::Off).await; - server.stop().await; + server.stop().await?; std::fs::remove_dir_all(server.socket().parent().unwrap())?; assert!( vibeface_bridge::codex::DirectSession::connect(&control) @@ -2066,7 +2140,7 @@ mod tests { candidates: vec![candidate] } ); - server.stop().await; + server.stop().await?; std::fs::remove_dir_all(server.socket().parent().unwrap())?; std::fs::remove_dir_all(sockets)?; std::fs::remove_dir_all(dir)?; diff --git a/apps/core/src/runtime/opencode.rs b/apps/core/src/runtime/opencode.rs index a532191be..82d52d750 100644 --- a/apps/core/src/runtime/opencode.rs +++ b/apps/core/src/runtime/opencode.rs @@ -128,17 +128,27 @@ struct Conn { struct Serve { launch: Launch, - conn: Conn, + conn: Option, child: tokio::process::Child, tree: tree::Tree, pidfile: PathBuf, } impl Serve { - /// Asks the tree to stop, then the drop ends what is left after a grace period. - async fn stop(mut self) { - self.tree.ask_to_stop(); - let _ = tokio::time::timeout(Duration::from_secs(3), self.child.wait()).await; + /// Stops admitting requests, retaining this serve until its tree exit is confirmed. + async fn stop(&mut self) -> Result<()> { + ensure!( + self.conn.take().is_some(), + "the previous opencode tree exit is unconfirmed" + ); + ensure!( + agent::terminate_process_tree(&mut self.child, &mut self.tree).await, + "the opencode process-tree exit is unconfirmed" + ); + match std::fs::remove_file(&self.pidfile) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()), + _ => Ok(()), + } } } @@ -146,32 +156,33 @@ impl Drop for Serve { /// The tools the serve started belong to its tree and end with it. fn drop(&mut self) { self.tree.kill(); - let _ = std::fs::remove_file(&self.pidfile); } } /// A serve an earlier run of the Node left is killed, not adopted: its runs died with that Node /// and probes read them back from the store. Only a tree whose own command line is such a serve /// is touched, so a recorded identifier that now belongs to something else is left alone. -fn kill_orphan(pidfile: &Path) { - let Ok(token) = std::fs::read_to_string(pidfile) else { - return; +fn kill_orphan(pidfile: &Path) -> Result<()> { + let token = match std::fs::read_to_string(pidfile) { + Ok(token) => token, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).context("read the recorded opencode tree"), }; - match tree::stop_recorded(token.trim(), |member| { + if tree::stop_recorded(token.trim(), |member| { member.contains(" serve --hostname 127.0.0.1 --port ") - }) { - Ok(Some(_)) => tracing::info!( + }) + .context("opencode tree exit is unconfirmed; the journal was retained")? + .is_some() + { + tracing::info!( event = "opencode.leftover_stopped", "stopping the opencode serve left by an earlier run" - ), - Ok(None) => {} - Err(error) => tracing::warn!( - event = "opencode.leftover_left_alone", - %error, - "the opencode serve left by an earlier run was not ended" - ), - } - let _ = std::fs::remove_file(pidfile); + ); + } + match std::fs::remove_file(pidfile) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()), + _ => Ok(()), + } } /// A bot turn in progress. @@ -251,7 +262,7 @@ impl Opencode { env: BTreeMap, ) -> Result { let dir = data_dir.join("opencode"); - kill_orphan(&dir.join(PIDFILE)); + kill_orphan(&dir.join(PIDFILE))?; Ok(Self { dir, roots: ProviderRoots::new(data_dir), @@ -342,10 +353,13 @@ impl Opencode { } /// Stops the serve; the Node calls this when it shuts down. - pub(crate) async fn stop(&self) { - if let Some(serve) = self.serve.lock().await.take() { - serve.stop().await; + pub(crate) async fn stop(&self) -> Result<()> { + let mut serve = self.serve.lock().await; + if let Some(running) = serve.as_mut() { + running.stop().await?; } + *serve = None; + Ok(()) } /// The running serve and a use of it. A serve is started first when there is none or it @@ -357,6 +371,10 @@ impl Opencode { async fn conn_for(&self, expected: Option) -> Result<(Conn, Use)> { use std::sync::atomic::Ordering::SeqCst; let mut serve = self.serve.lock().await; + ensure!( + serve.as_ref().is_none_or(|running| running.conn.is_some()), + "the previous opencode tree exit is unconfirmed" + ); let launch = self.launch.lock().expect("launch").current.clone(); if let Some(expected) = &expected { ensure!( @@ -378,14 +396,30 @@ impl Opencode { .is_ok_and(|status| status.is_none()) { self.users.fetch_add(1, SeqCst); - return Ok((running.conn.clone(), Use(self.users.clone()))); + return Ok(( + running + .conn + .as_ref() + .expect("a running serve accepts requests") + .clone(), + Use(self.users.clone()), + )); } - if let Some(old) = serve.take() { - old.stop().await; + if let Some(old) = serve.as_mut() { + old.stop().await?; } + *serve = None; let started = self.spawn(launch).await?; self.users.fetch_add(1, SeqCst); - Ok((serve.insert(started).conn.clone(), Use(self.users.clone()))) + Ok(( + serve + .insert(started) + .conn + .as_ref() + .expect("a started serve accepts requests") + .clone(), + Use(self.users.clone()), + )) } /// The serve running now, never started here. @@ -395,9 +429,14 @@ impl Opencode { (running.child.try_wait()) .is_ok_and(|status| status.is_none()) .then(|| running.conn.clone()) + .flatten() } async fn spawn(&self, launch: Launch) -> Result { + ensure!( + !self.dir.join(PIDFILE).try_exists()?, + "the previous opencode tree exit is unconfirmed" + ); config::private_dir(&self.dir)?; for (name, value) in self.roots.env(Provider::Opencode) { if value == "true" { @@ -414,7 +453,6 @@ impl Opencode { let dir = self.dir.canonicalize()?; let password = crate::crypto::random_hex(32); crate::logging::add_secret(&password); - // ponytail: the port may be taken before the serve binds it; the next use starts again. let port = std::net::TcpListener::bind("127.0.0.1:0")? .local_addr()? .port(); @@ -444,13 +482,10 @@ impl Opencode { .stderr(std::process::Stdio::piped()); let (tree, mut child) = tree::Tree::spawn(command, SERVE_TREE_KEY, true)?; let (stdout, stderr) = (child.stdout.take(), child.stderr.take()); + let started_ms = now_ms(); let mut serve = Serve { launch, - conn: Conn { - base: String::new(), - password, - started_ms: now_ms(), - }, + conn: None, child, pidfile: dir.join(PIDFILE), tree, @@ -480,15 +515,20 @@ impl Opencode { } bail!("the opencode serve exited before it listened") }; - serve.conn.base = tokio::time::timeout(READY_WAIT, listening) + let base = tokio::time::timeout(READY_WAIT, listening) .await .context("the opencode serve did not listen in time")??; // The password goes only to the loopback address the Node asked for. ensure!( - serve.conn.base.starts_with("http://127.0.0.1:"), + base.starts_with("http://127.0.0.1:"), "the opencode serve listens on {}", - serve.conn.base + base ); + serve.conn = Some(Conn { + base, + password, + started_ms, + }); tokio::spawn(async move { while let Ok(Some(line)) = lines.next_line().await { crate::logging::child_line( @@ -974,7 +1014,7 @@ impl Opencode { return Some(false); }; match serve.child.try_wait() { - Ok(None) => serve.conn.clone(), + Ok(None) => serve.conn.clone()?, Ok(Some(_)) => return Some(false), Err(_) => return None, } @@ -2631,6 +2671,93 @@ mod tests { } } + #[tokio::test] + #[cfg(unix)] + async fn hard_killed_serve_is_reaped_before_its_record_is_removed() -> Result<()> { + use std::os::unix::process::ExitStatusExt as _; + + let dir = + std::env::temp_dir().join(format!("vibeface-opencode-kill-{}", uuid::Uuid::new_v4())); + config::private_dir(&dir)?; + let mut command = std::process::Command::new("/bin/sh"); + command + .args(["-c", "trap '' TERM; printf 'ready\\n'; exec /bin/sleep 120"]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + let (tree, mut child) = tree::Tree::spawn(command, "opencode-stop-fixture", true)?; + let token = tree.token().to_owned(); + let stdout = child.stdout.take().context("controlled process stdout")?; + let mut serve = Serve { + launch: Launch { + bin: "/bin/sh".into(), + env: BTreeMap::new(), + }, + conn: Some(Conn { + base: "http://127.0.0.1:9".into(), + password: "fixture".into(), + started_ms: now_ms(), + }), + child, + tree, + pidfile: dir.join(PIDFILE), + }; + config::private_write(&serve.pidfile, token.as_bytes())?; + let mut reader = tokio::io::BufReader::new(stdout); + let mut ready = String::new(); + tokio::time::timeout(READY_WAIT, reader.read_line(&mut ready)).await??; + assert_eq!(ready, "ready\n"); + + serve.stop().await?; + let status = serve + .child + .try_wait()? + .context("the stopped root was reaped")?; + assert_eq!(status.signal(), Some(libc::SIGKILL)); + assert!(!tree::token_is_running(&token)); + assert!(!serve.pidfile.exists()); + std::fs::remove_dir_all(dir)?; + Ok(()) + } + + #[tokio::test] + async fn unconfirmed_stop_blocks_reusing_or_replacing_the_opencode_serve() -> Result<()> { + let place = Place::new().await?; + let server = place.opencode()?; + let (_, using) = server.conn().await?; + drop(using); + let pidfile = server + .serve + .lock() + .await + .as_ref() + .context("running serve")? + .pidfile + .clone(); + let started = place.recorded("argv"); + assert!(!started.is_empty()); + std::fs::remove_file(&pidfile)?; + std::fs::create_dir(&pidfile)?; + assert!(server.stop().await.is_err()); + for _ in 0..2 { + assert!(server.conn().await.is_err()); + } + assert_eq!(place.recorded("argv"), started); + assert!( + pidfile.is_dir(), + "a failed cleanup keeps the original record location" + ); + assert!( + server + .serve + .lock() + .await + .as_ref() + .is_some_and(|serve| serve.conn.is_none()) + ); + Ok(()) + } + fn bot(place: &Place, server: &Arc, client: &str, turns: &Turns) -> ManagerConfig { let turns = turns.clone(); let launch = server.launch.lock().expect("launch").current.clone(); @@ -2864,7 +2991,7 @@ mod tests { } assert_eq!(std::fs::read_dir(&user)?.count(), 0); for server in servers { - server.stop().await; + server.stop().await?; } Ok(()) } @@ -3865,6 +3992,8 @@ mod tests { (server.serve.lock().await.as_mut()) .context("the serve")? .conn + .as_mut() + .context("the serve accepts requests")? .started_ms -= 3 * QUIET_MS; let id = work_message("w-1"); let sent = now_ms() - 2 * QUIET_MS; @@ -3984,7 +4113,7 @@ mod tests { assert!(server.run_ended(&session).await); assert_eq!(server.users.load(std::sync::atomic::Ordering::SeqCst), 0); assert!(!server.configuration_pending(&expected.bin, &expected.env)); - server.stop().await; + server.stop().await?; Ok(()) } @@ -4027,7 +4156,7 @@ mod tests { (running.base, running.started_ms), "an idle serve takes the new launch" ); - server.stop().await; + server.stop().await?; Ok(()) } diff --git a/apps/core/src/runtime/pi.rs b/apps/core/src/runtime/pi.rs index e67276531..8ecc08a5b 100644 --- a/apps/core/src/runtime/pi.rs +++ b/apps/core/src/runtime/pi.rs @@ -142,7 +142,7 @@ struct Launch { struct Process { child: Child, tree: tree::Tree, - _tracked: Tracked, + processes: Arc, rpc: Arc, /// Everything pi writes but the responses. events: mpsc::UnboundedReceiver, @@ -469,15 +469,6 @@ async fn read_output(stdout: ChildStdout, rpc: Arc, events: mpsc::Unbounded *lock(&rpc.waiting) = None; } -/// A pi process tree recorded in the pidfile until its process is done. -struct Tracked(Arc, String); - -impl Drop for Tracked { - fn drop(&mut self) { - self.0.forget(&self.1); - } -} - impl Process { fn spawn( launch: &Launch, @@ -520,7 +511,6 @@ impl Process { processes .track(tree.token(), &launch.bin) .map_err(|error| ExecFailure::new(FailureKind::Unknown, format!("{error:#}")))?; - let tracked = Tracked(processes.clone(), tree.token().to_owned()); let (Some(stdin), Some(stdout), Some(mut stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take()) else { @@ -545,23 +535,25 @@ impl Process { Ok(Self { child, tree, - _tracked: tracked, + processes: processes.clone(), rpc, events, stderr, }) } - /// Ends the process: closing its input shuts pi down, and one that does not exit in time is - /// ended with its tree. Returns the end of its stderr. + /// Closes pi's input, then confirms its whole tree exited before forgetting its record. + /// Returns the end of its stderr. async fn end(mut self) -> String { self.rpc.stdin.lock().await.take(); - let exited = matches!( - tokio::time::timeout(Duration::from_secs(5), self.child.wait()).await, - Ok(Ok(_)) - ); - if !exited { - agent::terminate_process_tree(&mut self.child, &mut self.tree).await; + let _ = tokio::time::timeout(Duration::from_secs(5), self.child.wait()).await; + if agent::terminate_process_tree(&mut self.child, &mut self.tree).await { + self.processes.forget(self.tree.token()); + } else { + tracing::warn!( + event = "pi.tree_exit_unconfirmed", + "pi process-tree exit is unconfirmed; keeping its journal" + ); } match tokio::time::timeout(Duration::from_secs(1), self.stderr).await { Ok(Ok(tail)) => tail, @@ -719,20 +711,20 @@ impl Pi { } /// Ends the pi processes an earlier Node run left, so their turns are read back as they are. - pub(crate) fn new(data_dir: &Path) -> Self { - Self { + pub(crate) fn new(data_dir: &Path) -> Result { + Ok(Self { dir: data_dir.join("pi"), sessions: ProviderRoots::new(data_dir).pi_sessions, - processes: Arc::new(Processes::open(data_dir.join(PIDFILE))), + processes: Arc::new(Processes::open(data_dir.join(PIDFILE))?), live: Default::default(), preparing: Default::default(), resuming: Default::default(), - } + }) } /// Ends every running pi; the Node calls this before it exits. - pub(super) async fn stop(&self) { - self.processes.stop().await; + pub(super) async fn stop(&self) -> Result<()> { + self.processes.stop().await } fn pointer_path(&self, session: &str) -> Result { @@ -2021,6 +2013,135 @@ mod tests { } } + #[tokio::test] + async fn teardown_normal_exit_clears_the_confirmed_tree_record() -> Result<()> { + let dir = scratch("teardown-normal"); + let pi = Pi::new(&dir)?; + let (process, _) = pi + .open( + &launch(&dir, "reply", "s-1"), + "s-1", + &mut watch::channel(false).1, + ) + .await?; + let token = process.tree.token().to_owned(); + assert!(pi.processes.tracked(&token)); + assert!(dir.join(PIDFILE).is_file()); + process.end().await; + assert!(!tree::token_is_running(&token)); + assert!(!pi.processes.tracked(&token)); + assert!(!dir.join(PIDFILE).exists()); + std::fs::remove_dir_all(dir)?; + Ok(()) + } + + #[tokio::test] + async fn teardown_drop_and_cancelled_future_keep_the_record_and_probe_pending() -> Result<()> { + use futures_util::FutureExt as _; + + for cancel_end in [false, true] { + let dir = scratch(if cancel_end { + "teardown-cancel" + } else { + "teardown-drop" + }); + let pi = Pi::new(&dir)?; + let (process, _) = pi + .open( + &launch(&dir, "reply", "s-1"), + "s-1", + &mut watch::channel(false).1, + ) + .await?; + let token = process.tree.token().to_owned(); + let cleanup = tree::Leftover::find(&token)?.context("the owned fixture tree")?; + assert!( + cleanup + .members()? + .iter() + .any(|member| tree::names_program(member, &fake())) + ); + let recorded = std::fs::read(dir.join(PIDFILE))?; + if cancel_end { + let rpc = process.rpc.clone(); + let stdin = rpc.stdin.lock().await; + let mut ending = Box::pin(process.end()); + assert!(ending.as_mut().now_or_never().is_none()); + drop(ending); + drop(stdin); + } else { + drop(process); + } + let retained = pi.processes.tracked(&token); + let journal = std::fs::read(dir.join(PIDFILE)).ok(); + let (mut work, _) = crate::work::accept(spec("w-1", "t", &dir), 0); + crate::work::transition(&mut work, Signal::ThreadCreated("s-1".into())); + let pending = pi.probe(&work).await.is_err(); + if tree::token_is_running(&token) { + cleanup.stop()?; + } + std::fs::remove_dir_all(dir)?; + assert!(retained, "drop is not proof that the whole tree exited"); + assert_eq!(journal.as_deref(), Some(recorded.as_slice())); + assert!(pending, "an unconfirmed tree must not become NotStarted"); + } + Ok(()) + } + + #[tokio::test] + async fn teardown_reaps_children_even_when_the_root_already_exited() -> Result<()> { + use std::os::unix::fs::PermissionsExt as _; + + let dir = scratch("teardown-children"); + let pi = Pi::new(&dir)?; + let bin = dir.join("pi-tree-fixture"); + std::fs::write( + &bin, + "#!/bin/sh\n/bin/sleep 120 >/dev/null 2>&1 &\nprintf '{\"type\":\"fixture_child_ready\"}\\n'\nread ignored\nexit 0\n", + )?; + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o700))?; + let launch = Launch { + bin, + cwd: dir.clone(), + env: BTreeMap::new(), + args: Vec::new(), + }; + let mut process = Process::spawn(&launch, &pi.processes, &pi.sessions) + .map_err(|failure| anyhow::anyhow!("{failure}"))?; + let token = process.tree.token().to_owned(); + let ready = tokio::time::timeout(ANSWER, process.events.recv()) + .await? + .context("the controlled child is running")?; + assert_eq!(ready["type"], "fixture_child_ready"); + let cleanup = tree::Leftover::find(&token)?.context("the owned fixture tree")?; + assert!( + cleanup + .members()? + .iter() + .any(|member| tree::names_program(member, &launch.bin)) + ); + process.rpc.stdin.lock().await.take(); + let status = tokio::time::timeout(ANSWER, process.child.wait()).await??; + assert!(status.success()); + assert!(process.tree.is_running(), "the child outlives the root"); + assert!(pi.processes.tracked(&token)); + process.end().await; + let running = tree::token_is_running(&token); + let tracked = pi.processes.tracked(&token); + let recorded = dir.join(PIDFILE).exists(); + if running { + cleanup.stop()?; + } + std::fs::remove_dir_all(dir)?; + assert!( + !running, + "normal root exit does not prove its children exited" + ); + assert!(!tracked); + assert!(!recorded); + Ok(()) + } + #[tokio::test] async fn two_nodes_force_private_pi_sessions_without_changing_auth_config() -> Result<()> { let dir = scratch("private-sessions"); @@ -2028,7 +2149,7 @@ mod tests { std::fs::create_dir(&user)?; for name in ["node-a", "node-b"] { let data = dir.join(name); - let pi = Arc::new(Pi::new(&data)); + let pi = Arc::new(Pi::new(&data)?); let mut launch = launch(&dir, "reply", name); launch.env.insert( "PI_CODING_AGENT_SESSION_DIR".into(), @@ -2068,7 +2189,7 @@ mod tests { #[tokio::test] async fn bot_readback_uses_its_frozen_input_and_requires_an_ending() -> Result<()> { let dir = scratch("bot-readback"); - let pi = Pi::new(&dir); + let pi = Pi::new(&dir)?; let file = dir.join("session.jsonl"); std::fs::write(&file, "")?; pi.keep("s-1", &file, &dir, "")?; @@ -2136,7 +2257,7 @@ mod tests { #[tokio::test] async fn a_bot_turn_streams_its_reply_and_the_next_turn_goes_on_in_its_session() -> Result<()> { let dir = scratch("bot"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let mut config = bot(&dir, &pi, "reply", None); config.reasoning_effort = Some("high".into()); let shown = std::sync::Mutex::new(Vec::new()); @@ -2207,7 +2328,7 @@ mod tests { #[tokio::test] async fn a_message_steered_into_the_running_reply_is_answered_in_it() -> Result<()> { let dir = scratch("steer"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let turns = Turns::default(); let mut config = bot(&dir, &pi, "wait", Some(&turns)); let native_starts = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -2306,7 +2427,7 @@ mod tests { #[tokio::test] async fn stopping_a_bot_turn_aborts_it_in_pi() -> Result<()> { let dir = scratch("stop"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let turns = Turns::default(); let config = bot(&dir, &pi, "wait", Some(&turns)); let (stop, cancel) = watch::channel(false); @@ -2343,7 +2464,7 @@ mod tests { #[tokio::test] async fn sixteen_pi_turns_overlap_and_keep_their_outputs() -> Result<()> { let dir = scratch("concurrent"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let tasks = concurrent_pi_turns(&dir, &pi, (0..16).map(|_| String::from("reply"))); wait_for_gate(&dir).await?; release(&dir); @@ -2361,7 +2482,7 @@ mod tests { #[tokio::test] async fn cancelling_one_of_sixteen_pi_turns_leaves_the_others_running() -> Result<()> { let dir = scratch("concurrent-cancel"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let mut tasks = Vec::with_capacity(16); let mut stops = Vec::with_capacity(16); for index in 0..16 { @@ -2413,7 +2534,7 @@ mod tests { #[tokio::test] async fn one_failed_pi_turn_does_not_stop_the_other_fifteen() -> Result<()> { let dir = scratch("concurrent-failure"); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let modes = (0..16).map(|index| { if index == 0 { String::from("fail") @@ -2546,7 +2667,7 @@ mod tests { async fn a_cancelled_prompt_never_wins_a_ready_or_queued_stdin_write() -> Result<()> { for queued in [false, true] { let dir = scratch("cancel-before-write"); - let pi = Pi::new(&dir); + let pi = Pi::new(&dir)?; let (stop, mut cancel) = watch::channel(false); let (mut process, after) = pi .open(&launch(&dir, "reply", "s-1"), "s-1", &mut cancel) @@ -2593,7 +2714,7 @@ mod tests { #[tokio::test] async fn cancelling_after_the_prompt_write_keeps_an_unknown_outcome() -> Result<()> { let dir = scratch("cancel-after-write"); - let pi = Pi::new(&dir); + let pi = Pi::new(&dir)?; let (stop, mut cancel) = watch::channel(false); let (mut process, after) = pi .open(&launch(&dir, "prompt-pending", "s-1"), "s-1", &mut cancel) @@ -2861,7 +2982,7 @@ mod tests { let mut recorded = std::fs::read_to_string(&pidfile).unwrap_or_default(); recorded.push_str(&format!("{} {}\n", stranger.id(), fake().display())); std::fs::write(&pidfile, recorded)?; - let restarted = Pi::new(&data); + let restarted = Pi::new(&data)?; assert!(ended(&left).await, "the restart ended the pi it left"); assert!(!pidfile.exists()); assert!( @@ -2902,7 +3023,7 @@ mod tests { #[tokio::test] async fn a_session_without_the_prompt_reads_as_not_started() -> Result<()> { let dir = scratch("unsent"); - let pi = Pi::new(&dir); + let pi = Pi::new(&dir)?; let (mut work, _) = crate::work::accept(spec("w-1", "t", &dir), 0); crate::work::transition(&mut work, Signal::ThreadCreated("s-1".into())); assert_eq!(pi.probe(&work).await?, Probe::NotStarted); @@ -2944,7 +3065,7 @@ mod tests { ("pointer-error", NotStarted, FailureKind::Unknown, 0, 1), ] { let dir = scratch(mode); - let pi = Arc::new(Pi::new(&dir)); + let pi = Arc::new(Pi::new(&dir)?); let mut config = bot(&dir, &pi, mode, None); let previous = match mode { "instructions-error" => { diff --git a/apps/core/src/runtime/provider_probe.rs b/apps/core/src/runtime/provider_probe.rs index 02056638e..e7ffa9d79 100644 --- a/apps/core/src/runtime/provider_probe.rs +++ b/apps/core/src/runtime/provider_probe.rs @@ -807,7 +807,7 @@ mod tests { )); assert!(readiness.can_attempt()); } - node.cursor.get().unwrap().stop().await; + node.cursor.get().unwrap().stop().await?; drop(node); std::fs::remove_dir_all(dir)?; Ok(()) @@ -825,7 +825,7 @@ mod tests { assert!(matches!(probe.launch, LaunchCheck::Failed { .. })); assert_eq!(probe.authentication, Authentication::Unverified); assert_eq!(probe.catalog, ModelCatalog::default()); - node.cursor.get().unwrap().stop().await; + node.cursor.get().unwrap().stop().await?; drop(node); std::fs::remove_dir_all(dir)?; Ok(()) @@ -879,7 +879,7 @@ mod tests { let current = node.provider_probe_snapshot(provider).await; std::fs::write(release, b"ready")?; let returned = pending.await?; - node.cursor.get().unwrap().stop().await; + node.cursor.get().unwrap().stop().await?; drop(node); std::fs::remove_dir_all(dir)?; assert_ne!(first.config_id, current.config_id); diff --git a/apps/mobile/src/features/workspace/workspace.tsx b/apps/mobile/src/features/workspace/workspace.tsx index 3c8ec9767..04d069717 100644 --- a/apps/mobile/src/features/workspace/workspace.tsx +++ b/apps/mobile/src/features/workspace/workspace.tsx @@ -3,7 +3,7 @@ import { Link, Stack, router, useFocusEffect } from 'expo-router' import { BrainCircuit, ChevronDown, ChevronRight, CircleQuestionMark, ListChecks, MessagesSquare, Plus, Reply, Settings, X } from 'lucide-react-native' import { useCallback, useEffect, useRef, useState } from 'react' import { useReducedMotion } from 'react-native-reanimated' -import { Modal, Pressable, ScrollView, View } from 'react-native' +import { Modal, Platform, Pressable, ScrollView, View } from 'react-native' import { KeyboardAvoidingView, KeyboardAwareScrollView, KeyboardController, KeyboardStickyView } from 'react-native-keyboard-controller' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { messageOf } from '@vibeface/client/lib/node.ts' @@ -177,7 +177,8 @@ function InputQueue({ targets }: { targets: InputTarget[] }) { } export function InputOptions({ label, options, selected, onSelect, intent, onIntent, pending }: { label: string; options: TargetOption[]; selected: string; onSelect: (option: TargetOption) => void; intent: InputIntent; onIntent: (intent: InputIntent) => void; pending: PendingMessage[] }) { - const [open, setOpen] = useState(false) + const [phase, setPhase] = useState<'closed' | 'open' | 'closing'>('closed') + const close = () => setPhase(Platform.OS === 'ios' ? 'closing' : 'closed') const shared = useLive() const [scopeContext, setScopeContext] = useState(null) const [contextError, setContextError] = useState('') @@ -187,8 +188,8 @@ export function InputOptions({ label, options, selected, onSelect, intent, onInt const insets = useSafeAreaInsets() const reducedMotion = useReducedMotion() const intents: { value: InputIntent; label: string }[] = [{ value: 'continue', label: '补充当前工作' }, { value: 'new_task', label: '新任务' }, { value: 'defer', label: '稍后处理' }] - return <> item.value === intent)?.label},打开目标和队列`} onPress={() => setOpen(true)} className="min-h-11 flex-row items-center gap-2 rounded-xl bg-muted px-3 py-2">{label}{pending.length ? ` · ${pending.length} 条待确认` : ''} - setOpen(false)}> setOpen(false)} accessibilityRole="button" accessibilityLabel="关闭目标和队列" />目标和队列发送给{options.map((option) => )}发送方式{intents.map((item) => )}发送给{options.map((option) => )}发送方式{intents.map((item) => )}