Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(android): release to Google Play from pull requests, like iOS (#8118)

Peter Chinmanb23021a3687d
diff --git a/.github/workflows/android-play-release.yml b/.github/workflows/android-play-release.yml
new file mode 100644
index 0000000000..93996a0954
--- /dev/null
+++ b/.github/workflows/android-play-release.yml
@@ -0,0 +1,433 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
+name: Android Play Release
+'on':
+ pull_request:
+ types:
+ - labeled
+jobs:
+ release:
+ if: github.event.label.name == 'android-update' && github.event.pull_request.head.repo.full_name == github.repository
+ name: Android Play Release
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: read
+ pull-requests: write
+ checks: read
+ statuses: read
+ id-token: write
+ env:
+ CI: 'true'
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ timeout-minutes: 90
+ steps:
+ - name: Checkout PR head
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: 'false'
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: '1.3.13'
+ - id: preconditions
+ name: Require the PR to be ready to merge
+ run: |
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # here don't persist credentials, so authenticate the way actions/checkout
+ # does. Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # The android-update label means "release this and merge it when it is live",
+ # so refuse to start unless the PR is in a mergeable state: not a draft, the
+ # Android native code actually changed with a version code bump, and every
+ # other check on the head commit passing (pending ones are waited on). Our own
+ # checks are excluded: the native check is expected to be red until the
+ # release is live.
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json isDraft,headRefOid,baseRefOid)
+ if [[ "$(jq -r '.isDraft' <<<"$pr_json")" == "true" ]]; then
+ echo "PR #${PR_NUMBER} is a draft; mark it ready for review before adding android-update." >&2
+ exit 1
+ fi
+ head_sha=$(jq -r '.headRefOid' <<<"$pr_json")
+ base_sha=$(jq -r '.baseRefOid' <<<"$pr_json")
+ if [[ "$head_sha" != "$HEAD_SHA" ]]; then
+ # Pushed since the label event. Web-only commits are fine (they ship over
+ # the air after the merge); native ones would make this build stale.
+ gh_fetch "$head_sha"
+ if [[ "$(bun scripts/android-native.mjs hash "$head_sha")" != "$(bun scripts/android-native.mjs hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER} got Android native changes since this run started (${HEAD_SHA:0:10} → ${head_sha:0:10});" \
+ "re-add android-update on the current head." >&2
+ exit 1
+ fi
+ echo "PR #${PR_NUMBER} moved to ${head_sha:0:10} since this run started, but its Android native code is unchanged; continuing."
+ fi
+
+ # The version code must be bumped against the base, and something native
+ # must actually have changed — there is nothing to release otherwise.
+ gh_fetch "$base_sha"
+ outputs=$(mktemp)
+ GITHUB_OUTPUT="$outputs" bun scripts/android-version-check.mjs "$base_sha"
+ if [[ "$(sed -n 's/^changed=//p' "$outputs")" != "true" ]]; then
+ echo "PR #${PR_NUMBER} has no Android native changes against its base; nothing to release (remove the android-update label)." >&2
+ exit 1
+ fi
+ version_code=$(sed -n 's/^version_code=//p' "$outputs")
+
+ # The gate compares the release stamp with the native hash of the PR's merge
+ # result, not of its head. A head that lacks Android native code main gained
+ # since the PR branched would be released but could never pass the gate — and
+ # a Play release cannot be withdrawn. Refuse before the build instead.
+ merge=$(pr_merge_commit)
+ gh_fetch "$merge"
+ if [[ "$(bun scripts/android-native.mjs hash "$merge")" != "$(bun scripts/android-native.mjs hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER}'s merge result (${merge:0:10}) has Android native code this head lacks: main changed native code since the PR branched." \
+ "Merge main into the PR, bump (cd apps/web && just android-bump), commit, and re-add android-update." >&2
+ exit 1
+ fi
+ echo "version_code=${version_code}" >> "$GITHUB_OUTPUT"
+ echo "Releasing Android version code ${version_code} (native hash matches the merge result ${merge:0:10})."
+
+ # (`gh pr checks` names are job names, not workflow names.)
+ ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check)'
+ deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
+ while true; do
+ checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
+ | jq -c --arg ours "$ours" '[.[] | select(.name | test($ours) | not)]')
+ failing=$(jq -r '[.[] | select(.bucket == "fail" or .bucket == "cancel") | .name] | join(", ")' <<<"$checks")
+ pending=$(jq -r '[.[] | select(.bucket == "pending") | .name] | join(", ")' <<<"$checks")
+ if [[ -n "$failing" ]]; then
+ echo "PR #${PR_NUMBER} has failing checks: ${failing}. Get the PR green, then re-add android-update." >&2
+ exit 1
+ fi
+ if [[ -z "$pending" ]]; then
+ echo "All other checks on ${head_sha:0:10} pass ($(jq 'length' <<<"$checks") checks)."
+ exit 0
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "Checks still pending after ${WAIT_MINUTES} minutes: ${pending}. Re-add android-update once they pass." >&2
+ exit 1
+ fi
+ echo "Waiting for: ${pending}"
+ sleep 60
+ done
+ shell: bash
+ env:
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ WAIT_MINUTES: '30'
+ working-directory: apps/web
+ - name: Install Android SDK components
+ run: |
+ set -euo pipefail
+ export JAVA_HOME="$JAVA_HOME_21_X64"
+ export PATH="$JAVA_HOME/bin:$PATH"
+ "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
+ 'platforms;android-36' 'build-tools;36.0.0' 'ndk;30.0.16248370'
+ echo "JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"
+ echo "NDK_HOME=$ANDROID_HOME/ndk/30.0.16248370" >> "$GITHUB_ENV"
+ shell: bash
+ - name: Setup Nix
+ uses: './.github/actions/setup-nix'
+ - name: Setup prerequisites
+ uses: './.github/actions/setup-reqs-web'
+ - id: metadata
+ name: Prepare version and signing
+ run: |
+ set -euo pipefail
+ filename=$(bun scripts/android-release.ts metadata "vc${VERSION_CODE}" "$RUNNER_TEMP/android-release.json")
+ echo "filename=$filename" >> "$GITHUB_OUTPUT"
+ echo "release_name=$(jq -r .version tauri/src-tauri/tauri.android.conf.json) (${VERSION_CODE})" >> "$GITHUB_OUTPUT"
+ bun scripts/android-release.ts signing "$RUNNER_TEMP/android-signing" \
+ tauri/src-tauri/gen/android/keystore.properties
+ bun scripts/android-firebase.ts build --doppler "$RUNNER_TEMP/android-google-services.json"
+ shell: bash
+ env:
+ VERSION_CODE: ${{ steps.preconditions.outputs.version_code }}
+ DOPPLER_TOKEN: ${{ secrets.ANDROID_RELEASE_DOPPLER_TOKEN }}
+ working-directory: apps/web
+ - name: Build production App Bundle
+ run: |
+ set -euo pipefail
+ # The Nix environment is already loaded. Do not reload it in nested
+ # bash processes and re-enable its local-development sccache wrapper.
+ # This ephemeral runner has no compiler cache/server to reuse.
+ unset BASH_ENV
+ export RUSTC_WRAPPER=""
+ cargo tauri --version
+ # Tauri has shipped both switch-only and value-taking APK/AAB flags.
+ # Nix and local installations can differ; build only the AAB with either CLI.
+ android_help=$(cargo tauri android build --help)
+ artifact_args=(--aab)
+ if [[ "$android_help" == *'--apk <APK>'* ]]; then
+ artifact_args=(--apk false --aab true)
+ fi
+ just android-build --firebase-config "$RUNNER_TEMP/android-google-services.json" \
+ "${artifact_args[@]}" --ci --config "$RUNNER_TEMP/android-release.json" \
+ 2>&1 | tee "$RUNNER_TEMP/android-build.log"
+ shell: bash
+ env:
+ VITE_SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY_PRODUCTION }}
+ VITE_POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
+ VITE_OTEL_EXPORTER_URL: https://macro-prox-prod.macroverse.workers.dev/i/otlp/v1/traces
+ VITE_OTEL_ENV: prod
+ working-directory: apps/web
+ - name: Preserve Android build log
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: android-build-log
+ path: ${{ runner.temp }}/android-build.log
+ if-no-files-found: ignore
+ retention-days: '7'
+ - id: artifact
+ name: Verify and collect App Bundle
+ run: |
+ set -euo pipefail
+ curl --fail --location --retry 3 \
+ https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
+ --output "$RUNNER_TEMP/bundletool.jar"
+ echo "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29 $RUNNER_TEMP/bundletool.jar" | sha256sum --check
+ mapfile -t bundles < <(find tauri/src-tauri/gen/android/app/build/outputs/bundle -type f -name '*-release.aab')
+ if [ "${#bundles[@]}" -ne 1 ]; then
+ echo "Expected exactly one signed release AAB, found ${#bundles[@]}" >&2
+ exit 1
+ fi
+ bun scripts/android-bundle.ts "vc${VERSION_CODE}" "${bundles[0]}" \
+ "$RUNNER_TEMP/bundletool.jar" "$RUNNER_TEMP/android-signing/certificate-sha256"
+ bundle_filename="${RELEASE_FILENAME%.*}.aab"
+ mkdir -p "$GITHUB_WORKSPACE/android-artifacts"
+ cp "${bundles[0]}" "$GITHUB_WORKSPACE/android-artifacts/$bundle_filename"
+ # R8 mapping belongs to this exact binary; preserve it for Play crash reports.
+ bundle_variant=$(basename "$(dirname "${bundles[0]}")")
+ mapping="tauri/src-tauri/gen/android/app/build/outputs/mapping/$bundle_variant/mapping.txt"
+ if [[ ! -s "$mapping" ]]; then
+ echo "Missing R8 mapping for bundle variant $bundle_variant" >&2
+ exit 1
+ fi
+ mapping_filename="${bundle_filename%.aab}-mapping.txt"
+ cp "$mapping" "$GITHUB_WORKSPACE/android-artifacts/$mapping_filename"
+ \cd "$GITHUB_WORKSPACE/android-artifacts"
+ sha256sum "$bundle_filename" > "$bundle_filename.sha256"
+ sha256sum "$mapping_filename" > "$mapping_filename.sha256"
+ echo "bundle=$GITHUB_WORKSPACE/android-artifacts/$bundle_filename" >> "$GITHUB_OUTPUT"
+ echo "mapping=$GITHUB_WORKSPACE/android-artifacts/$mapping_filename" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ VERSION_CODE: ${{ steps.preconditions.outputs.version_code }}
+ RELEASE_FILENAME: ${{ steps.metadata.outputs.filename }}
+ working-directory: apps/web
+ - name: Require the PR's Android native code to be unchanged since the build
+ run: |
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # here don't persist credentials, so authenticate the way actions/checkout
+ # does. Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # Last check before uploading: the bundle must still describe the native code
+ # the merge gate will hash — that of the PR's merge result — or it could never
+ # pass the gate, and a promoted Play release cannot be withdrawn. Two things
+ # can move while a build runs: the PR head (a native push; the drift workflow
+ # cancels runs after the fact, but better not to upload at all) and main
+ # (another Android PR merged).
+ built=$(bun scripts/android-native.mjs hash HEAD)
+ head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
+ if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
+ echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
+ else
+ gh_fetch "$head_sha"
+ current=$(bun scripts/android-native.mjs hash "$head_sha")
+ if [[ "$current" != "$built" ]]; then
+ echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(${built:0:10} → ${current:0:10}). Not uploading the stale bundle." >&2
+ echo "Re-add the android-update label to release the current head." >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
+ fi
+ merge=$(pr_merge_commit)
+ gh_fetch "$merge"
+ merged=$(bun scripts/android-native.mjs hash "$merge")
+ if [[ "$merged" != "$built" ]]; then
+ echo "Android native code landed on main while this release was building: the merge result" \
+ "(${merge:0:10}) hashes ${merged:0:10}, the bundle ${built:0:10}. Not uploading a bundle the merge gate could never accept." >&2
+ echo "Merge main into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
+ exit 1
+ fi
+ echo "Merge result ${merge:0:10} matches the built native code (${built:0:10}); uploading."
+ shell: bash
+ working-directory: apps/web
+ - name: Write the provenance stamp as release notes
+ run: |
+ set -euo pipefail
+ hash=$(bun scripts/android-native.mjs hash HEAD)
+ mkdir -p "$RUNNER_TEMP/whatsnew"
+ printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
+ echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
+ shell: bash
+ working-directory: apps/web
+ - name: Upload verified Android artifact
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: android-release
+ path: android-artifacts/
+ if-no-files-found: error
+ retention-days: '90'
+ - id: auth
+ name: Authenticate to Google Play
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ export_environment_variables: 'false'
+ - name: Upload to internal testing
+ uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5
+ with:
+ serviceAccountJson: ${{ steps.auth.outputs.credentials_file_path }}
+ packageName: com.macro.workspace.mobile
+ releaseFiles: ${{ steps.artifact.outputs.bundle }}
+ mappingFile: ${{ steps.artifact.outputs.mapping }}
+ releaseName: ${{ steps.metadata.outputs.release_name }}
+ track: internal
+ status: completed
+ whatsNewDirectory: ${{ runner.temp }}/whatsnew
+ - name: Promote to production
+ run: |
+ set -euo pipefail
+ for attempt in 1 2 3 4 5; do
+ if node scripts/android-play-promote.mjs; then
+ exit 0
+ fi
+ echo "Promotion attempt ${attempt} failed; retrying in 30s."
+ sleep 30
+ done
+ echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
+ exit 1
+ shell: bash
+ env:
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
+ VERSION_CODE: ${{ steps.preconditions.outputs.version_code }}
+ CHANGES_NOT_SENT_FOR_REVIEW: 'false'
+ working-directory: apps/web
+ - name: Remove signing material
+ if: always()
+ run: |
+ rm -rf "$RUNNER_TEMP/android-signing" "$RUNNER_TEMP/android-release.json" \
+ "$RUNNER_TEMP/android-google-services.json" "$RUNNER_TEMP/whatsnew" || true
+ rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties || true
+ shell: bash
+ - name: Comment on the PR
+ if: success() || failure()
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ const versionCode = '${{ steps.preconditions.outputs.version_code }}' || '?';
+ const releaseName = '${{ steps.metadata.outputs.release_name }}' || `version code ${versionCode}`;
+ const runUrl =
+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
+ `/actions/runs/${context.runId}`;
+ const success = '${{ job.status }}' === 'success';
+ const body = success
+ ? [
+ `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout.`,
+ '',
+ 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
+ 're-runs the **Android Native Check** on this PR within half an hour of that, and the PR',
+ 'becomes mergeable. To merge it the moment that happens, click **Enable auto-merge** on this PR now (squash).',
+ 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
+ '',
+ `[Workflow run](${runUrl})`,
+ ].join('\n')
+ : [
+ `🤖 Android Play release for ${releaseName} **failed** — see the [workflow run](${runUrl}).`,
+ '',
+ 'Fix the problem, then remove and re-add the `android-update` label to retry.',
+ ].join('\n');
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ body,
+ });
+concurrency:
+ group: android-play-release-${{ github.event.pull_request.number }}
diff --git a/.github/workflows/android-release-drift.yml b/.github/workflows/android-release-drift.yml
new file mode 100644
index 0000000000..39bec2a633
--- /dev/null
+++ b/.github/workflows/android-release-drift.yml
@@ -0,0 +1,151 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
+name: Android Release Drift
+'on':
+ pull_request:
+ types:
+ - synchronize
+jobs:
+ drift:
+ if: contains(github.event.pull_request.labels.*.name, 'android-update') && github.event.pull_request.head.repo.full_name == github.repository
+ name: Android Release Drift
+ runs-on: namespace-profile-linux-tiny-no-cache
+ permissions:
+ actions: write
+ contents: read
+ pull-requests: write
+ id-token: write
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: '1.3.13'
+ - id: detect
+ name: Detect Android native changes in this push
+ run: |
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # here don't persist credentials, so authenticate the way actions/checkout
+ # does. Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # A push landed on a PR that carries android-update. Compare the Android native
+ # code before and after the push. Only native changes matter — web-only
+ # commits ship over the air after the merge. A force-push that discarded the
+ # old head counts as changed: nothing proves the released bundle still matches.
+ if gh_fetch "$BEFORE_SHA" && before=$(bun scripts/android-native.mjs hash "$BEFORE_SHA"); then :; else
+ before=unknown
+ fi
+ gh_fetch "$AFTER_SHA"
+ after=$(bun scripts/android-native.mjs hash "$AFTER_SHA")
+ echo "native hash before: ${before}"
+ echo "native hash after: ${after}"
+ if [[ "$before" == "$after" ]]; then
+ echo "changed=false" >> "$GITHUB_OUTPUT"
+ echo "No Android native changes in this push; the release stays valid."
+ else
+ echo "changed=true" >> "$GITHUB_OUTPUT"
+ # The version code that may already be on Play is the old head's. After a
+ # force-push the old head is gone; the new head's code is the best guess (a
+ # push rarely changes it), and it keeps the Play check running — that
+ # check is what tells the author a stale bundle is already in production.
+ if [[ "$before" != unknown ]]; then
+ released=$BEFORE_SHA
+ else
+ released=$AFTER_SHA
+ echo "The previous head is unreachable (force-push); checking Play for the current head's version code instead."
+ fi
+ echo "version_code=$(bun scripts/android-native.mjs version-code "$released")" >> "$GITHUB_OUTPUT"
+ echo "Android native code changed; the released bundle is stale."
+ fi
+ shell: bash
+ env:
+ BEFORE_SHA: ${{ github.event.before }}
+ AFTER_SHA: ${{ github.event.after }}
+ working-directory: apps/web
+ - name: Cancel in-progress release runs for this PR
+ if: steps.detect.outputs.changed == 'true'
+ run: |
+ set -euo pipefail
+ runs=$(gh run list --repo "$GH_REPO" --workflow android-play-release.yml \
+ --branch "$HEAD_REF" --json databaseId,status \
+ --jq '.[] | select(.status == "queued" or .status == "in_progress" or .status == "waiting") | .databaseId')
+ if [[ -z "$runs" ]]; then
+ echo "No release run in progress."
+ exit 0
+ fi
+ for run_id in $runs; do
+ echo "Cancelling release run ${run_id} (it would upload a bundle of the old head)."
+ gh run cancel "$run_id" --repo "$GH_REPO" || true
+ done
+ deadline=$(( $(date +%s) + 180 ))
+ for run_id in $runs; do
+ while [[ "$(gh run view "$run_id" --repo "$GH_REPO" --json status --jq .status)" != "completed" ]]; do
+ if (( $(date +%s) > deadline )); then
+ echo "::warning::Release run ${run_id} is still not completed."
+ break
+ fi
+ sleep 10
+ done
+ done
+ shell: bash
+ env:
+ HEAD_REF: ${{ github.event.pull_request.head.ref }}
+ - id: auth
+ name: Authenticate to Google Play
+ if: steps.detect.outputs.changed == 'true' && steps.detect.outputs.version_code != ''
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ create_credentials_file: 'false'
+ export_environment_variables: 'false'
+ - id: status
+ name: Check whether the stale version code is already on Play
+ if: steps.detect.outputs.changed == 'true' && steps.detect.outputs.version_code != ''
+ run: |
+ set -euo pipefail
+ bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" || true
+ shell: bash
+ env:
+ VERSION_CODE: ${{ steps.detect.outputs.version_code }}
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
+ working-directory: apps/web
+ - name: Remove the android-update label
+ if: always() && steps.detect.outputs.changed == 'true'
+ run: gh pr edit "$PR_NUMBER" --repo "$GH_REPO" --remove-label android-update
+ shell: bash
+ - name: Comment on the PR
+ if: always() && steps.detect.outputs.changed == 'true'
+ run: |
+ set -euo pipefail
+ bump='cd apps/web && just android-bump'
+ if [[ "$PROMOTED" == "true" ]]; then
+ body="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."
+ else
+ body="🤖 Android native code changed after this PR's Play release started, so the release was stopped: any in-progress build was cancelled and the \`android-update\` label removed. If a bundle already reached the internal track it stays there (internal testers only). When the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
+ fi
+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"
+ shell: bash
+ env:
+ PROMOTED: ${{ steps.status.outputs.promoted }}
+ VERSION_CODE: ${{ steps.detect.outputs.version_code }}
diff --git a/.github/workflows/android-release-watch.yml b/.github/workflows/android-release-watch.yml
new file mode 100644
index 0000000000..a3cf2f49ca
--- /dev/null
+++ b/.github/workflows/android-release-watch.yml
@@ -0,0 +1,165 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
+name: Android Release Watch
+'on':
+ schedule:
+ - cron: '*/30 * * * *'
+ workflow_dispatch: {}
+permissions:
+ actions: write
+ contents: read
+ pull-requests: write
+ id-token: write
+jobs:
+ watch:
+ name: Re-run the Android Native Check once the Play release is live
+ runs-on: namespace-profile-linux-tiny-no-cache
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ timeout-minutes: 15
+ steps:
+ - id: prs
+ name: Find PRs waiting on a Play release
+ run: |
+ set -euo pipefail
+ prs=$(gh pr list --repo "$GH_REPO" --label android-update --state open \
+ --json number,headRefOid,potentialMergeCommit \
+ --jq 'map({number, sha: .headRefOid, merge: .potentialMergeCommit.oid})' | jq -c .)
+ count=$(jq 'length' <<<"$prs")
+ echo "Open PRs labeled android-update: ${count}"
+ echo "prs=${prs}" >> "$GITHUB_OUTPUT"
+ echo "count=${count}" >> "$GITHUB_OUTPUT"
+ shell: bash
+ - name: Checkout
+ if: steps.prs.outputs.count != '0'
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - name: Setup Bun
+ if: steps.prs.outputs.count != '0'
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: '1.3.13'
+ - id: auth
+ name: Authenticate to Google Play
+ if: steps.prs.outputs.count != '0'
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ create_credentials_file: 'false'
+ export_environment_variables: 'false'
+ - name: Re-run the check on PRs whose release is live
+ if: steps.prs.outputs.count != '0'
+ run: |
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # here don't persist credentials, so authenticate the way actions/checkout
+ # does. Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ set -euo pipefail
+ # For each open PR labeled `android-update` (PRS: [{number, sha, merge}]), ask
+ # Google Play whether the version code committed at the PR head is live on
+ # production, built from the Android native code of the PR's merge result
+ # (`merge` is GitHub's test merge commit; the gate hashes the same). When it
+ # is, and the PR's latest `Android Native Check` job (of the web app PR checks
+ # run) failed — it fails until the release is live — re-run that job so the
+ # gate, and the `Web App Status Check` that depends on it, go green without
+ # anyone clicking "Re-run". GH_TOKEN needs actions:write + pull-requests:write;
+ # GOOGLE_PLAY_ACCESS_TOKEN the androidpublisher scope.
+ cd apps/web
+ conf_path="apps/web/tauri/src-tauri/tauri.android.conf.json"
+
+ check_pr() {
+ local pr=$1 number sha merge native_hash version_code run run_id status run_url job conclusion job_id reruns
+ number=$(jq -r '.number' <<<"$pr")
+ sha=$(jq -r '.sha' <<<"$pr")
+ merge=$(jq -r '.merge // empty' <<<"$pr")
+ if [[ -z "$merge" ]]; then
+ echo "PR #${number}: no merge commit (conflicts with main?); cannot check the merge result"
+ return 0
+ fi
+ version_code=$(gh api "repos/${GH_REPO}/contents/${conf_path}?ref=${sha}" --jq '.content' | base64 --decode | jq -r '.bundle.android.versionCode')
+ gh_fetch "$merge"
+ native_hash=$(bun scripts/android-native.mjs hash "$merge")
+ echo "PR #${number}: Android version code ${version_code} at ${sha:0:10}, merge-result native hash ${native_hash:0:10}"
+
+ if ! bun scripts/android-play-status.mjs --version-code "$version_code" --require-live \
+ --native-hash "$native_hash" --pr "$number" >"$RUNNER_TEMP/status-${number}.log" 2>&1; then
+ echo " not live yet:"
+ sed 's/^/ /' "$RUNNER_TEMP/status-${number}.log"
+ return 0
+ fi
+ echo " live on Google Play production"
+
+ run=$(gh run list --workflow web-app-check-main.yml --commit "$sha" \
+ --json databaseId,status,url --limit 1 --jq '.[0] // empty')
+ if [[ -z "$run" ]]; then
+ echo " no Web App Pr Checks run for this commit; skipping"
+ return 0
+ fi
+ run_id=$(jq -r '.databaseId' <<<"$run")
+ status=$(jq -r '.status' <<<"$run")
+ run_url=$(jq -r '.url' <<<"$run")
+ if [[ "$status" != "completed" ]]; then
+ echo " Web App Pr Checks run ${run_id} is ${status}; skipping"
+ return 0
+ fi
+ job=$(gh run view "$run_id" --json jobs \
+ --jq '.jobs[] | select(.name == "Android Native Check") | {id: .databaseId, conclusion}')
+ if [[ -z "$job" ]]; then
+ echo " run ${run_id} has no Android Native Check job; skipping"
+ return 0
+ fi
+ job_id=$(jq -r '.id' <<<"$job")
+ conclusion=$(jq -r '.conclusion' <<<"$job")
+ if [[ "$conclusion" == "success" ]]; then
+ echo " Android Native Check already passed"
+ return 0
+ fi
+ if [[ "$conclusion" != "failure" ]]; then
+ echo " Android Native Check job concluded ${conclusion}; leaving it alone"
+ return 0
+ fi
+ # If our re-run also fails something else is wrong (the job's log says
+ # what), so stop after two rather than retrying every half hour forever.
+ reruns=$(gh pr view "$number" --json comments --jq \
+ "[.comments[].body | select(contains(\"Re-ran the **Android Native Check**\")) | select(contains(\"version code ${version_code}\"))] | length")
+ if (( reruns >= 2 )); then
+ echo " Android Native Check already re-run ${reruns} times and still failing; not re-running again — see ${run_url}"
+ return 0
+ fi
+ echo " re-running Android Native Check (job ${job_id} of run ${run_id}; ${reruns} automatic re-runs so far)"
+ gh run rerun --job "$job_id"
+ gh pr comment "$number" --body "🤖 Android version code ${version_code} is live on Google Play. Re-ran the **Android Native Check** ([run](${run_url})); this PR can merge once it passes."
+ }
+
+ # One PR's API hiccup must not stop the others from being checked this
+ # half hour: each PR runs in its own errexit subshell.
+ failed=0
+ while read -r pr; do
+ set +e
+ ( set -e; check_pr "$pr" )
+ rc=$?
+ set -e
+ if (( rc != 0 )); then
+ echo " error while checking PR $(jq -r '.number' <<<"$pr") (exit ${rc}); continuing"
+ failed=1
+ fi
+ done < <(jq -c '.[]' <<<"$PRS")
+ exit $failed
+ shell: bash
+ env:
+ PRS: ${{ steps.prs.outputs.prs }}
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
diff --git a/.github/workflows/ios-app-store-release.yml b/.github/workflows/ios-app-store-release.yml
index 14ae40f00c..401e62f3be 100644
--- a/.github/workflows/ios-app-store-release.yml
+++ b/.github/workflows/ios-app-store-release.yml
@@ -93,6 +93,36 @@ jobs:
fetch -q --depth=1 origin "$1"
}
# ----------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
# The ios-update label means "release this and merge it when Apple approves",
# so refuse to start unless the PR is in a mergeable state: not a draft, and
@@ -118,10 +148,22 @@ jobs:
echo "PR #${PR_NUMBER} moved to ${head_sha:0:10} since this run started, but its native code is unchanged; continuing."
fi
+ # The gate compares the build's stamp with the native tree of the PR's merge
+ # result, not of its head. A head that lacks iOS native code main gained since
+ # the PR branched would go through App Review but could never pass the gate.
+ merge=$(pr_merge_commit)
+ native_tree_fetch "$merge"
+ if [[ "$(native_tree_hash "$merge")" != "$(native_tree_hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER}'s merge result (${merge:0:10}) has iOS native code this head lacks: main changed native code since the PR branched." \
+ "Merge main into the PR, bump (doppler run --project ios-release --config prd -- just ios-bump), commit, and re-add ios-update." >&2
+ exit 1
+ fi
+ echo "Native tree matches the merge result ${merge:0:10}."
+
# Web App Status Check aggregates the gate, so it is red whenever the gate is;
# its other inputs (Typecheck, Test, Build, ...) are separate checks and stay.
# (`gh pr checks` names are job names, not workflow names.)
- ours='^(iOS Native Check|Re-run the iOS Native Check|Web App Status Check|iOS App Store Release|iOS Release Drift)'
+ ours='^(iOS Native Check|Re-run the native check|Web App Status Check|iOS App Store Release|iOS Release Drift|Android Native Check)'
deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
while true; do
checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
@@ -348,30 +390,70 @@ jobs:
fetch -q --depth=1 origin "$1"
}
# ----------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
- # Last check before submitting for review: native code pushed to the PR while
- # this run was building would make the uploaded build stale. The drift
- # workflow withdraws submissions after the fact, but better not to submit at
- # all. Compares the native tree of the PR's current head with the tree that
- # was built (this checkout is the head the run started from).
+ # Last check before submitting for review: the uploaded build must still
+ # describe the native tree the merge gate will hash — that of the PR's merge
+ # result — or it could never pass the gate. Two things can move while a build
+ # runs: the PR head (a native push; the drift workflow withdraws submissions
+ # after the fact, but better not to submit at all) and main (another iOS PR
+ # merged). This checkout is the head the run started from.
built_tree=$(native_tree_hash HEAD)
built=$(jq -r '.bundle.iOS.bundleVersion' apps/web/tauri/src-tauri/tauri.ios.conf.json)
+ bump='doppler run --project ios-release --config prd -- just ios-bump'
head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
echo "PR head unchanged (${head_sha:0:10}); native tree ${built_tree:0:10} is current."
- exit 0
+ else
+ native_tree_fetch "$head_sha"
+ head_tree=$(native_tree_hash "$head_sha")
+ if [[ "$head_tree" != "$built_tree" ]]; then
+ echo "Native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(tree ${built_tree:0:10} → ${head_tree:0:10}). Not submitting the stale build ${built}." >&2
+ echo "Bump (${bump}), commit, and re-add the ios-update label to release the current head." >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its native tree is still ${built_tree:0:10}."
fi
- native_tree_fetch "$head_sha"
- head_tree=$(native_tree_hash "$head_sha")
- if [[ "$head_tree" == "$built_tree" ]]; then
- echo "PR head moved to ${head_sha:0:10} but its native tree is still ${built_tree:0:10}; submitting."
- exit 0
+ merge=$(pr_merge_commit)
+ native_tree_fetch "$merge"
+ merged_tree=$(native_tree_hash "$merge")
+ if [[ "$merged_tree" != "$built_tree" ]]; then
+ echo "iOS native code landed on main while this release was building: the merge result" \
+ "(${merge:0:10}) hashes ${merged_tree:0:10}, build ${built} ${built_tree:0:10}. Not submitting a build the merge gate could never accept." >&2
+ echo "Merge main into the PR, bump (${bump}), commit, and re-add the ios-update label." >&2
+ exit 1
fi
- echo "Native code changed on PR #${PR_NUMBER} while this release was building" \
- "(tree ${built_tree:0:10} → ${head_tree:0:10}). Not submitting the stale build ${built}." >&2
- echo "Bump (doppler run --project ios-release --config prd -- just ios-bump), commit," \
- "and re-add the ios-update label to release the current head." >&2
- exit 1
+ echo "Merge result ${merge:0:10} matches the built native tree (${built_tree:0:10}); submitting."
shell: bash
- name: Submit for App Review
run: |-
diff --git a/.github/workflows/ios-native-check-label.yml b/.github/workflows/native-check-label.yml
similarity index 69%
rename from .github/workflows/ios-native-check-label.yml
rename to .github/workflows/native-check-label.yml
index ed2e3606b2..9216960a1d 100644
--- a/.github/workflows/ios-native-check-label.yml
+++ b/.github/workflows/native-check-label.yml
@@ -1,6 +1,6 @@
# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
-# Source: tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rs
-name: iOS Native Check Label
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/native_check_label.rs
+name: Native Check Label
'on':
pull_request:
types:
@@ -10,8 +10,8 @@ name: iOS Native Check Label
- main
jobs:
rerun:
- if: github.event.label.name == 'skip-ios-update' && github.event.pull_request.head.repo.full_name == github.repository
- name: Re-run the iOS Native Check
+ if: (github.event.label.name == 'skip-ios-update' || github.event.label.name == 'skip-android-update') && github.event.pull_request.head.repo.full_name == github.repository
+ name: Re-run the native check
runs-on: namespace-profile-linux-tiny-no-cache
permissions:
actions: write
@@ -21,16 +21,16 @@ jobs:
GH_REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_NUMBER: ${{ github.event.pull_request.number }}
+ JOB_NAME: ${{ github.event.label.name == 'skip-ios-update' && 'iOS Native Check' || 'Android Native Check' }}
timeout-minutes: 30
steps:
- name: Re-run the gate job for this head
run: |
set -euo pipefail
- # Re-run the `iOS Native Check` job of the web app PR checks run for
- # $HEAD_SHA (waiting for that run to finish first: a run in progress saw the
- # labels as they were when it started). GitHub re-runs the dependent
- # `Web App Status Check` with it.
- # A push after the label event starts a fresh run that reads the labels
+ # Re-run the $JOB_NAME job of the web app PR checks run for $HEAD_SHA (waiting
+ # for that run to finish first: a run in progress saw the labels as they were
+ # when it started). GitHub re-runs the dependent `Web App Status Check` with
+ # it. A push after the label event starts a fresh run that reads the labels
# itself, and would also have cancelled this head's run (the web suite
# cancels in-progress runs per PR): nothing to re-run then.
current=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
@@ -56,18 +56,18 @@ jobs:
break
fi
if (( $(date +%s) > deadline )); then
- echo "Run ${run_id} is still ${status}; giving up. Re-run the iOS Native Check job by hand." >&2
+ echo "Run ${run_id} is still ${status}; giving up. Re-run the ${JOB_NAME} job by hand." >&2
exit 1
fi
echo "Run ${run_id} is ${status}; waiting for it to finish before re-running the gate."
sleep 30
done
job_id=$(gh run view "$run_id" --repo "$GH_REPO" --json jobs \
- --jq '.jobs[] | select(.name == "iOS Native Check") | .databaseId')
+ --jq ".jobs[] | select(.name == \"${JOB_NAME}\") | .databaseId")
if [[ -z "$job_id" ]]; then
- echo "Run ${run_id} has no iOS Native Check job; nothing to re-run."
+ echo "Run ${run_id} has no ${JOB_NAME} job; nothing to re-run."
exit 0
fi
- echo "Re-running iOS Native Check (job ${job_id} of run ${run_id}) with the current labels."
+ echo "Re-running ${JOB_NAME} (job ${job_id} of run ${run_id}) with the current labels."
gh run rerun --repo "$GH_REPO" --job "$job_id"
shell: bash
diff --git a/.github/workflows/release-android.yml b/.github/workflows/release-android.yml
deleted file mode 100644
index 1fc8203891..0000000000
--- a/.github/workflows/release-android.yml
+++ /dev/null
@@ -1,230 +0,0 @@
-name: Release Android App Bundle
-
-on:
- workflow_dispatch:
- inputs:
- release_tag:
- description: Published production release to build (vYYYY.M.D or vYYYY.M.D.N)
- required: true
- type: string
- operation:
- description: Release after deployment, or force a recovery build without uploading to Play
- type: choice
- default: rebuild
- options:
- - rebuild
- - release
- publish_android:
- description: Recovery builds only — attach verified artifacts to the existing release
- default: false
- type: boolean
-
-# Android builds have their own cancellation lifecycle and never hold the
-# production deployment lock. Serialize them so release detection sees the
-# artifacts published by the preceding Android build.
-concurrency:
- group: android-native-release
- cancel-in-progress: false
-
-env:
- MODE: "production"
-
-jobs:
- android-changes:
- name: Check for native Android changes
- if: github.ref == 'refs/heads/main'
- runs-on: ubuntu-24.04
- permissions:
- contents: read
- timeout-minutes: 10
- env:
- RELEASE_TAG: ${{ inputs.release_tag }}
- outputs:
- build: ${{ steps.changes.outputs.build || steps.recovery.outputs.build }}
- steps:
- - name: Validate published release
- env:
- GH_TOKEN: ${{ github.token }}
- shell: bash
- run: |
- set -euo pipefail
- [[ "$RELEASE_TAG" =~ ^v20[0-9]{2}\.[0-9]{1,2}\.[0-9]{1,2}(\.[0-9]{1,2})?$ ]]
- gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json isDraft,isPrerelease \
- | jq -e '.isDraft == false and .isPrerelease == false'
- - name: Allow explicit recovery build
- id: recovery
- if: inputs.operation == 'rebuild'
- run: echo 'build=true' >> "$GITHUB_OUTPUT"
- - name: Checkout release history
- if: inputs.operation == 'release'
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
- with:
- ref: ${{ format('refs/tags/{0}', inputs.release_tag) }}
- fetch-depth: 0
- persist-credentials: false
- - name: Compare Tauri with last published Android bundle
- id: changes
- if: inputs.operation == 'release'
- env:
- GH_TOKEN: ${{ github.token }}
- run: node apps/web/scripts/android-release-needed.mjs
-
- build-android:
- name: Build signed Android App Bundle
- needs: [android-changes]
- if: needs.android-changes.outputs.build == 'true'
- runs-on: ubuntu-24.04
- permissions:
- contents: read
- timeout-minutes: 90
- env:
- CI: "true"
- RELEASE_TAG: ${{ inputs.release_tag }}
- steps:
- - name: Checkout release
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
- with:
- ref: ${{ format('refs/tags/{0}', inputs.release_tag) }}
- persist-credentials: false
- - name: Install Android SDK components
- shell: bash
- run: |
- set -euo pipefail
- export JAVA_HOME="$JAVA_HOME_21_X64"
- export PATH="$JAVA_HOME/bin:$PATH"
- "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
- 'platforms;android-36' 'build-tools;36.0.0' 'ndk;30.0.16248370'
- echo "JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"
- echo "NDK_HOME=$ANDROID_HOME/ndk/30.0.16248370" >> "$GITHUB_ENV"
- - name: Setup Nix
- uses: ./.github/actions/setup-nix
- - name: Setup prerequisites
- uses: ./.github/actions/setup-reqs-web
- - name: Prepare version and signing
- id: metadata
- working-directory: apps/web
- env:
- DOPPLER_TOKEN: ${{ secrets.ANDROID_RELEASE_DOPPLER_TOKEN }}
- run: |
- set -euo pipefail
- filename=$(bun scripts/android-release.ts metadata "$RELEASE_TAG" "$RUNNER_TEMP/android-release.json")
- echo "filename=$filename" >> "$GITHUB_OUTPUT"
- bun scripts/android-release.ts signing "$RUNNER_TEMP/android-signing" \
- tauri/src-tauri/gen/android/keystore.properties
- bun scripts/android-firebase.ts build --doppler "$RUNNER_TEMP/android-google-services.json"
- - name: Build production App Bundle
- working-directory: apps/web
- env:
- VITE_SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY_PRODUCTION }}
- VITE_POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
- VITE_OTEL_EXPORTER_URL: https://macro-prox-prod.macroverse.workers.dev/i/otlp/v1/traces
- VITE_OTEL_ENV: prod
- run: |
- set -euo pipefail
- # The Nix environment is already loaded. Do not reload it in nested
- # bash processes and re-enable its local-development sccache wrapper.
- # This ephemeral runner has no compiler cache/server to reuse.
- unset BASH_ENV
- export RUSTC_WRAPPER=""
- cargo tauri --version
- # Tauri has shipped both switch-only and value-taking APK/AAB flags.
- # Nix and local installations can differ; build only the AAB with either CLI.
- android_help=$(cargo tauri android build --help)
- artifact_args=(--aab)
- if [[ "$android_help" == *'--apk <APK>'* ]]; then
- artifact_args=(--apk false --aab true)
- fi
- just android-build --firebase-config "$RUNNER_TEMP/android-google-services.json" \
- "${artifact_args[@]}" --ci --config "$RUNNER_TEMP/android-release.json" \
- 2>&1 | tee "$RUNNER_TEMP/android-build.log"
- - name: Preserve Android build log
- if: always()
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
- with:
- name: android-build-log
- path: ${{ runner.temp }}/android-build.log
- if-no-files-found: warn
- retention-days: 7
- - name: Verify and collect App Bundle
- working-directory: apps/web
- env:
- RELEASE_FILENAME: ${{ steps.metadata.outputs.filename }}
- run: |
- set -euo pipefail
- curl --fail --location --retry 3 \
- https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
- --output "$RUNNER_TEMP/bundletool.jar"
- echo "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29 $RUNNER_TEMP/bundletool.jar" | sha256sum --check
- mapfile -t bundles < <(find tauri/src-tauri/gen/android/app/build/outputs/bundle -type f -name '*-release.aab')
- if [ "${#bundles[@]}" -ne 1 ]; then
- echo "Expected exactly one signed release AAB, found ${#bundles[@]}" >&2
- exit 1
- fi
- bun scripts/android-bundle.ts "$RELEASE_TAG" "${bundles[0]}" \
- "$RUNNER_TEMP/bundletool.jar" "$RUNNER_TEMP/android-signing/certificate-sha256"
- # Recovery builds can check out older tags whose metadata names an APK.
- bundle_filename="${RELEASE_FILENAME%.*}.aab"
- mkdir -p "$GITHUB_WORKSPACE/android-artifacts"
- cp "${bundles[0]}" "$GITHUB_WORKSPACE/android-artifacts/$bundle_filename"
- # R8 mapping belongs to this exact binary; preserve it for Play crash reports.
- bundle_variant=$(basename "$(dirname "${bundles[0]}")")
- mapping="tauri/src-tauri/gen/android/app/build/outputs/mapping/$bundle_variant/mapping.txt"
- if [[ ! -s "$mapping" ]]; then
- echo "Missing R8 mapping for bundle variant $bundle_variant" >&2
- exit 1
- fi
- mapping_filename="${bundle_filename%.aab}-mapping.txt"
- cp "$mapping" "$GITHUB_WORKSPACE/android-artifacts/$mapping_filename"
- \cd "$GITHUB_WORKSPACE/android-artifacts"
- sha256sum "$bundle_filename" > "$bundle_filename.sha256"
- sha256sum "$mapping_filename" > "$mapping_filename.sha256"
- - name: Upload verified Android artifact
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
- with:
- name: android-release
- path: android-artifacts/*
- if-no-files-found: error
- retention-days: 30
- - name: Remove signing material
- if: always()
- run: |
- rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties \
- apps/web/tauri/src-tauri/gen/android/app/google-services.json \
- "$RUNNER_TEMP/android-google-services.json"
- rm -rf "$RUNNER_TEMP/android-signing"
- # This hosted runner has no separate /nix cache mount to detach. The cache
- # teardown action's fuser -km /nix can kill the runner on its root filesystem.
-
- upload-android:
- name: Publish Android release artifact
- needs: [build-android]
- if: inputs.operation == 'release' || inputs.publish_android
- runs-on: ubuntu-24.04
- timeout-minutes: 30
- permissions:
- contents: write
- actions: write
- steps:
- - name: Download verified Android artifact
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
- with:
- name: android-release
- path: android-artifacts
- - name: Attach Android artifacts and checksums to release
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65
- with:
- tag_name: ${{ inputs.release_tag }}
- files: android-artifacts/*
- fail_on_unmatched_files: true
- - name: Release to Google Play internal testers
- if: inputs.operation == 'release'
- env:
- GH_TOKEN: ${{ github.token }}
- RELEASE_TAG: ${{ inputs.release_tag }}
- run: |
- set -euo pipefail
- # Dispatch from main to retain the existing restricted Google OIDC identity.
- gh workflow run publish-android-play.yml --repo "$GITHUB_REPOSITORY" --ref main \
- -f operation=upload-internal -f release_tag="$RELEASE_TAG" -f status=completed
- printf 'Queued Google Play internal testing upload for `%s`. Check the Publish Android to Google Play workflow for its result.\n' \
- "$RELEASE_TAG" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.yml
index 4244b58312..4c10e95061 100644
--- a/.github/workflows/release-production.yml
+++ b/.github/workflows/release-production.yml
@@ -11,28 +11,6 @@ env:
MODE: "production"
jobs:
- release-android:
- name: Queue Android release
- needs: [deploy, deploy-sync-service, deploy-ai-editing-worker]
- runs-on: ubuntu-24.04
- timeout-minutes: 5
- permissions:
- contents: read
- actions: write
- steps:
- - name: Dispatch independent Android workflow
- env:
- GH_TOKEN: ${{ github.token }}
- RELEASE_TAG: ${{ github.event.release.tag_name }}
- run: |
- set -euo pipefail
- # Do not wait for the native build: it must not hold this workflow's
- # production concurrency lock or delay cancellation of this run.
- gh workflow run release-android.yml --repo "$GITHUB_REPOSITORY" --ref main \
- -f operation=release -f release_tag="$RELEASE_TAG"
- printf 'Queued Android release for `%s`. Check the Release Android App Bundle workflow for build and publishing results.\n' \
- "$RELEASE_TAG" >> "$GITHUB_STEP_SUMMARY"
-
deploy-cloud-storage:
if: github.event_name == 'release'
name: Deploy Cloud Storage Services
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 68ba23ce43..8327524d75 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -62,11 +62,13 @@ jobs:
- 'packages/sdk/**'
- 'apps/docs/**'
- '.github/actions/setup-reqs-web/**'
- android-version:
- name: Android Version Code
+ android-native-check:
+ name: Android Native Check
runs-on: namespace-profile-linux-tiny-no-cache
permissions:
contents: read
+ pull-requests: read
+ id-token: write
steps:
- name: Checkout PR merge commit
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
@@ -74,15 +76,107 @@ jobs:
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
with:
bun-version: '1.3.13'
- - name: Require an Android version bump for native changes
+ - id: android-version
+ name: Require an Android version bump for native changes
+ run: |
+ set -euo pipefail
+ base=$(git cat-file -p HEAD | sed -n 's/^parent //p' | head -1)
+ echo "Comparing the merge result with its base ${base:0:10}"
+ git fetch -q --depth=1 origin "$base"
+ bun scripts/android-version-check.mjs "$base"
+ shell: bash
+ working-directory: apps/web
+ - id: labels
+ name: Read the PR's current labels
+ if: steps.android-version.outputs.changed == 'true'
+ run: |
+ set -euo pipefail
+ labels=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json labels --jq '[.labels[].name] | join(",")')
+ echo "labels: ${labels:-<none>}"
+ if [[ ",${labels}," == *",skip-android-update,"* ]]; then
+ echo "skip=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "skip=false" >> "$GITHUB_OUTPUT"
+ fi
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ - id: auth
+ name: Authenticate to Google Play
+ if: steps.android-version.outputs.changed == 'true' && steps.labels.outputs.skip != 'true'
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ create_credentials_file: 'false'
+ export_environment_variables: 'false'
+ - name: Require the Play release to be live
+ if: steps.android-version.outputs.changed == 'true' && steps.labels.outputs.skip != 'true'
run: |
+ # --- authenticated fetch ------------------------------------------------------
+ # gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+ # commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+ # here don't persist credentials, so authenticate the way actions/checkout
+ # does. Fails if the commit is unreachable (a force-pushed-away head).
+ gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+ }
+ # ------------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
- git fetch -q --depth=1 origin "$BASE_SHA"
- bun scripts/android-version-check.mjs "$BASE_SHA"
+ merge=$(pr_merge_commit)
+ gh_fetch "$merge"
+ native_hash=$(bun scripts/android-native.mjs hash "$merge")
+ echo "Merge result ${merge:0:10}: Android native hash ${native_hash}"
+ bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" --require-live \
+ --native-hash "$native_hash" --pr "$PR_NUMBER"
shell: bash
env:
- BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ VERSION_CODE: ${{ steps.android-version.outputs.version_code }}
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
working-directory: apps/web
+ - name: Skipped via label
+ if: steps.android-version.outputs.changed == 'true' && steps.labels.outputs.skip == 'true'
+ run: echo "Android native changes detected, but the skip-android-update label says they don't break the native/web contract — skipping the Play release gate."
typescript:
needs:
- path-check
@@ -430,10 +524,15 @@ jobs:
set -euo pipefail
manifest=crates/client/cache-wasm/Cargo.toml
version() { git show "$1:$manifest" 2>/dev/null | sed -n 's/^version *= *"\([^"]*\)".*/\1/p' | head -1 | grep . || echo none; }
- git fetch -q --depth=1 origin "$BASE_BRANCH"
- base=$(version "origin/$BASE_BRANCH")
+ # The merge commit's first parent is the main this merge result was
+ # built on; a fresh fetch of main could be newer and misattribute
+ # its bumps to the PR.
+ base_sha=$(git cat-file -p HEAD | sed -n 's/^parent //p' | head -1)
+ git fetch -q --depth=1 origin "$base_sha"
+ echo "base_sha=${base_sha}" >> "$GITHUB_OUTPUT"
+ base=$(version "$base_sha")
head=$(version HEAD)
- echo "cache-wasm version: base ${base}, merge result ${head}"
+ echo "cache-wasm version: base ${base} (${base_sha:0:10}), merge result ${head}"
if [[ "$base" != "$head" ]]; then
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "The client cache wasm version moved; the native app compiles that cache, so this counts as a native change."
@@ -441,8 +540,6 @@ jobs:
echo "bumped=false" >> "$GITHUB_OUTPUT"
fi
shell: bash
- env:
- BASE_BRANCH: ${{ github.base_ref }}
- id: labels
name: Read the PR's current labels
if: (steps.native-filter.outputs.ios_native == 'true' || steps.cache-wasm.outputs.bumped == 'true')
@@ -467,14 +564,9 @@ jobs:
bun-version: '1.3.13'
- name: Verify iOS release numbers were bumped
if: (steps.native-filter.outputs.ios_native == 'true' || steps.cache-wasm.outputs.bumped == 'true') && steps.labels.outputs.skip != 'true'
- run: |
- set -euo pipefail
- git fetch --depth=1 origin "$BASE_BRANCH"
- bun scripts/ios-verify-native-bump.mjs
- shell: bash
+ run: bun scripts/ios-verify-native-bump.mjs
env:
- BASE_BRANCH: ${{ github.base_ref }}
- BASE_REF: origin/${{ github.base_ref }}
+ BASE_REF: ${{ steps.cache-wasm.outputs.base_sha }}
working-directory: apps/web
- name: Fetch App Store Connect credentials from Doppler
if: (steps.native-filter.outputs.ios_native == 'true' || steps.cache-wasm.outputs.bumped == 'true') && steps.labels.outputs.skip != 'true'
@@ -596,28 +688,40 @@ jobs:
fetch -q --depth=1 origin "$1"
}
# ----------------------------------------------------------------------------
+ # --- PR merge result ----------------------------------------------------------
+ # pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+ # the merge result the native gates hash. GitHub computes it lazily
+ # (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+ # conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+ # PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+ pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+ }
+ # ------------------------------------------------------------------------------
set -euo pipefail
# The gate proper: the committed version + build must be live, built from the
- # native code of the PR's current merge result. GitHub computes that merge
- # commit lazily (mergeable=UNKNOWN until it has), so poll for it a little; a
- # PR that really conflicts with main cannot merge anyway.
- deadline=$(( $(date +%s) + 120 ))
- while true; do
- pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
- mergeable=$(jq -r '.mergeable' <<<"$pr_json")
- merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
- [[ -n "$merge" ]] && break
- if [[ "$mergeable" == "CONFLICTING" ]]; then
- echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
- exit 1
- fi
- if (( $(date +%s) > deadline )); then
- echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); re-run this job in a minute." >&2
- exit 1
- fi
- echo "Merge commit not computed yet (mergeable=${mergeable}); waiting."
- sleep 10
- done
+ # native code of the PR's current merge result.
+ merge=$(pr_merge_commit)
native_tree_fetch "$merge"
native_tree=$(native_tree_hash "$merge")
echo "Merge result ${merge:0:10}: native tree ${native_tree}"
@@ -634,7 +738,7 @@ jobs:
status-check:
needs:
- path-check
- - android-version
+ - android-native-check
- typescript
- generated-code
- biome-check
@@ -649,7 +753,7 @@ jobs:
- name: Check job results
run: |
echo "path-check: ${{ needs.path-check.result }}"
- echo "android-version: ${{ needs.android-version.result }}"
+ echo "android-native-check: ${{ needs.android-native-check.result }}"
echo "typescript: ${{ needs.typescript.result }}"
echo "generated-code: ${{ needs.generated-code.result }}"
echo "biome-check: ${{ needs.biome-check.result }}"
@@ -660,7 +764,7 @@ jobs:
# Fail if any job failed (skipped and success are both OK). The iOS
# gate is the merge gate, so a cancelled gate is not OK either.
- if [[ "${{ needs.android-version.result }}" != "success" ]] || \
+ if [[ "${{ needs.android-native-check.result }}" != "success" ]] || \
[[ "${{ needs.path-check.result }}" == "failure" ]] || \
[[ "${{ needs.typescript.result }}" == "failure" ]] || \
[[ "${{ needs.generated-code.result }}" == "failure" ]] || \
diff --git a/CLAUDE.md b/CLAUDE.md
index c6f21ae369..3750073193 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -55,6 +55,7 @@ Real files live in `.agents/`; tool-specific directories only symlink to it.
| SQLx queries, migrations, DB tests, or cache errors | [Database development](docs/development/database.md) |
| Web frontend | [Web agent guide](apps/web/AGENTS.md) |
| iOS App Store releases, breaking Tauri changes, native build floors | [iOS releases](apps/web/docs/ios-releases.md) |
+| Android Play releases from pull requests | [Android development](docs/development/android.md) |
| Email body rendering or snapshots | [Standalone renderer](packages/email-renderer/README.md) |
| Running the frontend or backend on a local machine | [Running locally](docs/development/running-locally.md) |
| Giving the user a local preview link | `local-preview` skill |
diff --git a/apps/web/docs/ios-releases.md b/apps/web/docs/ios-releases.md
index a2f7d80659..96b8462196 100644
--- a/apps/web/docs/ios-releases.md
+++ b/apps/web/docs/ios-releases.md
@@ -1,5 +1,8 @@
# iOS releases and breaking Tauri changes
+(The Android counterpart — `android-update`, `Android Native Check`, Google
+Play as the source of truth — is described in `docs/development/android.md`.)
+
Web bundles ship to installed apps over the air (see
`tauri/macro_bundle_updater_plugin`), but native code — anything under
`apps/web/tauri/` — only reaches users through the App Store. A bundle that
@@ -109,9 +112,8 @@ Two things:
bumps when a cache change must ship: a PR that moves it (compared with
the base branch on the merge ref) is a native PR, and the version is part
of the provenance hash, so a build is only "live" for the version it was
- built with. The Android release workflow applies the same rule when it
- decides whether a production release needs a new App Bundle
- (`scripts/android-release-needed.mjs`).
+ built with. The Android gate and release apply the same rule through
+ `scripts/android-native.mjs`.
The hash recipe is defined once, in `scripts/ios_native_tree.sh` next to the
workflow sources, mirrored in `ios-app-store.mjs`; the gate's change
@@ -131,6 +133,12 @@ code" is defined above. The checks:
a hand release — fails with "re-bump". The PR's own earlier upload (same
version, same stamp) is a retry: the release skips the build and goes
straight to submit.
+- **Up-to-date check** (release workflow, before building and again before
+ submitting): the head's native tree must equal that of the PR's merge
+ result. A head that lacks native code `main` gained since it branched
+ would go through App Review but could never pass the gate; the release
+ refuses instead, and the fix is to merge `main`, bump, and re-add the
+ label.
- **Live check** (the gate): the live build's stamp must equal the native
tree of the PR's **current merge result** (fetched through the API, so a
re-run of the job evaluates today's `main`, not the one the run started
@@ -174,7 +182,8 @@ release only starts on a PR that is ready to merge. Pushes afterwards:
PR is caught by the watcher instead, within half an hour: it compares the
in-flight build's stamp with the head's native code and does the same
withdrawal. The release itself also refuses to
- submit if the native tree moved while it was building. To continue: bump
+ submit if the native tree moved while it was building, on the PR or on
+ `main`. To continue: bump
(the marketing version stays, the build number moves), commit, push, and
re-add the label; `submit` takes the withdrawn version record over, so no
App Store Connect visit is needed. If Apple had already approved the stale
diff --git a/apps/web/scripts/android-native.mjs b/apps/web/scripts/android-native.mjs
index 76fbfecc49..bdcb2234d1 100644
--- a/apps/web/scripts/android-native.mjs
+++ b/apps/web/scripts/android-native.mjs
@@ -1,7 +1,8 @@
-// What "the Android native code" is, shared by the PR-time version check
-// (android-version-check.mjs) and the release-time build decision
-// (android-release-needed.mjs) so the two can never disagree: a PR that
-// passes the gate must not fail the release for the same question.
+// What "the Android native code" is, shared by the PR gate
+// (android-version-check.mjs), the Play release workflow's preconditions,
+// head guard and provenance stamp, the drift check and the watcher (all
+// through the `hash` CLI below) so they can never disagree about whether a
+// change is native.
//
// It is every tracked file under apps/web/tauri except what never reaches
// the Android binary — iOS, macOS, Linux, Windows and desktop-only paths by
@@ -15,6 +16,8 @@
// image, excluding Android-only paths instead.
import { execFileSync } from 'node:child_process';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
export const tauriPath = 'apps/web/tauri';
export const cacheWasmManifest = 'crates/client/cache-wasm/Cargo.toml';
@@ -93,3 +96,23 @@ export function androidVersionCode(git, commit) {
throw new Error(`Invalid Android versionCode at ${commit}`);
return code;
}
+
+// CLI for the workflows' shell steps:
+// bun scripts/android-native.mjs hash [commit] the native hash
+// bun scripts/android-native.mjs version-code [commit] the versionCode
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
+) {
+ try {
+ const [command, commit = 'HEAD'] = process.argv.slice(2);
+ const git = gitIn(process.cwd());
+ const resolved = git(['rev-parse', '--verify', '--end-of-options', `${commit}^{commit}`]);
+ if (command === 'hash') console.log(androidNativeHash(git, resolved));
+ else if (command === 'version-code') console.log(androidVersionCode(git, resolved));
+ else throw new Error('Usage: android-native.mjs hash|version-code [commit]');
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : 'android-native failed');
+ process.exitCode = 1;
+ }
+}
diff --git a/apps/web/scripts/android-play-status.mjs b/apps/web/scripts/android-play-status.mjs
new file mode 100644
index 0000000000..789c460bb2
--- /dev/null
+++ b/apps/web/scripts/android-play-status.mjs
@@ -0,0 +1,202 @@
+// Google Play as the source of truth for "is this Android build live": the
+// counterpart of `ios-app-store.mjs status` for the App Store.
+//
+// bun scripts/android-play-status.mjs --version-code N [--require-live]
+// [--native-hash H] [--pr N]
+//
+// Reads the production (and internal) track through a throwaway edit, plus
+// the production release list, and reports where version code N is. With
+// --require-live it exits non-zero unless N is a production release that
+// Google has published — the edit's `status: completed` only says the rollout
+// is full; the release list's `releaseLifecycleState` says whether it passed
+// review and is available to users — whose release notes carry the
+// provenance stamp written by the release workflow ("native tree <hash> for
+// PR #<n>") matching --native-hash / --pr when given: the same check the iOS
+// gate makes against the TestFlight "What to Test" text. Needs
+// GOOGLE_PLAY_ACCESS_TOKEN (androidpublisher scope).
+import { appendFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const packageName = 'com.macro.workspace.mobile';
+const api = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}`;
+export const consoleUrl =
+ 'https://play.google.com/console/developers/app/com.macro.workspace.mobile/tracks/production';
+
+export const STAMP_RE = /native tree ([0-9a-f]{40})/;
+export const STAMP_PR_RE = /for PR #(\d+)/;
+export const PUBLISHED = 'RELEASE_LIFECYCLE_STATE_PUBLISHED';
+
+/// The provenance text the release workflow puts in the Play release notes.
+export function stamp(nativeHash, pr) {
+ return `native tree ${nativeHash} for PR #${pr}`;
+}
+
+function releasesOf(track) {
+ const releases = track?.releases;
+ return Array.isArray(releases) ? releases : [];
+}
+
+/// Where a version code stands: `production`/`internal` are the edit's track
+/// payloads (rollout status, release notes), `summaries` the production
+/// release list (review lifecycle).
+export function versionCodeStatus(production, internal, versionCode, summaries) {
+ const code = String(versionCode);
+ const find = (track) =>
+ releasesOf(track).find((release) =>
+ (release.versionCodes ?? []).map(String).includes(code)
+ );
+ const promoted = find(production);
+ const testing = find(internal);
+ const summary = releasesOf(summaries).find((release) =>
+ (release.activeArtifacts ?? []).some((artifact) => String(artifact?.versionCode) === code)
+ );
+ const lifecycle = summary?.releaseLifecycleState ?? null;
+ const notes = (release) =>
+ (release?.releaseNotes ?? []).map((note) => note.text ?? '').join('\n');
+ const stampOf = (release) => {
+ const text = notes(release);
+ return {
+ tree: text.match(STAMP_RE)?.[1] ?? null,
+ pr: text.match(STAMP_PR_RE)?.[1] ?? null,
+ };
+ };
+ return {
+ versionCode: code,
+ promoted: promoted !== undefined,
+ live: promoted?.status === 'completed' && lifecycle === PUBLISHED,
+ productionStatus: promoted?.status ?? null,
+ lifecycle,
+ internalStatus: testing?.status ?? null,
+ stamp: promoted ? stampOf(promoted) : testing ? stampOf(testing) : null,
+ };
+}
+
+function notLiveProblem(status) {
+ const code = `version code ${status.versionCode}`;
+ if (!status.productionStatus) {
+ return status.internalStatus
+ ? `${code} is only on the internal track (status ${status.internalStatus}); it has not been promoted to production`
+ : `${code} is on neither the production nor the internal track`;
+ }
+ if (status.productionStatus !== 'completed') {
+ return `${code} is on the production track with status ${status.productionStatus}, not completed (a staged rollout or a halted release?)`;
+ }
+ switch (status.lifecycle) {
+ case 'RELEASE_LIFECYCLE_STATE_IN_REVIEW':
+ return `${code} is on the production track but still in Google Play review`;
+ case 'RELEASE_LIFECYCLE_STATE_APPROVED_NOT_PUBLISHED':
+ return `${code} passed Google Play review but has not been published (managed publishing? publish it in Play Console)`;
+ case 'RELEASE_LIFECYCLE_STATE_NOT_APPROVED':
+ return `${code} was rejected by Google Play review; resolve the policy issue in Play Console, then bump and release again`;
+ default:
+ return `${code} is on the production track (status completed) but its review state is ${status.lifecycle ?? 'unknown: it is missing from the production release list'}`;
+ }
+}
+
+/// Why a status fails --require-live, or null when it passes.
+export function liveProblem(status, { nativeHash, pr } = {}) {
+ if (!status.live) return notLiveProblem(status);
+ if (nativeHash && status.stamp?.tree !== nativeHash) {
+ return `version code ${status.versionCode} is live, but was built from native tree ${status.stamp?.tree ?? 'unknown (no provenance stamp)'}, not ${nativeHash}: native code changed after that build (pushed to the PR, or landed on main since)`;
+ }
+ if (pr && status.stamp?.pr !== String(pr)) {
+ return `version code ${status.versionCode} is live, but was released for PR #${status.stamp?.pr ?? 'unknown'}, not #${pr}`;
+ }
+ return null;
+}
+
+/// Read the production release list and both tracks through a throwaway edit
+/// (always discarded).
+export async function readTracks({ token, request = fetch }) {
+ if (!token) throw new Error('Missing Google Play access token');
+ async function call(method, path, body = undefined) {
+ const response = await request(`${api}${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ signal: AbortSignal.timeout(60_000),
+ });
+ if (!response.ok)
+ throw new Error(`Google Play ${method} ${path} failed (HTTP ${response.status})`);
+ return response.status === 204 ? undefined : response.json();
+ }
+ const summaries = await call('GET', '/tracks/production/releases');
+ const edit = await call('POST', '/edits', {});
+ if (typeof edit?.id !== 'string' || !edit.id)
+ throw new Error('Google Play did not return an edit ID');
+ const editPath = `/edits/${encodeURIComponent(edit.id)}`;
+ try {
+ const production = await call('GET', `${editPath}/tracks/production`);
+ const internal = await call('GET', `${editPath}/tracks/internal`);
+ return { production, internal, summaries };
+ } finally {
+ try {
+ await call('DELETE', editPath);
+ } catch {
+ // A leftover read-only edit expires on its own.
+ }
+ }
+}
+
+function parseArgs(argv) {
+ const args = {};
+ for (let i = 0; i < argv.length; i += 1) {
+ const flag = argv[i];
+ if (!flag.startsWith('--')) throw new Error(`Unexpected argument ${flag}`);
+ const name = flag.slice(2);
+ if (name === 'require-live') args[name] = true;
+ else args[name] = argv[++i];
+ }
+ return args;
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
+) {
+ try {
+ const args = parseArgs(process.argv.slice(2));
+ if (!/^[1-9][0-9]{0,9}$/.test(args['version-code'] ?? ''))
+ throw new Error('--version-code must be a positive integer');
+ const { production, internal, summaries } = await readTracks({
+ token: process.env.GOOGLE_PLAY_ACCESS_TOKEN,
+ });
+ const status = versionCodeStatus(production, internal, args['version-code'], summaries);
+ console.log(
+ `Version code ${status.versionCode}: production ${status.productionStatus ?? 'absent'}` +
+ (status.lifecycle ? ` (${status.lifecycle})` : '') +
+ `, internal ${status.internalStatus ?? 'absent'}` +
+ (status.stamp?.tree ? `, built from native tree ${status.stamp.tree} for PR #${status.stamp.pr ?? '?'}` : '')
+ );
+ if (process.env.GITHUB_OUTPUT)
+ await appendFile(
+ process.env.GITHUB_OUTPUT,
+ `live=${status.live}\npromoted=${status.promoted}\n`
+ );
+ if (args['require-live']) {
+ const problem = liveProblem(status, { nativeHash: args['native-hash'], pr: args.pr });
+ if (problem) {
+ console.error(`Android native changes require version code ${status.versionCode} to be live on Google Play before merging, but ${problem}.
+ - Not started yet? Add the \`android-update\` label to the PR to build, upload
+ and promote it.
+ - Promoted? Wait for Google review; the \`Android Release Watch\` workflow
+ re-runs this check within half an hour of the release.
+ - Native code changed since the release? Bump (\`just android-bump\`), commit,
+ re-add \`android-update\`.
+ - If the native change doesn't break the native/web contract, add the
+ \`skip-android-update\` label instead.
+${consoleUrl}`);
+ process.exitCode = 1;
+ } else {
+ console.log(`Version code ${status.versionCode} is live on Google Play production.`);
+ }
+ }
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : 'Google Play status check failed');
+ process.exitCode = 1;
+ }
+}
diff --git a/apps/web/scripts/android-play-status.test.ts b/apps/web/scripts/android-play-status.test.ts
new file mode 100644
index 0000000000..d6de070acc
--- /dev/null
+++ b/apps/web/scripts/android-play-status.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ liveProblem,
+ PUBLISHED,
+ readTracks,
+ stamp,
+ versionCodeStatus,
+} from './android-play-status.mjs';
+
+const hash = 'a'.repeat(40);
+const live = {
+ status: 'completed',
+ versionCodes: ['3'],
+ releaseNotes: [{ language: 'en-US', text: stamp(hash, 42) }],
+};
+const production = { track: 'production', releases: [live] };
+const internal = {
+ track: 'internal',
+ releases: [{ status: 'completed', versionCodes: ['4'], releaseNotes: [{ language: 'en-US', text: stamp('b'.repeat(40), 43) }] }],
+};
+const published = {
+ releases: [
+ { releaseName: '2', track: 'production', activeArtifacts: [{ versionCode: 2 }], releaseLifecycleState: PUBLISHED },
+ { releaseName: '3', track: 'production', activeArtifacts: [{ versionCode: 3 }], releaseLifecycleState: PUBLISHED },
+ ],
+};
+const withLifecycle = (state) => ({
+ releases: [{ releaseName: '3', track: 'production', activeArtifacts: [{ versionCode: 3 }], releaseLifecycleState: state }],
+});
+
+describe('versionCodeStatus', () => {
+ it('reads the published production release and its provenance stamp', () => {
+ expect(versionCodeStatus(production, internal, 3, published)).toEqual({
+ versionCode: '3',
+ promoted: true,
+ live: true,
+ productionStatus: 'completed',
+ lifecycle: PUBLISHED,
+ internalStatus: null,
+ stamp: { tree: hash, pr: '42' },
+ });
+ });
+
+ it('reports a version that is only in internal testing', () => {
+ const status = versionCodeStatus(production, internal, '4', published);
+ expect(status.live).toBe(false);
+ expect(status.promoted).toBe(false);
+ expect(status.internalStatus).toBe('completed');
+ expect(liveProblem(status)).toMatch(/only on the internal track/);
+ });
+
+ it('reports an unknown version', () => {
+ expect(liveProblem(versionCodeStatus(production, internal, '9', published))).toMatch(/neither/);
+ expect(liveProblem(versionCodeStatus({ track: 'production' }, undefined, '9', undefined))).toMatch(/neither/);
+ });
+
+ it('treats a non-completed production release as not live', () => {
+ const staged = { track: 'production', releases: [{ ...live, status: 'inProgress' }] };
+ const status = versionCodeStatus(staged, internal, '3', published);
+ expect(status.promoted).toBe(true);
+ expect(liveProblem(status)).toMatch(/inProgress/);
+ });
+
+ it('is promoted but not live until Google publishes the release', () => {
+ const cases: Array<[string, RegExp]> = [
+ ['RELEASE_LIFECYCLE_STATE_IN_REVIEW', /still in Google Play review/],
+ ['RELEASE_LIFECYCLE_STATE_APPROVED_NOT_PUBLISHED', /not been published/],
+ ['RELEASE_LIFECYCLE_STATE_NOT_APPROVED', /rejected/],
+ ['RELEASE_LIFECYCLE_STATE_DRAFT', /review state is RELEASE_LIFECYCLE_STATE_DRAFT/],
+ ];
+ for (const [state, message] of cases) {
+ const status = versionCodeStatus(production, internal, '3', withLifecycle(state));
+ expect(status.promoted).toBe(true);
+ expect(status.live).toBe(false);
+ expect(status.lifecycle).toBe(state);
+ expect(liveProblem(status, { nativeHash: hash })).toMatch(message);
+ }
+ });
+
+ it('fails closed when the release list does not know the version code', () => {
+ const status = versionCodeStatus(production, internal, '3', { releases: [] });
+ expect(status.live).toBe(false);
+ expect(liveProblem(status)).toMatch(/missing from the production release list/);
+ });
+});
+
+describe('liveProblem', () => {
+ const status = versionCodeStatus(production, internal, '3', published);
+ it('passes when the stamp matches', () => {
+ expect(liveProblem(status, { nativeHash: hash, pr: 42 })).toBeNull();
+ expect(liveProblem(status)).toBeNull();
+ });
+ it('fails on a different native tree or PR', () => {
+ expect(liveProblem(status, { nativeHash: 'c'.repeat(40) })).toMatch(/native code changed/);
+ expect(liveProblem(status, { pr: 7 })).toMatch(/released for PR #42, not #7/);
+ });
+ it('names a missing stamp', () => {
+ const unstamped = { track: 'production', releases: [{ status: 'completed', versionCodes: ['3'] }] };
+ expect(liveProblem(versionCodeStatus(unstamped, internal, '3', published), { nativeHash: hash })).toMatch(/no provenance stamp/);
+ });
+});
+
+describe('readTracks', () => {
+ it('lists production releases, then reads both tracks through a discarded edit', async () => {
+ const calls: string[] = [];
+ const request = vi.fn(async (url: string, init: RequestInit) => {
+ const path = url.split('/applications/com.macro.workspace.mobile')[1];
+ calls.push(`${init.method} ${path}`);
+ const body = path === '/tracks/production/releases'
+ ? published
+ : path === '/edits'
+ ? { id: 'edit-1' }
+ : path.endsWith('/tracks/production')
+ ? production
+ : path.endsWith('/tracks/internal')
+ ? internal
+ : undefined;
+ return { ok: true, status: body === undefined ? 204 : 200, json: async () => body };
+ });
+ await expect(readTracks({ token: 't', request })).resolves.toEqual({
+ production,
+ internal,
+ summaries: published,
+ });
+ expect(calls).toEqual([
+ 'GET /tracks/production/releases',
+ 'POST /edits',
+ 'GET /edits/edit-1/tracks/production',
+ 'GET /edits/edit-1/tracks/internal',
+ 'DELETE /edits/edit-1',
+ ]);
+ });
+
+ it('rejects without a token', async () => {
+ await expect(readTracks({ token: '' })).rejects.toThrow(/access token/);
+ });
+});
diff --git a/apps/web/scripts/android-release-needed.mjs b/apps/web/scripts/android-release-needed.mjs
deleted file mode 100644
index 7fe549b8be..0000000000
--- a/apps/web/scripts/android-release-needed.mjs
+++ /dev/null
@@ -1,107 +0,0 @@
-import { appendFile } from 'node:fs/promises';
-import { execFileSync } from 'node:child_process';
-import { resolve } from 'node:path';
-import { pathToFileURL } from 'node:url';
-import {
- androidChangeReasons,
- androidNativeHash,
- androidVersionCode,
- gitIn,
- tauriPath,
-} from './android-native.mjs';
-
-const releaseTag = /^v20\d{2}\.\d{1,2}\.\d{1,2}(?:\.\d{1,2})?$/;
-
-export function androidReleaseDecision({ releases, cwd = process.cwd() }) {
- const git = gitIn(cwd);
- const head = git(['rev-parse', '--verify', 'HEAD^{commit}']);
- const candidates = new Map();
- for (const release of releases) {
- const tag = release.tag_name;
- if (release.draft || release.prerelease || !releaseTag.test(tag)) continue;
- const stem = `macro-${tag}-android-arm64`;
- const assets = new Set(
- release.assets
- .filter((asset) => asset.state === 'uploaded' && asset.size > 0)
- .map((asset) => asset.name)
- );
- if (
- !['.aab', '.aab.sha256', '-mapping.txt', '-mapping.txt.sha256'].every(
- (suffix) => assets.has(`${stem}${suffix}`)
- )
- )
- continue;
- // Missing tags/history must fail, rather than silently reuse a version code.
- const commit = git(['rev-parse', '--verify', `refs/tags/${tag}^{commit}`]);
- candidates.set(commit, tag);
- }
-
- // API release ordering can differ from commit order. Only consider ancestors
- // of this release, and prefer the closest one in topological history order.
- const baseline = git(['rev-list', '--topo-order', head])
- .split('\n')
- .find((commit) => candidates.has(commit));
- if (!baseline) {
- return {
- build: true,
- summary:
- 'Build the first AAB: no ancestor release has complete Android artifacts.',
- };
- }
- const tag = candidates.get(baseline);
- if (androidNativeHash(git, head) === androidNativeHash(git, baseline)) {
- return {
- build: false,
- summary: `Skip Android: the Android native code (${tauriPath}/ and the client cache wasm version) is unchanged since ${tag}. App updates use the bundle updater.`,
- };
- }
- const reason = `${androidChangeReasons(git, baseline, head).join(' and ')} since ${tag}`;
- if (androidVersionCode(git, head) <= androidVersionCode(git, baseline)) {
- throw new Error(
- `Native code changed (${reason}), but Android versionCode did not increase. Run just android-bump in apps/web and commit before tagging.`
- );
- }
- return {
- build: true,
- summary: `Build Android: ${reason}.`,
- };
-}
-
-if (
- process.argv[1] &&
- import.meta.url === pathToFileURL(resolve(process.argv[1])).href
-) {
- try {
- const repository = process.env.GITHUB_REPOSITORY;
- if (!repository || !/^[\w.-]+\/[\w.-]+$/.test(repository))
- throw new Error('GITHUB_REPOSITORY must identify the release repository');
- const pages = JSON.parse(
- execFileSync(
- 'gh',
- [
- 'api',
- '--paginate',
- '--slurp',
- `repos/${repository}/releases?per_page=100`,
- ],
- { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }
- )
- );
- const decision = androidReleaseDecision({ releases: pages.flat() });
- console.log(decision.summary);
- if (process.env.GITHUB_OUTPUT)
- await appendFile(process.env.GITHUB_OUTPUT, `build=${decision.build}\n`);
- if (process.env.GITHUB_STEP_SUMMARY)
- await appendFile(
- process.env.GITHUB_STEP_SUMMARY,
- `${decision.summary}\n`
- );
- } catch (error) {
- console.error(
- error instanceof Error
- ? error.message
- : 'Android release detection failed'
- );
- process.exitCode = 1;
- }
-}
diff --git a/apps/web/scripts/android-release.test.ts b/apps/web/scripts/android-release.test.ts
index 4d61dc154b..62714cd322 100644
--- a/apps/web/scripts/android-release.test.ts
+++ b/apps/web/scripts/android-release.test.ts
@@ -44,6 +44,17 @@ const releaseConfig = {
};
describe('Android release versions', () => {
+ it('names pull-request releases by version code', () => {
+ const code = releaseConfig.bundle.android.versionCode;
+ expect(androidReleaseMetadata(`vc${code}`, releaseConfig).filename).toBe(
+ `macro-vc${code}-android-arm64.aab`
+ );
+ expect(() => androidReleaseMetadata(`vc${code + 1}`, releaseConfig)).toThrow(
+ /does not match/
+ );
+ expect(() => androidReleaseMetadata('vc0', releaseConfig)).toThrow();
+ });
+
it.each(['v2026.10.7', 'v2026.10.6.2', 'v2027.1.1.0'])(
'uses the native config independently of tag %s',
(tag) => {
diff --git a/apps/web/scripts/android-release.ts b/apps/web/scripts/android-release.ts
index e6d5ce33d9..85b81753b8 100644
--- a/apps/web/scripts/android-release.ts
+++ b/apps/web/scripts/android-release.ts
@@ -28,9 +28,27 @@ const releaseConfigSchema = z
.passthrough();
export function androidReleaseMetadata(tag: string, config: unknown) {
+ const release = releaseConfigSchema.parse(config);
+ // Pull-request releases (the android-update label) have no production
+ // release tag; they are named by version code, `vc<versionCode>`, which
+ // must match the config being built.
+ const prLabel = /^vc([1-9][0-9]{0,9})$/.exec(tag);
+ if (prLabel) {
+ if (Number(prLabel[1]) !== release.bundle.android.versionCode)
+ throw new Error(
+ `Label ${tag} does not match the configured versionCode ${release.bundle.android.versionCode}`
+ );
+ return {
+ version: release.version,
+ versionCode: release.bundle.android.versionCode,
+ filename: `macro-${tag}-android-arm64.aab`,
+ };
+ }
const match = /^v(20\d{2})\.(\d{1,2})\.(\d{1,2})(?:\.(\d{1,2}))?$/.exec(tag);
if (!match || match[0] !== tag)
- throw new Error('Expected release tag vYYYY.M.D or vYYYY.M.D.N (N: 0–99)');
+ throw new Error(
+ 'Expected release tag vYYYY.M.D or vYYYY.M.D.N (N: 0–99), or vc<versionCode>'
+ );
const [year, month, day] = match.slice(1, 4).map(Number);
const date = new Date(Date.UTC(year, month - 1, day));
if (
@@ -39,7 +57,6 @@ export function androidReleaseMetadata(tag: string, config: unknown) {
date.getUTCDate() !== day
)
throw new Error('Release tag must contain a valid calendar date');
- const release = releaseConfigSchema.parse(config);
return {
version: release.version,
versionCode: release.bundle.android.versionCode,
diff --git a/apps/web/scripts/android-version-check.mjs b/apps/web/scripts/android-version-check.mjs
index 1aaeeaacbc..158fe01656 100644
--- a/apps/web/scripts/android-version-check.mjs
+++ b/apps/web/scripts/android-version-check.mjs
@@ -3,6 +3,7 @@
// base branch. The release workflow applies the same definition when it
// decides whether a production release needs a new App Bundle; catching a
// missing bump here keeps it from failing there, after the deploy.
+import { appendFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import {
@@ -31,8 +32,18 @@ export function checkAndroidVersion({
'--end-of-options',
`${head}^{commit}`,
]);
- if (androidNativeHash(git, baseCommit) === androidNativeHash(git, headCommit))
+ const output = (changed) => {
+ if (process.env.GITHUB_OUTPUT)
+ appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ `changed=${changed}\nversion_code=${androidVersionCode(git, headCommit)}\n`
+ );
+ };
+ if (androidNativeHash(git, baseCommit) === androidNativeHash(git, headCommit)) {
+ output(false);
return 'No Android native changes; no Android version bump needed.';
+ }
+ output(true);
const reason = androidChangeReasons(git, baseCommit, headCommit).join(
' and '
diff --git a/apps/web/scripts/android-release-needed.test.ts b/apps/web/scripts/android-version-check.test.ts
similarity index 51%
rename from apps/web/scripts/android-release-needed.test.ts
rename to apps/web/scripts/android-version-check.test.ts
index b389d29648..ec7debbe72 100644
--- a/apps/web/scripts/android-release-needed.test.ts
+++ b/apps/web/scripts/android-version-check.test.ts
@@ -3,7 +3,6 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { androidReleaseDecision } from './android-release-needed.mjs';
import { checkAndroidVersion } from './android-version-check.mjs';
const nativeConfig = 'apps/web/tauri/src-tauri/tauri.android.conf.json';
@@ -52,7 +51,7 @@ function release(tag = 'v2026.10.1') {
}
beforeEach(() => {
- cwd = mkdtempSync(join(tmpdir(), 'android-release-needed-'));
+ cwd = mkdtempSync(join(tmpdir(), 'android-version-check-'));
git('init', '--initial-branch=main');
git('config', 'user.name', 'Release test');
git('config', 'user.email', '[email protected]');
@@ -203,195 +202,3 @@ describe('PR Android version enforcement', () => {
});
});
-describe('native release detection', () => {
- it('builds the first AAB when no complete ancestor bundle exists', () => {
- expect(androidReleaseDecision({ cwd, releases: [] }).build).toBe(true);
- });
-
- it('skips frontend, backend, workflow, and root dependency changes', () => {
- const baseline = release();
- for (const path of [
- 'apps/web/src/index.tsx',
- 'services/example/src/lib.rs',
- '.github/workflows/release-production.yml',
- 'Cargo.lock',
- 'apps/web/scripts/android.sh',
- ]) {
- write(path, 'changed');
- }
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- false
- );
- });
-
- it.each([
- 'apps/web/tauri/src-tauri/src/lib.rs',
- 'apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts',
- 'apps/web/tauri/src-tauri/gen/apple/project.yml',
- ])('builds for changes under %s with a new version code', (path) => {
- const baseline = release();
- write(path, 'changed');
- version(2);
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- true
- );
- });
-
- it.each([1, 0])('rejects native changes with version code %s', (code) => {
- const baseline = release();
- write('apps/web/tauri/src-tauri/src/lib.rs', '// changed');
- version(code);
- commit();
- expect(() => androidReleaseDecision({ cwd, releases: [baseline] })).toThrow(
- /versionCode/
- );
- });
-
- const cacheWasm = (version: string, extra = '') =>
- write(
- 'crates/client/cache-wasm/Cargo.toml',
- `[package]\nname = "cache-wasm"\nversion = "${version}"\n${extra}`
- );
-
- it('builds when the client cache wasm version moves, with a new version code', () => {
- cacheWasm('0.6.1');
- commit();
- const baseline = release();
- cacheWasm('0.6.2');
- write('crates/client/cache-core/src/lib.rs', '// cache change');
- version(2);
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] })).toEqual({
- build: true,
- summary: expect.stringContaining(
- 'the client cache wasm version moved (0.6.1 → 0.6.2) since v2026.10.1'
- ),
- });
- });
-
- it('rejects a client cache wasm version bump without a new version code', () => {
- cacheWasm('0.6.1');
- commit();
- const baseline = release();
- cacheWasm('0.6.2');
- commit();
- expect(() => androidReleaseDecision({ cwd, releases: [baseline] })).toThrow(
- /versionCode/
- );
- });
-
- it('skips client cache changes that do not move the wasm version', () => {
- cacheWasm('0.6.1');
- commit();
- const baseline = release();
- cacheWasm('0.6.1', '[dependencies]\nserde = "1"\n');
- write('crates/client/cache-core/src/lib.rs', '// cache change');
- write('crates/client/cache-turso/src/lib.rs', '// storage change');
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- false
- );
- });
-
- it('detects deleted native files', () => {
- const baseline = release();
- rmSync(join(cwd, 'apps/web/tauri/src-tauri/src/lib.rs'));
- version(2);
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- true
- );
- });
-
- it('skips net-zero native changes', () => {
- const baseline = release();
- write('apps/web/tauri/src-tauri/src/lib.rs', '// temporary');
- commit();
- write('apps/web/tauri/src-tauri/src/lib.rs', '// native');
- commit();
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- false
- );
- });
-
- it('uses the closest ancestor regardless of API release ordering', () => {
- const old = release();
- version(2);
- commit();
- const latest = release('v2026.10.2');
- write('apps/web/src/index.tsx', '// frontend');
- commit();
- expect(androidReleaseDecision({ cwd, releases: [old, latest] })).toEqual({
- build: false,
- summary: expect.stringContaining('v2026.10.2'),
- });
- });
-
- it.each(['missing', 'empty', 'uploading', 'draft', 'prerelease'])(
- 'does not lose changes after a release with %s artifacts',
- (state) => {
- const baseline = release();
- version(2);
- commit();
- const failed = release('v2026.10.2');
- if (state === 'missing') failed.assets.pop();
- if (state === 'empty') failed.assets[0].size = 0;
- if (state === 'uploading') failed.assets[0].state = 'starter';
- if (state === 'draft') failed.draft = true;
- if (state === 'prerelease') failed.prerelease = true;
- write('apps/web/src/index.tsx', '// frontend');
- commit();
- expect(
- androidReleaseDecision({ cwd, releases: [failed, baseline] })
- ).toEqual({
- build: true,
- summary: expect.stringContaining('v2026.10.1'),
- });
- }
- );
-
- it('ignores bundles on an unrelated branch and future releases', () => {
- const baseline = release();
- git('checkout', '-b', 'other');
- version(3);
- commit();
- const unrelated = release('v2026.10.3');
- git('checkout', 'main');
- version(2);
- commit();
- const current = git('rev-parse', 'HEAD');
- version(3);
- commit();
- const future = release('v2026.10.4');
- git('checkout', '--detach', current);
- expect(
- androidReleaseDecision({ cwd, releases: [future, unrelated, baseline] })
- ).toEqual({ build: true, summary: expect.stringContaining('v2026.10.1') });
- });
-
- it('skips a rerun after this release already published complete artifacts', () => {
- const current = release();
- expect(androidReleaseDecision({ cwd, releases: [current] }).build).toBe(
- false
- );
- });
-
- it('supports annotated release tags', () => {
- const baseline = release();
- git('tag', '-d', baseline.tag_name);
- git('tag', '-a', baseline.tag_name, '-m', 'release');
- expect(androidReleaseDecision({ cwd, releases: [baseline] }).build).toBe(
- false
- );
- });
-
- it('fails when a published bundle tag is absent from checkout history', () => {
- const baseline = release();
- git('tag', '-d', baseline.tag_name);
- expect(() =>
- androidReleaseDecision({ cwd, releases: [baseline] })
- ).toThrow();
- });
-});
diff --git a/docs/development/android.md b/docs/development/android.md
index fabb9d46ff..d350240c95 100644
--- a/docs/development/android.md
+++ b/docs/development/android.md
@@ -128,158 +128,91 @@ The upload certificate identifies locally signed artifacts. When Google creates
the Play App Signing key, Play-delivered APKs use that separate certificate; add
its fingerprint to production associations before testing Play-installed links.
-### Production release artifacts
-
-After web, cloud-storage, sync-service, and AI editing worker deployments succeed,
-`.github/workflows/release-production.yml` dispatches the independent
-`release-android.yml` workflow and does not wait for it. Android has its own
-concurrency group and cancellation lifecycle: a slow or canceled native build
-cannot hold the production deployment lock or delay the next deployment.
-Cancel an already-dispatched Android build from its own workflow run; canceling
-the production run does not cancel it.
-
-The Android workflow builds an ARM64 signed AAB from the selected release tag
-only when `apps/web/tauri/` differs from the closest ancestor release with a
-complete AAB, R8 mapping, and checksums. The first release without
-such a baseline builds an AAB. Frontend-only releases skip native builds and Play
-uploads; their app updates use the bundle updater. The comparison covers the
-entire Tauri directory, including Android, iOS, Rust, and native config files,
-plus one signal outside it: the `version` of the client cache wasm package in
-`crates/client/cache-wasm/Cargo.toml`. The app compiles the client cache
-crates natively, and the team bumps that version when a cache change must
-ship, so a bump since the baseline release counts as a native change (other
-edits under `crates/client` do not). Other changes outside the Tauri
-directory do not trigger a native release. If an external dependency or
-build-script change needs a new binary, bump the native version code in the
-Tauri directory as part of that change.
-
-Failed/incomplete artifact uploads do not advance the baseline. A rerun whose
-release already has complete artifacts skips rebuilding; retry a failed Play
-upload through the publishing workflow after checking Console.
-
-The native build uses production services, the pinned production Firebase config,
-and the normal OTA-enabled release build.
-The GitHub Actions `ANDROID_RELEASE_DOPPLER_TOKEN` secret must have read access to
-`android-release/prd`, including both the signing JSON and pinned Firebase secret.
-CI passes this dedicated read-only service token as `DOPPLER_TOKEN` only during
-configuration retrieval. Signing files live in the runner's temporary directory
-and are removed even when the build fails. Only AAB, R8 mapping, and checksum
-files are attached to the release; the separate `android-build-log` Actions artifact is retained for
-seven days, including on failed builds.
-
-Android's native release identity lives in
-`apps/web/tauri/src-tauri/tauri.android.conf.json`: `version` is the user-visible
-versionName, and `bundle.android.versionCode` is an independent positive integer
-counter. Local Tauri builds and CI use the same values. Release tags may be
-`vYYYY.M.D` or `vYYYY.M.D.N` (valid dates, years 2000–2099, revision 0–99); they
-identify source and artifact filenames, and do not determine either Android
-version field.
-
-Build **1** was the manual Play bootstrap bundle. The next native release uses
-build **2**. Before each subsequent native release (including a new binary with the same marketing version), run
-from `apps/web`:
-
-```sh
-just android-bump
-```
-
-Commit the changed config before tagging the release. This increments only
-`versionCode`; edit `version` separately when changing the marketing version.
-The PR's **Android Version Code** check compares its merged result with the base
-branch and requires a higher code when the Android native code changed: any
-file under `apps/web/tauri/` except iOS-, macOS-, Linux- and desktop-only
-paths by naming convention (`ios/` directories, `gen/apple/`, `*.ios.*` and
-`*.macos.*` config, `macos_*`/`linux_*` sources, the macOS icon set,
-`desktop-release.json`, `.helix/`), or a bump of the client cache wasm
-version. It feeds the required **Web App Status Check**, so a missing bump
-blocks merging. If another PR has already used your proposed code, update
-your branch and bump again. The release workflow applies the same definition
-(both read `apps/web/scripts/android-native.mjs`) and rejects native changes
-whose code is not greater than the last published AAB baseline, so a PR that
-passes the check cannot fail the release for the same reason. No version
-bump is needed for frontend-only, backend-only, or iOS/desktop-only changes.
-Builds never increment the counter implicitly, so retries of the same release
-retain its identity. Never distribute different releases with the same code or
-reuse a code already uploaded to Google Play. Keep the signing key for upgrades.
-The counter may not exceed [Google Play's 2,100,000,000 limit](https://developer.android.com/studio/publish/versioning).
-
-This deliberately resets the former date-based/test codes. The new Android package
-is a separate installation from the former `com.macro.app.prod` test APK; it does
-not update that app or inherit its local data. Do not carry the old test APK into
-the Play rollout. Uninstall the old app when moving testers to the new package:
-both apps claim the same `macro://` authentication and navigation callbacks.
-
-`MIN_NATIVE_BUILD_ANDROID` remains a separate compatibility floor. For the first
-build with runtime GraphQL SDL and schema 3 OTA support (#7724 and #7303), it is
-**1**. Both floors are checked in at `apps/web/min-native-build.json`, which
-`just build-prod` exports as `MIN_NATIVE_BUILD_ANDROID` / `MIN_NATIVE_BUILD_IOS`.
-Retain the floor as the native counter increases; raise it only when the frontend
-requires newer native capabilities. Older date-coded test APKs exceed this floor,
-so retire them rather than relying on it to exclude those test installs.
-
-When moving to Google Play, keep this same counter for AAB builds across all
-tracks (internal testing, closed testing, and production). Promote the same
-uploaded artifact between tracks; allocate a new code for a new binary. The
-existing `just android-build --apk false --aab true` path uses the same Tauri config.
-CI builds only the AAB; the Google Play workflow below uploads it to internal testing. Use
-[Play App Signing](https://developer.android.com/studio/publish/app-signing) and
-preserve its app-signing key once
-Play distribution starts; the upload key and installed-app signing key are
-separate roles.
-
-Before publishing artifacts, CI verifies the signing certificate, package/version,
-ARM64 ABI, and non-debuggable manifest, and checks the AAB structure
-with a checksum-pinned bundletool. The automatic Android workflow starts after
-web/backend rollout succeeds. Build or publishing failures are reported on the
-Android workflow; the production workflow reports only whether dispatch succeeded.
-CI verification does not replace the device qualification described above.
-
-To recover an Android artifact without redeploying production, manually run
-`release-android.yml` from `main` with `operation=rebuild` (the default) and
-`release_tag` set to an existing published production release. The source is
-checked out from that tag; this workflow has no web/backend deployment jobs.
-`publish_android` defaults to false so the first run can validate the build and leave the files in the `android-release` Actions artifact. Set it to
-true to attach the verified artifacts and checksums to the selected release.
-This explicit recovery path bypasses change detection and does not automatically
-upload to Play:
-
-```sh
-gh workflow run release-android.yml --ref main -f operation=rebuild -f release_tag=v2026.9.30.0 -f publish_android=true
-```
-
-The Android job uses an ephemeral GitHub-hosted runner without a separate Nix
-cache mount. Do not invoke the shared `teardown-nix` cache-volume action there:
-its `fuser -km /nix` can kill the runner when `/nix` is on the root filesystem,
-preventing GitHub from receiving the build logs. Let the hosted VM be discarded.
-
-The public GitHub release receives `macro-<tag>-android-arm64.aab`,
-`macro-<tag>-android-arm64-mapping.txt`, and a `.sha256` checksum for each.
-Release CI does not build or attach APKs. Testers install through Google Play's
-internal testing track after the bundle is uploaded; an AAB cannot be installed
-directly on a device.
+### Releasing to Google Play from a pull request
+
+Android releases are driven from pull requests, like iOS (see
+`apps/web/docs/ios-releases.md`); they are not tied to the production
+deployment cycle. Three generated workflows plus the `Android Native Check`
+job of the web app PR checks enforce it:
+
+**`Android Native Check`** runs on every PR against `main`. It always
+requires a `versionCode` bump when the Android native code changed (see
+"Native release identity" above for what counts), and, when it changed, asks
+Google Play whether that version code is a production release that Google
+has **published** (through review and available to users — the edit API's
+`status: completed` only describes the rollout, so the gate also reads the
+release list's `releaseLifecycleState`), built from the native code of the
+PR's merge result. Until both hold the check fails and the required
+`Web App Status Check` fails with it. Add **`skip-android-update`** for
+native changes that don't break the native/web contract; the `Native Check
+Label` workflow re-runs just the gate job when that label is added or
+removed.
+
+To release:
+
+1. Bump and commit: `just android-bump` in `apps/web`.
+2. Add the **`android-update`** label once the PR is ready to merge. The
+ **`Android Play Release`** workflow (`.github/workflows/android-play-release.yml`)
+ first refuses drafts, PRs with failing checks (pending ones are waited on,
+ up to 30 minutes), PRs without a bump, and PRs whose head lacks Android
+ native code that landed on `main` since they branched (the gate hashes
+ the merge result, so such a bundle could never pass it; merge `main`,
+ bump, re-add the label). It then builds the signed App Bundle from the PR
+ head on a hosted Ubuntu runner (Android SDK, Nix, signing and Firebase
+ config from Doppler `android-release/prd`), verifies it with bundletool,
+ checks again that neither the PR head nor `main` changed native code
+ during the build, uploads it to the **internal** track with
+ `status=completed`, and promotes it to **production** as a full rollout
+ (Google review applies). The bundle and R8 mapping are kept as a workflow
+ artifact for 90 days. The release notes carry a provenance stamp,
+ `native tree <hash> for PR #<n>`, the twin of the iOS TestFlight stamp.
+ The run comments the outcome on the PR; remove and re-add the label to
+ retry. Click **Enable auto-merge** on the PR to merge the moment it is
+ live.
+3. Wait for Google. The **`Android Release Watch`** workflow (every 30
+ minutes) notices the version code being published on production, re-runs
+ the PR's failed `Android Native Check` job, and comments; the PR merges if
+ auto-merge is on.
+4. Pushes after the label: web-only commits need nothing. Native commits make
+ the bundle stale: **`Android Release Drift`** cancels an in-progress build,
+ removes the label and comments. A Play production release cannot be
+ withdrawn once submitted, so if the stale bundle was already promoted the
+ comment says so and the follow-up should ship as soon as possible (after
+ a force-push the old head is gone, so drift checks Play for the new
+ head's version code instead).
+
+Play is the source of truth for what is live; nothing ties Android bundles
+to production release tags any more. `publish-android-play.yml` remains as
+the manual fallback (promote a version code by hand; upload a bundle from a
+GitHub release that carries one).
+
+The native build uses production services, the pinned production Firebase
+config, and the normal OTA-enabled release build. The GitHub Actions
+`ANDROID_RELEASE_DOPPLER_TOKEN` secret must have read access to
+`android-release/prd`, including both the signing JSON and pinned Firebase
+secret; CI passes this dedicated read-only service token as `DOPPLER_TOKEN`
+only during configuration retrieval. Signing files live in the runner's
+temporary directory and are removed even when the build fails. The separate
+`android-build-log` Actions artifact is retained for seven days (unlike the
+90-day `android-release` bundle artifact), including on failed builds.
+
+The Android workflows use ephemeral GitHub-hosted runners without a separate
+Nix cache mount. Do not invoke the shared `teardown-nix` cache-volume action
+there: its `fuser -km /nix` can kill the runner when `/nix` is on the root
+filesystem, preventing GitHub from receiving the build logs. Let the hosted
+VM be discarded.
+
+Testers install through Google Play's internal testing track once the
+bundle is uploaded; an AAB cannot be installed directly on a device.
### Google Play publishing
-`.github/workflows/publish-android-play.yml` runs from `main`. After successful
-backend/web rollout, the production workflow dispatches `release-android.yml`
-with `operation=release`. That independent workflow checks for native changes,
-builds and verifies the AAB, and attaches its artifacts to GitHub. It then
-dispatches the Play publishing workflow with `operation=upload-internal` and
-`status=completed`. Testers receive the new version subject to Google Play
-checks. Frontend-only releases do not dispatch the Play publishing workflow.
-The separate workflow result reports whether the Play upload succeeded; queuing
-it does not mean Play has accepted the release. Manual upload remains available
-for recovery and Console-review drafts.
-It downloads the verified AAB and R8 mapping from a published GitHub release,
-checks their checksums, authenticates with short-lived Google credentials, and
-uploads to the **internal testing** track for `com.macro.workspace.mobile`.
-Its separate `promote-production` operation submits an existing tested version
-for a full production rollout without rebuilding or uploading the binary again.
-All Play edits use one concurrency group, including uploads and promotions.
-Production promotion remains manual, after device qualification of the
-Play-installed internal build. The dispatcher runs the publishing workflow on
-`main` so the existing Google OIDC restrictions remain valid; its GitHub token
-has `actions: write` for the workflow dispatch.
+`.github/workflows/publish-android-play.yml` runs from `main` and is the
+manual fallback. Routine releases go through the `Android Play Release`
+workflow described above, which uploads the PR's bundle to internal testing
+and promotes it to production itself; the publishing workflow is for
+promoting a version code by hand or uploading a bundle attached to a GitHub
+release.
#### First bundle (one time)
@@ -287,11 +220,9 @@ The Play app must already exist, and its first AAB must be uploaded manually
before the publishing API can find the package. See the
[upload action's setup guide](https://github.com/r0adkll/upload-google-play#faq).
-1. Merge the AAB build changes, then publish a release containing them. Recovery
- builds check out the selected release tag, so a tag predating
- `scripts/android-bundle.ts` cannot use the new verification step. For an older
- release, build the AAB locally from the intended source and verify it
- using the release signing procedure above.
+1. Build the first AAB locally from the intended source and verify it using
+ the release signing procedure above (the `Android Play Release` workflow
+ cannot run before the package exists in Play Console).
2. Download `macro-<tag>-android-arm64.aab` and its checksum from the release (or
from the `android-release` Actions artifact for a build-only run). Verify the
checksum before upload.
@@ -310,8 +241,8 @@ before the publishing API can find the package. See the
including sign-in, notifications, links, and upgrades.
The first manual upload consumes its version code. For the next binary, run
-`just android-bump` in `apps/web` and commit before tagging. Do not upload the
-bootstrap bundle again through CI.
+`just android-bump` in `apps/web` and commit it on the PR that carries the
+native change. Do not upload the bootstrap bundle again through CI.
#### Keyless publishing credentials (one time)
@@ -400,13 +331,13 @@ gh variable set GOOGLE_PLAY_SERVICE_ACCOUNT --repo macro-inc/macro \
```
-#### Routine upload and recovery
+#### Manual upload (fallback)
-After the first manual upload and credentials setup, native production releases
-automatically upload to internal testing with `status=completed`. For a manual
-upload or retry, select **Publish Android to Google Play** in Actions, run from
-`main`, select `operation=upload-internal`, and supply a published release tag
-that contains Android artifacts.
+The `Android Play Release` workflow uploads and promotes automatically. For a
+manual upload, select **Publish Android to Google Play** in Actions, run from
+`main`, select `operation=upload-internal`, and supply a published GitHub
+release tag that carries Android artifacts (none are produced automatically
+any more; attach them to a release first).
`status=draft` (the default) saves a release for Console review. Select
`status=completed` to release to internal testers, subject to Play's checks:
@@ -423,12 +354,11 @@ If a run fails, inspect Console before retrying: a completed upload may already
have consumed the version code. Complete or promote an existing draft there
instead of re-uploading it to change status. A new binary needs a new code. Avoid
editing the same app in Console while a CI upload is in progress; committing
-another edit invalidates the upload's pending edit. Missing AAB or mapping assets
-must be recovered with the build workflow before publishing.
+another edit invalidates the upload's pending edit.
-#### Promote a tested version to production
+#### Promote a tested version to production (fallback)
-After qualifying the Play-installed internal build, manually run the same
+The release workflow promotes automatically. To promote by hand, run the same
**Publish Android to Google Play** workflow from `main` with
`operation=promote-production` and its exact Android `version_code`. Use the code
shown in Play Console; this is not the release tag or marketing version. Leave
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows.rs b/tooling/xtask/crates/xtask_workflows/src/workflows.rs
index e779176cae..055f0bba5f 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows.rs
@@ -9,6 +9,9 @@
//! files — [`runners`] (runner labels), [`vars`] (env / secrets / concurrency),
//! and [`steps`] (reusable step + job helpers).
+mod android_play_release;
+mod android_release_drift;
+mod android_release_watch;
mod assign_author;
mod assign_labels;
mod build_agent_daemon_on_tag;
@@ -39,10 +42,10 @@ mod deploy_website;
mod ensure_daytona_snapshot;
mod export_ci_telemetry;
mod ios_app_store_release;
-mod ios_native_check_label;
mod ios_preview;
mod ios_release_drift;
mod ios_release_watch;
+mod native_check_label;
mod path_validation;
mod publish_sdk;
mod pulumi_preview_pr;
@@ -302,9 +305,24 @@ const WORKFLOWS: &[WorkflowFile] = &[
render_yaml: || render_gh_workflow(ios_app_store_release::ios_app_store_release)(),
},
WorkflowFile {
- slug: "ios_native_check_label",
- file_name: "ios-native-check-label.yml",
- render_yaml: || render_gh_workflow(ios_native_check_label::ios_native_check_label)(),
+ slug: "native_check_label",
+ file_name: "native-check-label.yml",
+ render_yaml: || render_gh_workflow(native_check_label::native_check_label)(),
+ },
+ WorkflowFile {
+ slug: "android_play_release",
+ file_name: "android-play-release.yml",
+ render_yaml: || render_gh_workflow(android_play_release::android_play_release)(),
+ },
+ WorkflowFile {
+ slug: "android_release_watch",
+ file_name: "android-release-watch.yml",
+ render_yaml: || render_gh_workflow(android_release_watch::android_release_watch)(),
+ },
+ WorkflowFile {
+ slug: "android_release_drift",
+ file_name: "android-release-drift.yml",
+ render_yaml: || render_gh_workflow(android_release_drift::android_release_drift)(),
},
WorkflowFile {
slug: "ios_release_drift",
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
new file mode 100644
index 0000000000..289df931d5
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_play_release.rs
@@ -0,0 +1,423 @@
+//! `Android Play Release` — add the `android-update` label to a PR with
+//! Android native changes and this workflow builds the signed App Bundle
+//! from the PR head, uploads it to Google Play's internal track and promotes
+//! it to production (full rollout; Google review applies) — the release the
+//! `Android Native Check` merge gate (a job of [`super::web_app_check_main`])
+//! then waits on; [`super::android_release_watch`] re-runs the gate once the
+//! release is live. The iOS counterpart is [`super::ios_app_store_release`].
+//!
+//! The PR must already contain the version code bump (`just android-bump`
+//! in `apps/web`, committed): the preconditions verify it against the base
+//! branch and fail fast otherwise. Release retries are label-driven (remove
+//! and re-add `android-update`).
+//!
+//! Play is the only artifact store that matters: the bundle and its R8
+//! mapping are also kept as a workflow artifact, but nothing ties releases to
+//! production release tags any more (the former tag-driven
+//! `release-android.yml` is gone). Each upload carries a provenance stamp in
+//! its release notes — the Android native hash it was built from and the PR
+//! number — that the gate and the watcher compare against the PR's merge
+//! result, exactly like the iOS TestFlight stamp.
+//!
+//! Credentials: the signing keystore and Firebase config come from Doppler
+//! (`android-release/prd` via `ANDROID_RELEASE_DOPPLER_TOKEN`); Play access is
+//! keyless (Workload Identity Federation through the repository variables
+//! `GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER` / `GOOGLE_PLAY_SERVICE_ACCOUNT`).
+
+use gh_workflow::{
+ Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,
+ Step, Use, Workflow,
+};
+
+use crate::workflows::{steps, vars};
+
+/// Build the workflow.
+pub fn android_play_release() -> Workflow {
+ Workflow::new("Android Play Release")
+ .on(Event::default()
+ .pull_request(PullRequest::default().add_type(PullRequestType::Labeled)))
+ .concurrency(Concurrency::new(Expression::new(
+ "android-play-release-${{ github.event.pull_request.number }}",
+ )))
+ .add_job("release", release_job())
+}
+
+fn release_job() -> Job {
+ Job::default()
+ .name("Android Play Release")
+ // Same-repo PRs only: the release needs the signing secrets and the
+ // Play identity, which fork PRs don't receive anyway.
+ .cond(Expression::new(
+ "github.event.label.name == 'android-update' && \
+ github.event.pull_request.head.repo.full_name == github.repository",
+ ))
+ // The former tag-driven build ran on this hosted image (Android SDK
+ // preinstalled, no Nix cache mount; see docs/development/android.md).
+ .runs_on("ubuntu-24.04")
+ .timeout_minutes(90u32)
+ .permissions(
+ Permissions::default()
+ .checks(Level::Read)
+ .contents(Level::Read)
+ .id_token(Level::Write)
+ .pull_requests(Level::Write)
+ .statuses(Level::Read),
+ )
+ .add_env(("CI", "true"))
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
+ .add_step(checkout_pr_head())
+ .add_step(setup_bun())
+ .add_step(preconditions())
+ .add_step(install_android_sdk())
+ .add_step(setup_nix())
+ .add_step(setup_prereqs())
+ .add_step(prepare_version_and_signing())
+ .add_step(build_bundle())
+ .add_step(preserve_build_log())
+ .add_step(verify_and_collect())
+ .add_step(head_guard())
+ .add_step(provenance_stamp())
+ .add_step(upload_workflow_artifact())
+ .add_step(play_auth())
+ .add_step(upload_internal())
+ .add_step(promote_production())
+ .add_step(remove_signing_material())
+ .add_step(pr_comment())
+}
+
+fn checkout_pr_head() -> Step<Use> {
+ Step::new("Checkout PR head")
+ .uses(
+ "actions",
+ "checkout",
+ "df4cb1c069e1874edd31b4311f1884172cec0e10",
+ ) // v6
+ .add_with(("ref", "${{ github.event.pull_request.head.sha }}"))
+ .add_with(("persist-credentials", false))
+}
+
+/// Bun before Nix: the preconditions run the Android scripts before the
+/// toolchain is set up.
+fn setup_bun() -> Step<Use> {
+ Step::new("Setup Bun")
+ .uses(
+ "oven-sh",
+ "setup-bun",
+ "0c5077e51419868618aeaa5fe8019c62421857d6",
+ ) // v2.2.0
+ .add_with(("bun-version", "1.3.13"))
+}
+
+/// `android-update` means "release this and merge it when it is live", so the
+/// PR must already be mergeable: not a draft, every other check on the head
+/// commit green (pending ones are waited on), and the version code bumped.
+fn preconditions() -> Step<Run> {
+ Step::new("Require the PR to be ready to merge")
+ .run(concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/pr_merge_commit.sh"),
+ include_str!("scripts/android_release_preconditions.sh")
+ ))
+ .id("preconditions")
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("HEAD_SHA", "${{ github.event.pull_request.head.sha }}"))
+ .add_env(("WAIT_MINUTES", "30"))
+}
+
+fn install_android_sdk() -> Step<Run> {
+ Step::new("Install Android SDK components")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ export JAVA_HOME="$JAVA_HOME_21_X64"
+ export PATH="$JAVA_HOME/bin:$PATH"
+ "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
+ 'platforms;android-36' 'build-tools;36.0.0' 'ndk;30.0.16248370'
+ echo "JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"
+ echo "NDK_HOME=$ANDROID_HOME/ndk/30.0.16248370" >> "$GITHUB_ENV"
+ "#})
+ .shell("bash")
+}
+
+fn setup_nix() -> Step<Use> {
+ steps::setup_nix()
+}
+
+fn setup_prereqs() -> Step<Use> {
+ steps::setup_reqs_web("Setup prerequisites", false)
+}
+
+/// Pull-request releases are named by version code (`vc<code>`), not by a
+/// production release tag.
+fn prepare_version_and_signing() -> Step<Run> {
+ Step::new("Prepare version and signing")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ filename=$(bun scripts/android-release.ts metadata "vc${VERSION_CODE}" "$RUNNER_TEMP/android-release.json")
+ echo "filename=$filename" >> "$GITHUB_OUTPUT"
+ echo "release_name=$(jq -r .version tauri/src-tauri/tauri.android.conf.json) (${VERSION_CODE})" >> "$GITHUB_OUTPUT"
+ bun scripts/android-release.ts signing "$RUNNER_TEMP/android-signing" \
+ tauri/src-tauri/gen/android/keystore.properties
+ bun scripts/android-firebase.ts build --doppler "$RUNNER_TEMP/android-google-services.json"
+ "#})
+ .id("metadata")
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("VERSION_CODE", "${{ steps.preconditions.outputs.version_code }}"))
+ .add_env(("DOPPLER_TOKEN", vars::ANDROID_RELEASE_DOPPLER_TOKEN))
+}
+
+fn build_bundle() -> Step<Run> {
+ Step::new("Build production App Bundle")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ # The Nix environment is already loaded. Do not reload it in nested
+ # bash processes and re-enable its local-development sccache wrapper.
+ # This ephemeral runner has no compiler cache/server to reuse.
+ unset BASH_ENV
+ export RUSTC_WRAPPER=""
+ cargo tauri --version
+ # Tauri has shipped both switch-only and value-taking APK/AAB flags.
+ # Nix and local installations can differ; build only the AAB with either CLI.
+ android_help=$(cargo tauri android build --help)
+ artifact_args=(--aab)
+ if [[ "$android_help" == *'--apk <APK>'* ]]; then
+ artifact_args=(--apk false --aab true)
+ fi
+ just android-build --firebase-config "$RUNNER_TEMP/android-google-services.json" \
+ "${artifact_args[@]}" --ci --config "$RUNNER_TEMP/android-release.json" \
+ 2>&1 | tee "$RUNNER_TEMP/android-build.log"
+ "#})
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env((
+ "VITE_SEGMENT_WRITE_KEY",
+ "${{ secrets.SEGMENT_WRITE_KEY_PRODUCTION }}",
+ ))
+ .add_env(("VITE_POSTHOG_API_KEY", vars::POSTHOG_API_KEY))
+ .add_env((
+ "VITE_OTEL_EXPORTER_URL",
+ "https://macro-prox-prod.macroverse.workers.dev/i/otlp/v1/traces",
+ ))
+ .add_env(("VITE_OTEL_ENV", "prod"))
+}
+
+fn preserve_build_log() -> Step<Use> {
+ Step::new("Preserve Android build log")
+ .uses(
+ "actions",
+ "upload-artifact",
+ "ea165f8d65b6e75b540449e92b4886f43607fa02",
+ ) // v4
+ .if_condition(Expression::new("always()"))
+ .add_with(("name", "android-build-log"))
+ .add_with(("path", "${{ runner.temp }}/android-build.log"))
+ .add_with(("if-no-files-found", "ignore"))
+ .add_with(("retention-days", 7))
+}
+
+fn verify_and_collect() -> Step<Run> {
+ Step::new("Verify and collect App Bundle")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ curl --fail --location --retry 3 \
+ https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar \
+ --output "$RUNNER_TEMP/bundletool.jar"
+ echo "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29 $RUNNER_TEMP/bundletool.jar" | sha256sum --check
+ mapfile -t bundles < <(find tauri/src-tauri/gen/android/app/build/outputs/bundle -type f -name '*-release.aab')
+ if [ "${#bundles[@]}" -ne 1 ]; then
+ echo "Expected exactly one signed release AAB, found ${#bundles[@]}" >&2
+ exit 1
+ fi
+ bun scripts/android-bundle.ts "vc${VERSION_CODE}" "${bundles[0]}" \
+ "$RUNNER_TEMP/bundletool.jar" "$RUNNER_TEMP/android-signing/certificate-sha256"
+ bundle_filename="${RELEASE_FILENAME%.*}.aab"
+ mkdir -p "$GITHUB_WORKSPACE/android-artifacts"
+ cp "${bundles[0]}" "$GITHUB_WORKSPACE/android-artifacts/$bundle_filename"
+ # R8 mapping belongs to this exact binary; preserve it for Play crash reports.
+ bundle_variant=$(basename "$(dirname "${bundles[0]}")")
+ mapping="tauri/src-tauri/gen/android/app/build/outputs/mapping/$bundle_variant/mapping.txt"
+ if [[ ! -s "$mapping" ]]; then
+ echo "Missing R8 mapping for bundle variant $bundle_variant" >&2
+ exit 1
+ fi
+ mapping_filename="${bundle_filename%.aab}-mapping.txt"
+ cp "$mapping" "$GITHUB_WORKSPACE/android-artifacts/$mapping_filename"
+ \cd "$GITHUB_WORKSPACE/android-artifacts"
+ sha256sum "$bundle_filename" > "$bundle_filename.sha256"
+ sha256sum "$mapping_filename" > "$mapping_filename.sha256"
+ echo "bundle=$GITHUB_WORKSPACE/android-artifacts/$bundle_filename" >> "$GITHUB_OUTPUT"
+ echo "mapping=$GITHUB_WORKSPACE/android-artifacts/$mapping_filename" >> "$GITHUB_OUTPUT"
+ "#})
+ .id("artifact")
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("VERSION_CODE", "${{ steps.preconditions.outputs.version_code }}"))
+ .add_env(("RELEASE_FILENAME", "${{ steps.metadata.outputs.filename }}"))
+}
+
+/// Native code pushed while the build ran would make the bundle stale; don't
+/// upload it (the drift workflow also cancels runs after the fact).
+fn head_guard() -> Step<Run> {
+ Step::new("Require the PR's Android native code to be unchanged since the build")
+ .run(concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/pr_merge_commit.sh"),
+ include_str!("scripts/android_release_head_guard.sh")
+ ))
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
+/// The release notes carry the native hash and PR number, which the gate and
+/// the watcher compare against the merge result (the TestFlight stamp's twin).
+fn provenance_stamp() -> Step<Run> {
+ Step::new("Write the provenance stamp as release notes")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ hash=$(bun scripts/android-native.mjs hash HEAD)
+ mkdir -p "$RUNNER_TEMP/whatsnew"
+ printf 'native tree %s for PR #%s\n' "$hash" "$PR_NUMBER" > "$RUNNER_TEMP/whatsnew/whatsnew-en-US"
+ echo "Stamp: native tree ${hash} for PR #${PR_NUMBER}"
+ "#})
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
+fn upload_workflow_artifact() -> Step<Use> {
+ Step::new("Upload verified Android artifact")
+ .uses(
+ "actions",
+ "upload-artifact",
+ "ea165f8d65b6e75b540449e92b4886f43607fa02",
+ ) // v4
+ .add_with(("name", "android-release"))
+ .add_with(("path", "android-artifacts/"))
+ .add_with(("if-no-files-found", "error"))
+ .add_with(("retention-days", 90))
+}
+
+/// Keyless Play access: a credentials file for the upload action and an
+/// access token for the promotion script.
+fn play_auth() -> Step<Use> {
+ Step::new("Authenticate to Google Play")
+ .uses(
+ "google-github-actions",
+ "auth",
+ "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
+ ) // v3
+ .id("auth")
+ .add_with((
+ "workload_identity_provider",
+ "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
+ ))
+ .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
+ .add_with(("token_format", "access_token"))
+ .add_with((
+ "access_token_scopes",
+ "https://www.googleapis.com/auth/androidpublisher",
+ ))
+ .add_with(("export_environment_variables", false))
+}
+
+fn upload_internal() -> Step<Use> {
+ Step::new("Upload to internal testing")
+ .uses(
+ "r0adkll",
+ "upload-google-play",
+ "e738b9dd8f2476ea806d921b64aacd24f34515a5",
+ ) // v1
+ .add_with((
+ "serviceAccountJson",
+ "${{ steps.auth.outputs.credentials_file_path }}",
+ ))
+ .add_with(("packageName", "com.macro.workspace.mobile"))
+ .add_with(("releaseFiles", "${{ steps.artifact.outputs.bundle }}"))
+ .add_with(("mappingFile", "${{ steps.artifact.outputs.mapping }}"))
+ .add_with(("releaseName", "${{ steps.metadata.outputs.release_name }}"))
+ .add_with(("track", "internal"))
+ .add_with(("status", "completed"))
+ .add_with(("whatsNewDirectory", "${{ runner.temp }}/whatsnew"))
+}
+
+/// Internal → production, full rollout. Play can take a moment to show the
+/// internal release in a fresh edit, so the promotion is retried briefly.
+fn promote_production() -> Step<Run> {
+ Step::new("Promote to production")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ for attempt in 1 2 3 4 5; do
+ if node scripts/android-play-promote.mjs; then
+ exit 0
+ fi
+ echo "Promotion attempt ${attempt} failed; retrying in 30s."
+ sleep 30
+ done
+ echo "Could not promote version code ${VERSION_CODE} to production; promote it by hand with publish-android-play.yml (operation=promote-production)." >&2
+ exit 1
+ "#})
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("GOOGLE_PLAY_ACCESS_TOKEN", "${{ steps.auth.outputs.access_token }}"))
+ .add_env(("VERSION_CODE", "${{ steps.preconditions.outputs.version_code }}"))
+ .add_env(("CHANGES_NOT_SENT_FOR_REVIEW", "false"))
+}
+
+fn remove_signing_material() -> Step<Run> {
+ Step::new("Remove signing material")
+ .run(indoc::indoc! {r#"
+ rm -rf "$RUNNER_TEMP/android-signing" "$RUNNER_TEMP/android-release.json" \
+ "$RUNNER_TEMP/android-google-services.json" "$RUNNER_TEMP/whatsnew" || true
+ rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties || true
+ "#})
+ .if_condition(Expression::new("always()"))
+ .shell("bash")
+}
+
+fn pr_comment() -> Step<Use> {
+ Step::new("Comment on the PR")
+ .uses(
+ "actions",
+ "github-script",
+ "f28e40c7f34bde8b3046d885e986cb6290c5673b",
+ )
+ // Not `always()`: a run the drift workflow cancelled must not post
+ // "failed, re-add the label" next to drift's own comment.
+ .if_condition(Expression::new("success() || failure()"))
+ .add_with(("github-token", "${{ secrets.GITHUB_TOKEN }}"))
+ .add_with((
+ "script",
+ indoc::indoc! {r#"
+ const versionCode = '${{ steps.preconditions.outputs.version_code }}' || '?';
+ const releaseName = '${{ steps.metadata.outputs.release_name }}' || `version code ${versionCode}`;
+ const runUrl =
+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` +
+ `/actions/runs/${context.runId}`;
+ const success = '${{ job.status }}' === 'success';
+ const body = success
+ ? [
+ `🤖 Android ${releaseName} was uploaded to Google Play internal testing and submitted for a full production rollout.`,
+ '',
+ 'When Google approves it, the version goes live, the **Android Release Watch** workflow',
+ 're-runs the **Android Native Check** on this PR within half an hour of that, and the PR',
+ 'becomes mergeable. To merge it the moment that happens, click **Enable auto-merge** on this PR now (squash).',
+ 'After merge, the next prod deploy applies the Android native build floor committed in `min-native-build.json`.',
+ '',
+ `[Workflow run](${runUrl})`,
+ ].join('\n')
+ : [
+ `🤖 Android Play release for ${releaseName} **failed** — see the [workflow run](${runUrl}).`,
+ '',
+ 'Fix the problem, then remove and re-add the `android-update` label to retry.',
+ ].join('\n');
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ body,
+ });
+ "#},
+ ))
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
new file mode 100644
index 0000000000..d1da14fd14
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs
@@ -0,0 +1,197 @@
+//! `Android Release Drift` — runs on every push to a PR that carries the
+//! `android-update` label, i.e. a PR whose Android bundle is (or is about to
+//! be) on Google Play. Web-only pushes are fine: the embedded web bundle is
+//! replaced over the air after the merge. Native pushes make the bundle
+//! stale, so when the Android native code changed this workflow:
+//!
+//! 1. cancels any [`super::android_play_release`] run still building the
+//! old head and waits for it to stop,
+//! 2. removes the `android-update` label (which also stops
+//! [`super::android_release_watch`] watching the PR), and
+//! 3. comments what to do: bump, commit, re-add the label.
+//!
+//! Unlike App Store review, a Play production release cannot be withdrawn
+//! once submitted: if the stale bundle was already promoted, the comment
+//! says so loudly and the follow-up should ship as soon as possible. The
+//! iOS counterpart is [`super::ios_release_drift`].
+
+use gh_workflow::{
+ Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run, Step, Use,
+ Workflow,
+};
+
+use crate::workflows::{runners, steps};
+
+const CHANGED: &str = "steps.detect.outputs.changed == 'true'";
+
+/// Build the workflow.
+pub fn android_release_drift() -> Workflow {
+ Workflow::new("Android Release Drift")
+ .on(Event::default()
+ .pull_request(PullRequest::default().add_type(PullRequestType::Synchronize)))
+ .add_job("drift", drift_job())
+}
+
+fn drift_job() -> Job {
+ Job::default()
+ .name("Android Release Drift")
+ .cond(Expression::new(
+ "contains(github.event.pull_request.labels.*.name, 'android-update') && \
+ github.event.pull_request.head.repo.full_name == github.repository",
+ ))
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .timeout_minutes(15u32)
+ .permissions(
+ Permissions::default()
+ .actions(Level::Write)
+ .contents(Level::Read)
+ .id_token(Level::Write)
+ .pull_requests(Level::Write),
+ )
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
+ .add_step(steps::checkout(false, false))
+ .add_step(setup_bun())
+ .add_step(detect())
+ .add_step(cancel_release_runs())
+ .add_step(play_auth())
+ .add_step(play_status())
+ .add_step(remove_label())
+ .add_step(comment())
+}
+
+fn changed() -> Expression {
+ Expression::new(CHANGED)
+}
+
+fn setup_bun() -> Step<Use> {
+ Step::new("Setup Bun")
+ .uses(
+ "oven-sh",
+ "setup-bun",
+ "0c5077e51419868618aeaa5fe8019c62421857d6",
+ ) // v2.2.0
+ .add_with(("bun-version", "1.3.13"))
+}
+
+fn detect() -> Step<Run> {
+ Step::new("Detect Android native changes in this push")
+ .run(concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/android_release_drift.sh")
+ ))
+ .id("detect")
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("BEFORE_SHA", "${{ github.event.before }}"))
+ .add_env(("AFTER_SHA", "${{ github.event.after }}"))
+}
+
+fn cancel_release_runs() -> Step<Run> {
+ Step::new("Cancel in-progress release runs for this PR")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ runs=$(gh run list --repo "$GH_REPO" --workflow android-play-release.yml \
+ --branch "$HEAD_REF" --json databaseId,status \
+ --jq '.[] | select(.status == "queued" or .status == "in_progress" or .status == "waiting") | .databaseId')
+ if [[ -z "$runs" ]]; then
+ echo "No release run in progress."
+ exit 0
+ fi
+ for run_id in $runs; do
+ echo "Cancelling release run ${run_id} (it would upload a bundle of the old head)."
+ gh run cancel "$run_id" --repo "$GH_REPO" || true
+ done
+ deadline=$(( $(date +%s) + 180 ))
+ for run_id in $runs; do
+ while [[ "$(gh run view "$run_id" --repo "$GH_REPO" --json status --jq .status)" != "completed" ]]; do
+ if (( $(date +%s) > deadline )); then
+ echo "::warning::Release run ${run_id} is still not completed."
+ break
+ fi
+ sleep 10
+ done
+ done
+ "#})
+ .if_condition(changed())
+ .shell("bash")
+ .add_env(("HEAD_REF", "${{ github.event.pull_request.head.ref }}"))
+}
+
+fn play_auth() -> Step<Use> {
+ Step::new("Authenticate to Google Play")
+ .uses(
+ "google-github-actions",
+ "auth",
+ "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
+ ) // v3
+ .id("auth")
+ .if_condition(Expression::new(format!(
+ "{CHANGED} && steps.detect.outputs.version_code != ''"
+ )))
+ .add_with((
+ "workload_identity_provider",
+ "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
+ ))
+ .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
+ .add_with(("token_format", "access_token"))
+ .add_with((
+ "access_token_scopes",
+ "https://www.googleapis.com/auth/androidpublisher",
+ ))
+ .add_with(("create_credentials_file", false))
+ .add_with(("export_environment_variables", false))
+}
+
+/// Was the stale bundle already promoted to production (in review or
+/// published)? Nothing can withdraw it then.
+fn play_status() -> Step<Run> {
+ Step::new("Check whether the stale version code is already on Play")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" || true
+ "#})
+ .id("status")
+ .if_condition(Expression::new(format!(
+ "{CHANGED} && steps.detect.outputs.version_code != ''"
+ )))
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("VERSION_CODE", "${{ steps.detect.outputs.version_code }}"))
+ .add_env((
+ "GOOGLE_PLAY_ACCESS_TOKEN",
+ "${{ steps.auth.outputs.access_token }}",
+ ))
+}
+
+/// `always()`: even if the Play check failed, the label must come off and
+/// someone must be told.
+fn after_detect() -> Expression {
+ Expression::new(format!("always() && {CHANGED}"))
+}
+
+fn remove_label() -> Step<Run> {
+ Step::new("Remove the android-update label")
+ .run("gh pr edit \"$PR_NUMBER\" --repo \"$GH_REPO\" --remove-label android-update")
+ .if_condition(after_detect())
+ .shell("bash")
+}
+
+fn comment() -> Step<Run> {
+ Step::new("Comment on the PR")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ bump='cd apps/web && just android-bump'
+ if [[ "$PROMOTED" == "true" ]]; then
+ body="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."
+ else
+ body="🤖 Android native code changed after this PR's Play release started, so the release was stopped: any in-progress build was cancelled and the \`android-update\` label removed. If a bundle already reached the internal track it stays there (internal testers only). When the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."
+ fi
+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"
+ "#})
+ .if_condition(after_detect())
+ .shell("bash")
+ .add_env(("PROMOTED", "${{ steps.status.outputs.promoted }}"))
+ .add_env(("VERSION_CODE", "${{ steps.detect.outputs.version_code }}"))
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
new file mode 100644
index 0000000000..dabe385e31
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_watch.rs
@@ -0,0 +1,121 @@
+//! `Android Release Watch` — half-hourly cron closing the loop of the
+//! `Android Native Check` gate (a job of [`super::web_app_check_main`]): that
+//! check fails on a PR with Android native changes until the version code is
+//! live on Google Play production, and nothing on GitHub's side notices when
+//! Google releases it. This workflow looks at every open PR labeled
+//! `android-update` (the label that started the
+//! [`super::android_play_release`] run), asks Play whether the version code
+//! committed at the PR head is live (built from the native code of the PR's
+//! merge result, like the gate checks), and when it is, re-runs the PR's
+//! failed `Android Native Check` job so the gate turns green on its own.
+//! Re-running an existing job is how this stays within GitHub's rule that
+//! events created with the workflow token never start workflows. The iOS
+//! counterpart is [`super::ios_release_watch`].
+
+use gh_workflow::{
+ Event, Expression, Job, Level, Permissions, Run, Schedule, Step, Use, Workflow,
+ WorkflowDispatch,
+};
+
+use crate::workflows::{runners, steps};
+
+const HAS_PRS: &str = "steps.prs.outputs.count != '0'";
+
+/// Build the workflow.
+pub fn android_release_watch() -> Workflow {
+ Workflow::new("Android Release Watch")
+ .on(Event::default()
+ .add_schedule(Schedule::new("*/30 * * * *"))
+ .workflow_dispatch(WorkflowDispatch::default()))
+ .permissions(
+ Permissions::default()
+ .actions(Level::Write)
+ .contents(Level::Read)
+ .id_token(Level::Write)
+ .pull_requests(Level::Write),
+ )
+ .add_job("watch", watch_job())
+}
+
+fn watch_job() -> Job {
+ Job::default()
+ .name("Re-run the Android Native Check once the Play release is live")
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .timeout_minutes(15u32)
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_step(find_prs())
+ .add_step(steps::checkout(false, false).if_condition(gated()))
+ .add_step(setup_bun())
+ .add_step(play_auth())
+ .add_step(rerun_live_checks())
+}
+
+fn gated() -> Expression {
+ Expression::new(HAS_PRS)
+}
+
+fn find_prs() -> Step<Run> {
+ Step::new("Find PRs waiting on a Play release")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ prs=$(gh pr list --repo "$GH_REPO" --label android-update --state open \
+ --json number,headRefOid,potentialMergeCommit \
+ --jq 'map({number, sha: .headRefOid, merge: .potentialMergeCommit.oid})' | jq -c .)
+ count=$(jq 'length' <<<"$prs")
+ echo "Open PRs labeled android-update: ${count}"
+ echo "prs=${prs}" >> "$GITHUB_OUTPUT"
+ echo "count=${count}" >> "$GITHUB_OUTPUT"
+ "#})
+ .id("prs")
+ .shell("bash")
+}
+
+fn setup_bun() -> Step<Use> {
+ Step::new("Setup Bun")
+ .uses(
+ "oven-sh",
+ "setup-bun",
+ "0c5077e51419868618aeaa5fe8019c62421857d6",
+ ) // v2.2.0
+ .if_condition(gated())
+ .add_with(("bun-version", "1.3.13"))
+}
+
+fn play_auth() -> Step<Use> {
+ Step::new("Authenticate to Google Play")
+ .uses(
+ "google-github-actions",
+ "auth",
+ "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
+ ) // v3
+ .id("auth")
+ .if_condition(gated())
+ .add_with((
+ "workload_identity_provider",
+ "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
+ ))
+ .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
+ .add_with(("token_format", "access_token"))
+ .add_with((
+ "access_token_scopes",
+ "https://www.googleapis.com/auth/androidpublisher",
+ ))
+ .add_with(("create_credentials_file", false))
+ .add_with(("export_environment_variables", false))
+}
+
+fn rerun_live_checks() -> Step<Run> {
+ Step::new("Re-run the check on PRs whose release is live")
+ .run(concat!(
+ include_str!("scripts/android_git_fetch.sh"),
+ include_str!("scripts/android_release_watch.sh")
+ ))
+ .shell("bash")
+ .if_condition(gated())
+ .add_env(("PRS", "${{ steps.prs.outputs.prs }}"))
+ .add_env((
+ "GOOGLE_PLAY_ACCESS_TOKEN",
+ "${{ steps.auth.outputs.access_token }}",
+ ))
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs
index f2a61ed85b..e64240b1b2 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs
@@ -91,6 +91,7 @@ fn preconditions() -> Step<Run> {
Step::new("Require the PR to be ready to merge")
.run(concat!(
include_str!("scripts/ios_native_tree.sh"),
+ include_str!("scripts/pr_merge_commit.sh"),
include_str!("scripts/ios_release_preconditions.sh")
))
.shell("bash")
@@ -123,6 +124,7 @@ fn head_guard() -> Step<Run> {
Step::new("Require the PR's native code to be unchanged since the build")
.run(concat!(
include_str!("scripts/ios_native_tree.sh"),
+ include_str!("scripts/pr_merge_commit.sh"),
include_str!("scripts/ios_release_head_guard.sh")
))
.shell("bash")
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rs
deleted file mode 100644
index 5eb1f41111..0000000000
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-//! `iOS Native Check Label` — re-runs the `iOS Native Check` job of the web
-//! app PR checks when the `skip-ios-update` label is added to or removed from
-//! a PR. The gate lives in that workflow (so the required `Web App Status
-//! Check` covers it), and re-running the whole web suite on every label
-//! event would be wasteful, so this re-runs just the one job; GitHub re-runs
-//! the status check that depends on it. A run still in progress saw the
-//! labels as they were when it started, so it is waited for first; a run
-//! cancelled by a later push, or a head that has since moved, is left alone
-//! (the newer run reads the labels itself). This job is not a required
-//! check: it can take up to 25 minutes while waiting, and the release
-//! preconditions ignore it.
-
-use gh_workflow::{
- Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Step, Workflow,
-};
-
-use crate::workflows::runners;
-
-/// Build the workflow.
-pub fn ios_native_check_label() -> Workflow {
- Workflow::new("iOS Native Check Label")
- .on(Event::default().pull_request(
- PullRequest::default()
- .add_branch("main")
- .add_type(PullRequestType::Labeled)
- .add_type(PullRequestType::Unlabeled),
- ))
- .add_job("rerun", rerun_job())
-}
-
-fn rerun_job() -> Job {
- Job::default()
- .name("Re-run the iOS Native Check")
- // Fork PRs get a read-only token, which cannot re-run jobs.
- .cond(Expression::new(
- "github.event.label.name == 'skip-ios-update' && \
- github.event.pull_request.head.repo.full_name == github.repository",
- ))
- .runs_on(runners::Runner::TinyNoCache.to_string())
- .timeout_minutes(30u32)
- .permissions(
- Permissions::default()
- .actions(Level::Write)
- .pull_requests(Level::Read),
- )
- .add_env(("GH_TOKEN", "${{ github.token }}"))
- .add_env(("GH_REPO", "${{ github.repository }}"))
- .add_env(("HEAD_SHA", "${{ github.event.pull_request.head.sha }}"))
- .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
- .add_step(
- Step::new("Re-run the gate job for this head")
- .run(include_str!("scripts/ios_native_check_rerun.sh"))
- .shell("bash"),
- )
-}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/native_check_label.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/native_check_label.rs
new file mode 100644
index 0000000000..b53dd9e9c1
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/native_check_label.rs
@@ -0,0 +1,59 @@
+//! `Native Check Label` — re-runs the `iOS Native Check` or `Android Native
+//! Check` job of the web app PR checks when the matching `skip-ios-update` /
+//! `skip-android-update` label is added to or removed from a PR. The gates
+//! live in that workflow (so the required `Web App Status Check` covers
+//! them), and re-running the whole web suite on every label event would be
+//! wasteful, so this re-runs just the one job; GitHub re-runs the status
+//! check that depends on it. A run still in progress saw the labels as they
+//! were when it started, so it is waited for first; a run cancelled by a
+//! later push, or a head that has since moved, is left alone (the newer run
+//! reads the labels itself). This job is not a required check: it can take
+//! up to 25 minutes while waiting, and the release preconditions ignore it.
+
+use gh_workflow::{
+ Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Step, Workflow,
+};
+
+use crate::workflows::runners;
+
+/// Build the workflow.
+pub fn native_check_label() -> Workflow {
+ Workflow::new("Native Check Label")
+ .on(Event::default().pull_request(
+ PullRequest::default()
+ .add_branch("main")
+ .add_type(PullRequestType::Labeled)
+ .add_type(PullRequestType::Unlabeled),
+ ))
+ .add_job("rerun", rerun_job())
+}
+
+fn rerun_job() -> Job {
+ Job::default()
+ .name("Re-run the native check")
+ // Fork PRs get a read-only token, which cannot re-run jobs.
+ .cond(Expression::new(
+ "(github.event.label.name == 'skip-ios-update' || github.event.label.name == 'skip-android-update') && \
+ github.event.pull_request.head.repo.full_name == github.repository",
+ ))
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .timeout_minutes(30u32)
+ .permissions(
+ Permissions::default()
+ .actions(Level::Write)
+ .pull_requests(Level::Read),
+ )
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("HEAD_SHA", "${{ github.event.pull_request.head.sha }}"))
+ .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
+ .add_env((
+ "JOB_NAME",
+ "${{ github.event.label.name == 'skip-ios-update' && 'iOS Native Check' || 'Android Native Check' }}",
+ ))
+ .add_step(
+ Step::new("Re-run the gate job for this head")
+ .run(include_str!("scripts/native_check_rerun.sh"))
+ .shell("bash"),
+ )
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh
new file mode 100644
index 0000000000..34574b63c8
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh
@@ -0,0 +1,12 @@
+# --- authenticated fetch ------------------------------------------------------
+# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base
+# commit, a moved PR head, GitHub's test merge commit) available. Checkouts
+# here don't persist credentials, so authenticate the way actions/checkout
+# does. Fails if the commit is unreachable (a force-pushed-away head).
+gh_fetch() {
+ local auth
+ auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')
+ git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \
+ fetch -q --depth=1 origin "$1"
+}
+# ------------------------------------------------------------------------------
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh
new file mode 100644
index 0000000000..b4969d3b4b
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh
@@ -0,0 +1,30 @@
+set -euo pipefail
+# A push landed on a PR that carries android-update. Compare the Android native
+# code before and after the push. Only native changes matter — web-only
+# commits ship over the air after the merge. A force-push that discarded the
+# old head counts as changed: nothing proves the released bundle still matches.
+if gh_fetch "$BEFORE_SHA" && before=$(bun scripts/android-native.mjs hash "$BEFORE_SHA"); then :; else
+ before=unknown
+fi
+gh_fetch "$AFTER_SHA"
+after=$(bun scripts/android-native.mjs hash "$AFTER_SHA")
+echo "native hash before: ${before}"
+echo "native hash after: ${after}"
+if [[ "$before" == "$after" ]]; then
+ echo "changed=false" >> "$GITHUB_OUTPUT"
+ echo "No Android native changes in this push; the release stays valid."
+else
+ echo "changed=true" >> "$GITHUB_OUTPUT"
+ # The version code that may already be on Play is the old head's. After a
+ # force-push the old head is gone; the new head's code is the best guess (a
+ # push rarely changes it), and it keeps the Play check running — that
+ # check is what tells the author a stale bundle is already in production.
+ if [[ "$before" != unknown ]]; then
+ released=$BEFORE_SHA
+ else
+ released=$AFTER_SHA
+ echo "The previous head is unreachable (force-push); checking Play for the current head's version code instead."
+ fi
+ echo "version_code=$(bun scripts/android-native.mjs version-code "$released")" >> "$GITHUB_OUTPUT"
+ echo "Android native code changed; the released bundle is stale."
+fi
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh
new file mode 100644
index 0000000000..ddbe0928ce
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_head_guard.sh
@@ -0,0 +1,32 @@
+set -euo pipefail
+# Last check before uploading: the bundle must still describe the native code
+# the merge gate will hash — that of the PR's merge result — or it could never
+# pass the gate, and a promoted Play release cannot be withdrawn. Two things
+# can move while a build runs: the PR head (a native push; the drift workflow
+# cancels runs after the fact, but better not to upload at all) and main
+# (another Android PR merged).
+built=$(bun scripts/android-native.mjs hash HEAD)
+head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
+if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
+ echo "PR head unchanged (${head_sha:0:10}); native hash ${built:0:10} is current."
+else
+ gh_fetch "$head_sha"
+ current=$(bun scripts/android-native.mjs hash "$head_sha")
+ if [[ "$current" != "$built" ]]; then
+ echo "Android native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(${built:0:10} → ${current:0:10}). Not uploading the stale bundle." >&2
+ echo "Re-add the android-update label to release the current head." >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its Android native code is unchanged (${built:0:10})."
+fi
+merge=$(pr_merge_commit)
+gh_fetch "$merge"
+merged=$(bun scripts/android-native.mjs hash "$merge")
+if [[ "$merged" != "$built" ]]; then
+ echo "Android native code landed on main while this release was building: the merge result" \
+ "(${merge:0:10}) hashes ${merged:0:10}, the bundle ${built:0:10}. Not uploading a bundle the merge gate could never accept." >&2
+ echo "Merge main into the PR, bump (cd apps/web && just android-bump), commit, and re-add the android-update label." >&2
+ exit 1
+fi
+echo "Merge result ${merge:0:10} matches the built native code (${built:0:10}); uploading."
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh
new file mode 100644
index 0000000000..aad0f97eef
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_preconditions.sh
@@ -0,0 +1,74 @@
+set -euo pipefail
+# The android-update label means "release this and merge it when it is live",
+# so refuse to start unless the PR is in a mergeable state: not a draft, the
+# Android native code actually changed with a version code bump, and every
+# other check on the head commit passing (pending ones are waited on). Our own
+# checks are excluded: the native check is expected to be red until the
+# release is live.
+pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json isDraft,headRefOid,baseRefOid)
+if [[ "$(jq -r '.isDraft' <<<"$pr_json")" == "true" ]]; then
+ echo "PR #${PR_NUMBER} is a draft; mark it ready for review before adding android-update." >&2
+ exit 1
+fi
+head_sha=$(jq -r '.headRefOid' <<<"$pr_json")
+base_sha=$(jq -r '.baseRefOid' <<<"$pr_json")
+if [[ "$head_sha" != "$HEAD_SHA" ]]; then
+ # Pushed since the label event. Web-only commits are fine (they ship over
+ # the air after the merge); native ones would make this build stale.
+ gh_fetch "$head_sha"
+ if [[ "$(bun scripts/android-native.mjs hash "$head_sha")" != "$(bun scripts/android-native.mjs hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER} got Android native changes since this run started (${HEAD_SHA:0:10} → ${head_sha:0:10});" \
+ "re-add android-update on the current head." >&2
+ exit 1
+ fi
+ echo "PR #${PR_NUMBER} moved to ${head_sha:0:10} since this run started, but its Android native code is unchanged; continuing."
+fi
+
+# The version code must be bumped against the base, and something native
+# must actually have changed — there is nothing to release otherwise.
+gh_fetch "$base_sha"
+outputs=$(mktemp)
+GITHUB_OUTPUT="$outputs" bun scripts/android-version-check.mjs "$base_sha"
+if [[ "$(sed -n 's/^changed=//p' "$outputs")" != "true" ]]; then
+ echo "PR #${PR_NUMBER} has no Android native changes against its base; nothing to release (remove the android-update label)." >&2
+ exit 1
+fi
+version_code=$(sed -n 's/^version_code=//p' "$outputs")
+
+# The gate compares the release stamp with the native hash of the PR's merge
+# result, not of its head. A head that lacks Android native code main gained
+# since the PR branched would be released but could never pass the gate — and
+# a Play release cannot be withdrawn. Refuse before the build instead.
+merge=$(pr_merge_commit)
+gh_fetch "$merge"
+if [[ "$(bun scripts/android-native.mjs hash "$merge")" != "$(bun scripts/android-native.mjs hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER}'s merge result (${merge:0:10}) has Android native code this head lacks: main changed native code since the PR branched." \
+ "Merge main into the PR, bump (cd apps/web && just android-bump), commit, and re-add android-update." >&2
+ exit 1
+fi
+echo "version_code=${version_code}" >> "$GITHUB_OUTPUT"
+echo "Releasing Android version code ${version_code} (native hash matches the merge result ${merge:0:10})."
+
+# (`gh pr checks` names are job names, not workflow names.)
+ours='^(Android Native Check|Android Play Release|Re-run the native check|Web App Status Check|Android Release Drift|iOS Native Check)'
+deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
+while true; do
+ checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
+ | jq -c --arg ours "$ours" '[.[] | select(.name | test($ours) | not)]')
+ failing=$(jq -r '[.[] | select(.bucket == "fail" or .bucket == "cancel") | .name] | join(", ")' <<<"$checks")
+ pending=$(jq -r '[.[] | select(.bucket == "pending") | .name] | join(", ")' <<<"$checks")
+ if [[ -n "$failing" ]]; then
+ echo "PR #${PR_NUMBER} has failing checks: ${failing}. Get the PR green, then re-add android-update." >&2
+ exit 1
+ fi
+ if [[ -z "$pending" ]]; then
+ echo "All other checks on ${head_sha:0:10} pass ($(jq 'length' <<<"$checks") checks)."
+ exit 0
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "Checks still pending after ${WAIT_MINUTES} minutes: ${pending}. Re-add android-update once they pass." >&2
+ exit 1
+ fi
+ echo "Waiting for: ${pending}"
+ sleep 60
+done
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh
new file mode 100644
index 0000000000..55faa6c4ac
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_watch.sh
@@ -0,0 +1,91 @@
+set -euo pipefail
+# For each open PR labeled `android-update` (PRS: [{number, sha, merge}]), ask
+# Google Play whether the version code committed at the PR head is live on
+# production, built from the Android native code of the PR's merge result
+# (`merge` is GitHub's test merge commit; the gate hashes the same). When it
+# is, and the PR's latest `Android Native Check` job (of the web app PR checks
+# run) failed — it fails until the release is live — re-run that job so the
+# gate, and the `Web App Status Check` that depends on it, go green without
+# anyone clicking "Re-run". GH_TOKEN needs actions:write + pull-requests:write;
+# GOOGLE_PLAY_ACCESS_TOKEN the androidpublisher scope.
+cd apps/web
+conf_path="apps/web/tauri/src-tauri/tauri.android.conf.json"
+
+check_pr() {
+ local pr=$1 number sha merge native_hash version_code run run_id status run_url job conclusion job_id reruns
+ number=$(jq -r '.number' <<<"$pr")
+ sha=$(jq -r '.sha' <<<"$pr")
+ merge=$(jq -r '.merge // empty' <<<"$pr")
+ if [[ -z "$merge" ]]; then
+ echo "PR #${number}: no merge commit (conflicts with main?); cannot check the merge result"
+ return 0
+ fi
+ version_code=$(gh api "repos/${GH_REPO}/contents/${conf_path}?ref=${sha}" --jq '.content' | base64 --decode | jq -r '.bundle.android.versionCode')
+ gh_fetch "$merge"
+ native_hash=$(bun scripts/android-native.mjs hash "$merge")
+ echo "PR #${number}: Android version code ${version_code} at ${sha:0:10}, merge-result native hash ${native_hash:0:10}"
+
+ if ! bun scripts/android-play-status.mjs --version-code "$version_code" --require-live \
+ --native-hash "$native_hash" --pr "$number" >"$RUNNER_TEMP/status-${number}.log" 2>&1; then
+ echo " not live yet:"
+ sed 's/^/ /' "$RUNNER_TEMP/status-${number}.log"
+ return 0
+ fi
+ echo " live on Google Play production"
+
+ run=$(gh run list --workflow web-app-check-main.yml --commit "$sha" \
+ --json databaseId,status,url --limit 1 --jq '.[0] // empty')
+ if [[ -z "$run" ]]; then
+ echo " no Web App Pr Checks run for this commit; skipping"
+ return 0
+ fi
+ run_id=$(jq -r '.databaseId' <<<"$run")
+ status=$(jq -r '.status' <<<"$run")
+ run_url=$(jq -r '.url' <<<"$run")
+ if [[ "$status" != "completed" ]]; then
+ echo " Web App Pr Checks run ${run_id} is ${status}; skipping"
+ return 0
+ fi
+ job=$(gh run view "$run_id" --json jobs \
+ --jq '.jobs[] | select(.name == "Android Native Check") | {id: .databaseId, conclusion}')
+ if [[ -z "$job" ]]; then
+ echo " run ${run_id} has no Android Native Check job; skipping"
+ return 0
+ fi
+ job_id=$(jq -r '.id' <<<"$job")
+ conclusion=$(jq -r '.conclusion' <<<"$job")
+ if [[ "$conclusion" == "success" ]]; then
+ echo " Android Native Check already passed"
+ return 0
+ fi
+ if [[ "$conclusion" != "failure" ]]; then
+ echo " Android Native Check job concluded ${conclusion}; leaving it alone"
+ return 0
+ fi
+ # If our re-run also fails something else is wrong (the job's log says
+ # what), so stop after two rather than retrying every half hour forever.
+ reruns=$(gh pr view "$number" --json comments --jq \
+ "[.comments[].body | select(contains(\"Re-ran the **Android Native Check**\")) | select(contains(\"version code ${version_code}\"))] | length")
+ if (( reruns >= 2 )); then
+ echo " Android Native Check already re-run ${reruns} times and still failing; not re-running again — see ${run_url}"
+ return 0
+ fi
+ echo " re-running Android Native Check (job ${job_id} of run ${run_id}; ${reruns} automatic re-runs so far)"
+ gh run rerun --job "$job_id"
+ gh pr comment "$number" --body "🤖 Android version code ${version_code} is live on Google Play. Re-ran the **Android Native Check** ([run](${run_url})); this PR can merge once it passes."
+}
+
+# One PR's API hiccup must not stop the others from being checked this
+# half hour: each PR runs in its own errexit subshell.
+failed=0
+while read -r pr; do
+ set +e
+ ( set -e; check_pr "$pr" )
+ rc=$?
+ set -e
+ if (( rc != 0 )); then
+ echo " error while checking PR $(jq -r '.number' <<<"$pr") (exit ${rc}); continuing"
+ failed=1
+ fi
+done < <(jq -c '.[]' <<<"$PRS")
+exit $failed
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_live.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_live.sh
index 65c961bb20..13b5a7c53c 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_live.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_live.sh
@@ -1,25 +1,7 @@
set -euo pipefail
# The gate proper: the committed version + build must be live, built from the
-# native code of the PR's current merge result. GitHub computes that merge
-# commit lazily (mergeable=UNKNOWN until it has), so poll for it a little; a
-# PR that really conflicts with main cannot merge anyway.
-deadline=$(( $(date +%s) + 120 ))
-while true; do
- pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
- mergeable=$(jq -r '.mergeable' <<<"$pr_json")
- merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
- [[ -n "$merge" ]] && break
- if [[ "$mergeable" == "CONFLICTING" ]]; then
- echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
- exit 1
- fi
- if (( $(date +%s) > deadline )); then
- echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); re-run this job in a minute." >&2
- exit 1
- fi
- echo "Merge commit not computed yet (mergeable=${mergeable}); waiting."
- sleep 10
-done
+# native code of the PR's current merge result.
+merge=$(pr_merge_commit)
native_tree_fetch "$merge"
native_tree=$(native_tree_hash "$merge")
echo "Merge result ${merge:0:10}: native tree ${native_tree}"
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_head_guard.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_head_guard.sh
index a8eb45bc60..a2d6b9453a 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_head_guard.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_head_guard.sh
@@ -1,24 +1,34 @@
set -euo pipefail
-# Last check before submitting for review: native code pushed to the PR while
-# this run was building would make the uploaded build stale. The drift
-# workflow withdraws submissions after the fact, but better not to submit at
-# all. Compares the native tree of the PR's current head with the tree that
-# was built (this checkout is the head the run started from).
+# Last check before submitting for review: the uploaded build must still
+# describe the native tree the merge gate will hash — that of the PR's merge
+# result — or it could never pass the gate. Two things can move while a build
+# runs: the PR head (a native push; the drift workflow withdraws submissions
+# after the fact, but better not to submit at all) and main (another iOS PR
+# merged). This checkout is the head the run started from.
built_tree=$(native_tree_hash HEAD)
built=$(jq -r '.bundle.iOS.bundleVersion' apps/web/tauri/src-tauri/tauri.ios.conf.json)
+bump='doppler run --project ios-release --config prd -- just ios-bump'
head_sha=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
if [[ "$head_sha" == "$(git rev-parse HEAD)" ]]; then
echo "PR head unchanged (${head_sha:0:10}); native tree ${built_tree:0:10} is current."
- exit 0
+else
+ native_tree_fetch "$head_sha"
+ head_tree=$(native_tree_hash "$head_sha")
+ if [[ "$head_tree" != "$built_tree" ]]; then
+ echo "Native code changed on PR #${PR_NUMBER} while this release was building" \
+ "(tree ${built_tree:0:10} → ${head_tree:0:10}). Not submitting the stale build ${built}." >&2
+ echo "Bump (${bump}), commit, and re-add the ios-update label to release the current head." >&2
+ exit 1
+ fi
+ echo "PR head moved to ${head_sha:0:10} but its native tree is still ${built_tree:0:10}."
fi
-native_tree_fetch "$head_sha"
-head_tree=$(native_tree_hash "$head_sha")
-if [[ "$head_tree" == "$built_tree" ]]; then
- echo "PR head moved to ${head_sha:0:10} but its native tree is still ${built_tree:0:10}; submitting."
- exit 0
+merge=$(pr_merge_commit)
+native_tree_fetch "$merge"
+merged_tree=$(native_tree_hash "$merge")
+if [[ "$merged_tree" != "$built_tree" ]]; then
+ echo "iOS native code landed on main while this release was building: the merge result" \
+ "(${merge:0:10}) hashes ${merged_tree:0:10}, build ${built} ${built_tree:0:10}. Not submitting a build the merge gate could never accept." >&2
+ echo "Merge main into the PR, bump (${bump}), commit, and re-add the ios-update label." >&2
+ exit 1
fi
-echo "Native code changed on PR #${PR_NUMBER} while this release was building" \
- "(tree ${built_tree:0:10} → ${head_tree:0:10}). Not submitting the stale build ${built}." >&2
-echo "Bump (doppler run --project ios-release --config prd -- just ios-bump), commit," \
- "and re-add the ios-update label to release the current head." >&2
-exit 1
+echo "Merge result ${merge:0:10} matches the built native tree (${built_tree:0:10}); submitting."
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_preconditions.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_preconditions.sh
index ed1a1ddf24..69d42a7df3 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_preconditions.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_preconditions.sh
@@ -23,10 +23,22 @@ if [[ "$head_sha" != "$HEAD_SHA" ]]; then
echo "PR #${PR_NUMBER} moved to ${head_sha:0:10} since this run started, but its native code is unchanged; continuing."
fi
+# The gate compares the build's stamp with the native tree of the PR's merge
+# result, not of its head. A head that lacks iOS native code main gained since
+# the PR branched would go through App Review but could never pass the gate.
+merge=$(pr_merge_commit)
+native_tree_fetch "$merge"
+if [[ "$(native_tree_hash "$merge")" != "$(native_tree_hash HEAD)" ]]; then
+ echo "PR #${PR_NUMBER}'s merge result (${merge:0:10}) has iOS native code this head lacks: main changed native code since the PR branched." \
+ "Merge main into the PR, bump (doppler run --project ios-release --config prd -- just ios-bump), commit, and re-add ios-update." >&2
+ exit 1
+fi
+echo "Native tree matches the merge result ${merge:0:10}."
+
# Web App Status Check aggregates the gate, so it is red whenever the gate is;
# its other inputs (Typecheck, Test, Build, ...) are separate checks and stay.
# (`gh pr checks` names are job names, not workflow names.)
-ours='^(iOS Native Check|Re-run the iOS Native Check|Web App Status Check|iOS App Store Release|iOS Release Drift)'
+ours='^(iOS Native Check|Re-run the native check|Web App Status Check|iOS App Store Release|iOS Release Drift|Android Native Check)'
deadline=$(( $(date +%s) + WAIT_MINUTES * 60 ))
while true; do
checks=$(gh pr checks "$PR_NUMBER" --repo "$GH_REPO" --json name,bucket \
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_rerun.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/native_check_rerun.sh
similarity index 71%
rename from tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_rerun.sh
rename to tooling/xtask/crates/xtask_workflows/src/workflows/scripts/native_check_rerun.sh
index 016435bad3..9790ba9025 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_rerun.sh
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/native_check_rerun.sh
@@ -1,9 +1,8 @@
set -euo pipefail
-# Re-run the `iOS Native Check` job of the web app PR checks run for
-# $HEAD_SHA (waiting for that run to finish first: a run in progress saw the
-# labels as they were when it started). GitHub re-runs the dependent
-# `Web App Status Check` with it.
-# A push after the label event starts a fresh run that reads the labels
+# Re-run the $JOB_NAME job of the web app PR checks run for $HEAD_SHA (waiting
+# for that run to finish first: a run in progress saw the labels as they were
+# when it started). GitHub re-runs the dependent `Web App Status Check` with
+# it. A push after the label event starts a fresh run that reads the labels
# itself, and would also have cancelled this head's run (the web suite
# cancels in-progress runs per PR): nothing to re-run then.
current=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json headRefOid --jq '.headRefOid')
@@ -29,17 +28,17 @@ while true; do
break
fi
if (( $(date +%s) > deadline )); then
- echo "Run ${run_id} is still ${status}; giving up. Re-run the iOS Native Check job by hand." >&2
+ echo "Run ${run_id} is still ${status}; giving up. Re-run the ${JOB_NAME} job by hand." >&2
exit 1
fi
echo "Run ${run_id} is ${status}; waiting for it to finish before re-running the gate."
sleep 30
done
job_id=$(gh run view "$run_id" --repo "$GH_REPO" --json jobs \
- --jq '.jobs[] | select(.name == "iOS Native Check") | .databaseId')
+ --jq ".jobs[] | select(.name == \"${JOB_NAME}\") | .databaseId")
if [[ -z "$job_id" ]]; then
- echo "Run ${run_id} has no iOS Native Check job; nothing to re-run."
+ echo "Run ${run_id} has no ${JOB_NAME} job; nothing to re-run."
exit 0
fi
-echo "Re-running iOS Native Check (job ${job_id} of run ${run_id}) with the current labels."
+echo "Re-running ${JOB_NAME} (job ${job_id} of run ${run_id}) with the current labels."
gh run rerun --repo "$GH_REPO" --job "$job_id"
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_merge_commit.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_merge_commit.sh
new file mode 100644
index 0000000000..a6eeda9caa
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/pr_merge_commit.sh
@@ -0,0 +1,30 @@
+# --- PR merge result ----------------------------------------------------------
+# pr_merge_commit: print the sha of GitHub's test merge commit for $PR_NUMBER —
+# the merge result the native gates hash. GitHub computes it lazily
+# (mergeable=UNKNOWN until it has), so poll a little; a PR that really
+# conflicts with its base cannot merge anyway. Needs GH_TOKEN, GH_REPO,
+# PR_NUMBER. Progress goes to stderr so `merge=$(pr_merge_commit)` works.
+pr_merge_commit() {
+ local deadline pr_json mergeable merge
+ deadline=$(( $(date +%s) + 120 ))
+ while true; do
+ pr_json=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json mergeable,potentialMergeCommit)
+ mergeable=$(jq -r '.mergeable' <<<"$pr_json")
+ merge=$(jq -r '.potentialMergeCommit.oid // empty' <<<"$pr_json")
+ if [[ -n "$merge" ]]; then
+ echo "$merge"
+ return 0
+ fi
+ if [[ "$mergeable" == "CONFLICTING" ]]; then
+ echo "::error::PR #${PR_NUMBER} conflicts with its base branch, so there is no merge result to check; resolve the conflicts first." >&2
+ return 1
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::GitHub has not computed PR #${PR_NUMBER}'s merge commit yet (mergeable=${mergeable}); retry in a minute." >&2
+ return 1
+ fi
+ echo "Merge commit not computed yet (mergeable=${mergeable}); waiting." >&2
+ sleep 10
+ done
+}
+# ------------------------------------------------------------------------------
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs
index 4732b5d44e..b4bf6d2740 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs
@@ -12,6 +12,7 @@ macro_rules! secret {
}
secret!(APPETIZE_API_TOKEN);
+secret!(ANDROID_RELEASE_DOPPLER_TOKEN);
secret!(AWS_ACCESS_KEY);
secret!(AWS_SECRET_ACCESS_KEY);
secret!(CLOUDFLARE_API_TOKEN);
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index fa5d41b099..a2d0eaa12c 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -2,8 +2,7 @@
//! Generated into `web-app-check-main.yml`.
use gh_workflow::{
- Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,
- Step, Use, Workflow,
+ Concurrency, Event, Expression, Job, PullRequest, PullRequestType, Run, Step, Use, Workflow,
};
use crate::workflows::{
@@ -12,6 +11,7 @@ use crate::workflows::{
vars,
};
+mod android_native_check;
mod ios_native_check;
#[cfg(test)]
mod test;
@@ -49,7 +49,7 @@ pub fn web_app_check_main() -> Workflow {
.cancel_in_progress(true),
)
.add_job("path-check", path_check())
- .add_job("android-version", android_version())
+ .add_job(android_native_check::JOB_ID, android_native_check())
.add_job("typescript", typescript())
.add_job("generated-code", generated_code())
.add_job("biome-check", biome_check())
@@ -62,33 +62,8 @@ pub fn web_app_check_main() -> Workflow {
/// Always run so the required collector can distinguish a successful native
/// check from a cancelled or skipped one, including frontend/backend-only PRs.
-fn android_version() -> Job {
- Job::default()
- .name("Android Version Code")
- .runs_on(runners::Runner::TinyNoCache.to_string())
- .permissions(Permissions::default().contents(Level::Read))
- // Shallow: only the merge result and the base commit are needed.
- .add_step(checkout("Checkout PR merge commit", false))
- .add_step(
- Step::new("Setup Bun")
- .uses(
- "oven-sh",
- "setup-bun",
- "0c5077e51419868618aeaa5fe8019c62421857d6",
- ) // v2.2.0
- .add_with(("bun-version", "1.3.13")),
- )
- .add_step(
- Step::new("Require an Android version bump for native changes")
- .run(indoc::indoc! {r#"
- set -euo pipefail
- git fetch -q --depth=1 origin "$BASE_SHA"
- bun scripts/android-version-check.mjs "$BASE_SHA"
- "#})
- .shell("bash")
- .working_directory(xtask_paths::repo_dir!("apps/web"))
- .add_env(("BASE_SHA", "${{ github.event.pull_request.base.sha }}")),
- )
+fn android_native_check() -> Job {
+ android_native_check::job()
}
fn path_check() -> Job {
@@ -259,7 +234,7 @@ fn status_check() -> Job {
.cond(Expression::new("always()"))
.needs(vec![
"path-check".to_string(),
- "android-version".to_string(),
+ android_native_check::JOB_ID.to_string(),
"typescript".to_string(),
"generated-code".to_string(),
"biome-check".to_string(),
@@ -492,7 +467,7 @@ fn run_build() -> Step<Run> {
fn check_job_results() -> Step<Run> {
Step::new("Check job results").run(indoc::indoc! {r#"
echo "path-check: ${{ needs.path-check.result }}"
- echo "android-version: ${{ needs.android-version.result }}"
+ echo "android-native-check: ${{ needs.android-native-check.result }}"
echo "typescript: ${{ needs.typescript.result }}"
echo "generated-code: ${{ needs.generated-code.result }}"
echo "biome-check: ${{ needs.biome-check.result }}"
@@ -503,7 +478,7 @@ fn check_job_results() -> Step<Run> {
# Fail if any job failed (skipped and success are both OK). The iOS
# gate is the merge gate, so a cancelled gate is not OK either.
- if [[ "${{ needs.android-version.result }}" != "success" ]] || \
+ if [[ "${{ needs.android-native-check.result }}" != "success" ]] || \
[[ "${{ needs.path-check.result }}" == "failure" ]] || \
[[ "${{ needs.typescript.result }}" == "failure" ]] || \
[[ "${{ needs.generated-code.result }}" == "failure" ]] || \
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs
new file mode 100644
index 0000000000..e433d3c8b1
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/android_native_check.rs
@@ -0,0 +1,179 @@
+//! `Android Native Check` — merge gate for PRs that change Android native
+//! code, as a job of the web app PR checks so that `Web App Status Check`
+//! (the required status check) covers it. The twin of
+//! [`super::ios_native_check`]. The gate:
+//!
+//! 1. Requires an Android `versionCode` bump against the base branch when
+//! the Android native code changed (`scripts/android-version-check.mjs`,
+//! which shares its definition of "native code" with the release
+//! workflow through `android-native.mjs`: every tracked file under
+//! `apps/web/tauri` minus iOS/desktop-only paths, plus the client cache
+//! wasm version). This part always runs.
+//! 2. When it changed, asks Google Play whether that version code is a
+//! published production release (through review and rolled out) built
+//! from the native code of the PR's current merge result (the provenance
+//! stamp in the release notes),
+//! and fails with instructions otherwise — add the `android-update` label
+//! to run [`super::super::android_play_release`];
+//! [`super::super::android_release_watch`] re-runs this job once the
+//! release is live.
+//!
+//! Play access is keyless (Workload Identity Federation), so the job needs
+//! `id-token: write`; fork PRs don't get that and fail closed at the auth
+//! step. The `skip-android-update` label bypasses the live check for native
+//! changes that don't break the native/web contract; labels are read at run
+//! time (a re-run keeps the original event payload). The job name must stay
+//! stable: the release preconditions, the watcher and the label workflow
+//! find it by name.
+
+use gh_workflow::{Expression, Job, Level, Permissions, Run, Step, Use};
+
+use crate::workflows::runners;
+
+/// The job's id in the web app check workflow.
+pub(super) const JOB_ID: &str = "android-native-check";
+
+const NATIVE_CHANGED: &str = "steps.android-version.outputs.changed == 'true'";
+const NOT_SKIPPED: &str = "steps.labels.outputs.skip != 'true'";
+const SKIP_LABEL: &str = "steps.labels.outputs.skip == 'true'";
+
+pub(super) fn job() -> Job {
+ Job::default()
+ .name("Android Native Check")
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .permissions(
+ Permissions::default()
+ .contents(Level::Read)
+ .id_token(Level::Write)
+ .pull_requests(Level::Read),
+ )
+ .add_step(super::checkout("Checkout PR merge commit", false))
+ .add_step(setup_bun())
+ .add_step(version_check())
+ .add_step(read_labels())
+ .add_step(play_auth())
+ .add_step(require_live())
+ .add_step(skip_notice())
+}
+
+fn gated() -> Expression {
+ Expression::new(format!("{NATIVE_CHANGED} && {NOT_SKIPPED}"))
+}
+
+fn setup_bun() -> Step<Use> {
+ Step::new("Setup Bun")
+ .uses(
+ "oven-sh",
+ "setup-bun",
+ "0c5077e51419868618aeaa5fe8019c62421857d6",
+ ) // v2.2.0
+ .add_with(("bun-version", "1.3.13"))
+}
+
+/// Always runs: the version code must exceed the base whenever the Android
+/// native code changed. Outputs `changed` and `version_code`.
+///
+/// The base is the merge commit's first parent — the main the merge result
+/// was actually built on — not the event payload's `base.sha`: GitHub can
+/// compute the merge against a newer main than the payload names, and then
+/// main's own native changes would be blamed on the PR. (`cat-file` because a
+/// shallow checkout grafts the parents away for `rev-parse HEAD^1`.)
+fn version_check() -> Step<Run> {
+ Step::new("Require an Android version bump for native changes")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ base=$(git cat-file -p HEAD | sed -n 's/^parent //p' | head -1)
+ echo "Comparing the merge result with its base ${base:0:10}"
+ git fetch -q --depth=1 origin "$base"
+ bun scripts/android-version-check.mjs "$base"
+ "#})
+ .id("android-version")
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
+fn read_labels() -> Step<Run> {
+ Step::new("Read the PR's current labels")
+ .run(indoc::indoc! {r#"
+ set -euo pipefail
+ labels=$(gh pr view "$PR_NUMBER" --repo "$GH_REPO" --json labels --jq '[.labels[].name] | join(",")')
+ echo "labels: ${labels:-<none>}"
+ if [[ ",${labels}," == *",skip-android-update,"* ]]; then
+ echo "skip=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "skip=false" >> "$GITHUB_OUTPUT"
+ fi
+ "#})
+ .id("labels")
+ .if_condition(Expression::new(NATIVE_CHANGED))
+ .shell("bash")
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
+}
+
+fn play_auth() -> Step<Use> {
+ Step::new("Authenticate to Google Play")
+ .uses(
+ "google-github-actions",
+ "auth",
+ "7c6bc770dae815cd3e89ee6cdf493a5fab2cc093",
+ ) // v3
+ .id("auth")
+ .if_condition(gated())
+ .add_with((
+ "workload_identity_provider",
+ "${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}",
+ ))
+ .add_with(("service_account", "${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}"))
+ .add_with(("token_format", "access_token"))
+ .add_with((
+ "access_token_scopes",
+ "https://www.googleapis.com/auth/androidpublisher",
+ ))
+ .add_with(("create_credentials_file", false))
+ .add_with(("export_environment_variables", false))
+}
+
+/// The gate proper: the committed version code must be live on production,
+/// built from the Android native code of the PR's *current* merge result
+/// (fetched through the API: a re-run checks out the merge commit of the
+/// run's original event, which may predate native code landing on main).
+fn require_live() -> Step<Run> {
+ Step::new("Require the Play release to be live")
+ .run(concat!(
+ include_str!("../scripts/android_git_fetch.sh"),
+ include_str!("../scripts/pr_merge_commit.sh"),
+ r#"set -euo pipefail
+merge=$(pr_merge_commit)
+gh_fetch "$merge"
+native_hash=$(bun scripts/android-native.mjs hash "$merge")
+echo "Merge result ${merge:0:10}: Android native hash ${native_hash}"
+bun scripts/android-play-status.mjs --version-code "$VERSION_CODE" --require-live \
+ --native-hash "$native_hash" --pr "$PR_NUMBER"
+"#
+ ))
+ .if_condition(gated())
+ .shell("bash")
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+ .add_env(("GH_TOKEN", "${{ github.token }}"))
+ .add_env(("GH_REPO", "${{ github.repository }}"))
+ .add_env(("PR_NUMBER", "${{ github.event.pull_request.number }}"))
+ .add_env((
+ "VERSION_CODE",
+ "${{ steps.android-version.outputs.version_code }}",
+ ))
+ .add_env((
+ "GOOGLE_PLAY_ACCESS_TOKEN",
+ "${{ steps.auth.outputs.access_token }}",
+ ))
+}
+
+fn skip_notice() -> Step<Run> {
+ Step::new("Skipped via label")
+ .run(
+ "echo \"Android native changes detected, but the skip-android-update label says they \
+ don't break the native/web contract — skipping the Play release gate.\"",
+ )
+ .if_condition(Expression::new(format!("{NATIVE_CHANGED} && {SKIP_LABEL}")))
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/ios_native_check.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/ios_native_check.rs
index add0c003b8..8e856162a8 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/ios_native_check.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/ios_native_check.rs
@@ -31,7 +31,7 @@
//! `IOS_RELEASE_DOPPLER_TOKEN` secret), shared with the release workflow.
//!
//! The `skip-ios-update` label bypasses the gate for tauri changes that don't
-//! break the native/web contract; the `iOS Native Check Label` workflow
+//! break the native/web contract; the `Native Check Label` workflow
//! re-runs this job when that label is added or removed. The labels are read
//! through the API at run time, not from `github.event`: a re-run keeps the
//! payload of the event that started the run, so the event's label list is
@@ -118,10 +118,15 @@ fn cache_wasm_version_bump() -> Step<Run> {
set -euo pipefail
manifest=crates/client/cache-wasm/Cargo.toml
version() { git show "$1:$manifest" 2>/dev/null | sed -n 's/^version *= *"\([^"]*\)".*/\1/p' | head -1 | grep . || echo none; }
- git fetch -q --depth=1 origin "$BASE_BRANCH"
- base=$(version "origin/$BASE_BRANCH")
+ # The merge commit's first parent is the main this merge result was
+ # built on; a fresh fetch of main could be newer and misattribute
+ # its bumps to the PR.
+ base_sha=$(git cat-file -p HEAD | sed -n 's/^parent //p' | head -1)
+ git fetch -q --depth=1 origin "$base_sha"
+ echo "base_sha=${base_sha}" >> "$GITHUB_OUTPUT"
+ base=$(version "$base_sha")
head=$(version HEAD)
- echo "cache-wasm version: base ${base}, merge result ${head}"
+ echo "cache-wasm version: base ${base} (${base_sha:0:10}), merge result ${head}"
if [[ "$base" != "$head" ]]; then
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "The client cache wasm version moved; the native app compiles that cache, so this counts as a native change."
@@ -131,7 +136,6 @@ fn cache_wasm_version_bump() -> Step<Run> {
"#})
.id("cache-wasm")
.shell("bash")
- .add_env(("BASE_BRANCH", "${{ github.base_ref }}"))
}
/// The PR's labels as they are now. `github.event.pull_request.labels` is
@@ -170,16 +174,11 @@ fn setup_bun() -> Step<Use> {
fn verify_bump() -> Step<Run> {
Step::new("Verify iOS release numbers were bumped")
- .run(indoc::indoc! {r#"
- set -euo pipefail
- git fetch --depth=1 origin "$BASE_BRANCH"
- bun scripts/ios-verify-native-bump.mjs
- "#})
+ .run("bun scripts/ios-verify-native-bump.mjs")
.if_condition(gated())
- .shell("bash")
.working_directory(xtask_paths::repo_dir!("apps/web"))
- .add_env(("BASE_BRANCH", "${{ github.base_ref }}"))
- .add_env(("BASE_REF", "origin/${{ github.base_ref }}"))
+ // The base the merge result was built on (fetched by the cache-wasm step).
+ .add_env(("BASE_REF", "${{ steps.cache-wasm.outputs.base_sha }}"))
}
/// Exports `APPLE_API_KEY` / `APPLE_API_ISSUER` via `GITHUB_ENV` and writes
@@ -204,6 +203,7 @@ fn require_live_version() -> Step<Run> {
Step::new("Require the App Store release to be live")
.run(concat!(
include_str!("../scripts/ios_native_tree.sh"),
+ include_str!("../scripts/pr_merge_commit.sh"),
include_str!("../scripts/ios_native_check_live.sh")
))
.if_condition(gated())
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
index d63a7aa814..7d47963c6c 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs
@@ -1,26 +1,31 @@
use super::*;
#[test]
-fn android_version_is_an_unconditional_required_merge_check() {
+fn android_native_check_is_an_unconditional_required_merge_check() {
let yaml = web_app_check_main().to_string().expect("workflow yaml");
- let android = job(&yaml, "android-version", "typescript");
+ let android = job(&yaml, "android-native-check", "typescript");
assert!(
- !android.contains("if:"),
- "native enforcement must always run"
+ !android.contains("\n if:"),
+ "native enforcement must always run (steps may be gated, the job may not): {android}"
);
assert!(
!android.contains("fetch-depth"),
"shallow checkout; the base commit is fetched by the step: {android}"
);
- assert!(android.contains("github.event.pull_request.base.sha"));
- assert!(android.contains("git fetch -q --depth=1 origin \"$BASE_SHA\""));
+ assert!(
+ android.contains("git cat-file -p HEAD | sed -n 's/^parent //p' | head -1")
+ && !android.contains("github.event.pull_request.base.sha"),
+ "the base is the merge commit's first parent, not the event payload: {android}"
+ );
assert!(android.contains("bun scripts/android-version-check.mjs"));
+ assert!(android.contains("bun scripts/android-play-status.mjs --version-code"));
+ assert!(android.contains("id-token: write"));
let status = yaml
.split("\n status-check:\n")
.nth(1)
.expect("status job");
- assert!(status.contains("- android-version"));
- assert!(status.contains("needs.android-version.result }}\" != \"success\""));
+ assert!(status.contains("- android-native-check"));
+ assert!(status.contains("needs.android-native-check.result }}\" != \"success\""));
}
fn filters(yaml: &str) -> (&str, &str) {