Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ios): automate App Store releases for breaking Tauri changes (#7988)
Peter Chinman1926c6d3ab20
diff --git a/.github/workflows/ios-app-store-release.yml b/.github/workflows/ios-app-store-release.ymlnew file mode 100644index 0000000000..90f662c817--- /dev/null+++ b/.github/workflows/ios-app-store-release.yml@@ -0,0 +1,398 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs+name: iOS App Store Release+'on':+ pull_request:+ types:+ - labeled+jobs:+ release:+ if: github.event.label.name == 'ios-update' && github.event.pull_request.head.repo.full_name == github.repository+ name: iOS App Store Release+ runs-on: nscloud-macos-sequoia-arm64-6x14+ permissions:+ contents: read+ pull-requests: write+ checks: read+ statuses: read+ env:+ 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 }}+ fetch-depth: '0'+ persist-credentials: 'false'+ - name: Ensure gh and jq are installed+ run: |+ set -euo pipefail+ for tool in gh jq; do+ if ! command -v "$tool" >/dev/null; then+ echo "${tool} missing on this runner; installing with Homebrew."+ brew install "$tool"+ fi+ done+ gh --version | head -1+ jq --version+ shell: bash+ - name: Require the PR to be ready to merge+ run: |+ # --- native tree ------------------------------------------------------------+ # Hash identifying "the iOS native code" at a commit: every tracked blob under+ # apps/web/tauri except the paths that never reach the iOS binary. Android-only+ # code is recognised by Tauri's naming convention — a path component that is+ # `android`, starts with `android_` / `android.`, or contains `.android.`+ # (the android_* plugins, every android/ directory, android.rs / android.json,+ # android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+ # cfg(target_os = "android")) — plus the desktop updater manifest and editor+ # config. The release stamps uploaded builds+ # with it, the merge gate compares the live build's stamp against the merge+ # result's, and the drift / head guards compare commits with it. Must match+ # nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+ # Check path filter (web_app_check_main/ios_native_check.rs).+ NATIVE_TREE_PATH=apps/web/tauri+ export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++ # native_tree_hash <commit>: prints the hash, fails if the path is missing.+ # (--full-tree: ls-tree otherwise narrows its output to the current directory,+ # which would silently hash nothing when run from apps/web.)+ native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+ }++ # native_tree_fetch <sha>: make a commit that is not in this checkout (a new+ # PR head, GitHub's test merge commit, the pre-push head) available to+ # native_tree_hash. Checkouts here don't persist credentials, so authenticate+ # the way actions/checkout does. Fails if the commit is unreachable (a+ # force-pushed-away head).+ native_tree_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+ # 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+ # every other check on the head commit passing. Pending checks are waited on+ # (the label often lands right after a push); anything failing stops the+ # release before the long build. 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)+ if [[ "$(jq -r '.isDraft' <<<"$pr_json")" == "true" ]]; then+ echo "PR #${PR_NUMBER} is a draft; mark it ready for review before adding ios-update." >&2+ exit 1+ fi+ head_sha=$(jq -r '.headRefOid' <<<"$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.+ native_tree_fetch "$head_sha"+ if [[ "$(native_tree_hash "$head_sha")" != "$(native_tree_hash HEAD)" ]]; then+ echo "PR #${PR_NUMBER} got native changes since this run started (${HEAD_SHA:0:10} → ${head_sha:0:10});" \+ "re-add ios-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 native code is unchanged; continuing."+ fi++ # 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)'+ 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 ios-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 ios-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'+ - name: Install Nix+ run: |+ set -euo pipefail+ if ! command -v nix >/dev/null 2>&1; then+ curl --http1.1 --retry 5 --retry-delay 5 --retry-all-errors \+ --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \+ sh -s -- install macos --no-confirm \+ --extra-conf "experimental-features = nix-command flakes" \+ --extra-conf "sandbox = false" \+ --extra-conf "trusted-users = root runner"+ fi+ echo "/nix/var/nix/profiles/default/bin" >> "$GITHUB_PATH"+ echo "NIX_REMOTE=daemon" >> "$GITHUB_ENV"+ export PATH="/nix/var/nix/profiles/default/bin:$PATH"+ export NIX_REMOTE=daemon+ nix --version+ shell: bash+ - name: Verify iOS release numbers were bumped+ run: |-+ nix develop --command bash -euo pipefail -c '+ cd apps/web+ bun scripts/ios-verify-native-bump.mjs+ '+ shell: bash+ env:+ BASE_REF: origin/${{ github.event.pull_request.base.ref }}+ - name: Fetch App Store Connect credentials from Doppler+ run: |+ set -euo pipefail+ # Fetch the App Store Connect credentials from Doppler (ios-release/prd) —+ # the same shape as the DMG workflow's notarization step — and hand them to+ # later steps the way the iOS scripts expect them:+ # APPLE_API_KEY / APPLE_API_ISSUER exported via GITHUB_ENV+ # ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8 the private key, where+ # altool, tauri (APPLE_API_KEY_PATH default) and ios-app-store.mjs look+ # With IOS_DISTRIBUTION_CERTIFICATE=1 the optional Apple Distribution .p12 is+ # decoded to $RUNNER_TEMP and exported as APPLE_DISTRIBUTION_CERTIFICATE_PATH+ # / _PASSWORD for the signing step.+ if [ -z "${DOPPLER_TOKEN:-}" ]; then+ echo "DOPPLER_TOKEN is empty: the IOS_RELEASE_DOPPLER_TOKEN secret is missing, or this is a fork PR (secrets are not available to forks; a maintainer must run the release from a branch in this repository, or add skip-ios-update if the change is non-breaking)." >&2+ exit 1+ fi++ umask 077+ secrets=$(mktemp)+ trap 'rm -f "$secrets"' EXIT+ curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=ios-release&config=prd&format=json' \+ > "$secrets"++ required() {+ jq -er --arg name "$1" '.[$name] | strings | select(length > 0)' "$secrets" \+ || { echo "ios-release/prd is missing $1" >&2; exit 1; }+ }+ key_id=$(required APPLE_API_KEY_ID)+ issuer=$(required APPLE_API_ISSUER)++ key_dir="$HOME/.appstoreconnect/private_keys"+ mkdir -p "$key_dir"+ key_path="$key_dir/AuthKey_${key_id}.p8"+ required APPLE_API_PRIVATE_KEY > "$key_path"+ echo "::add-mask::$issuer"+ {+ echo "APPLE_API_KEY=$key_id"+ echo "APPLE_API_ISSUER=$issuer"+ } >> "$GITHUB_ENV"+ echo "Wrote App Store Connect API key $key_id to $key_path"++ if [ "${IOS_DISTRIBUTION_CERTIFICATE:-}" = "1" ]; then+ certificate=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_BASE64 // empty' "$secrets")+ if [ -z "$certificate" ]; then+ echo "No APPLE_DISTRIBUTION_CERTIFICATE_BASE64 in ios-release/prd; the build will" \+ "rely on Xcode cloud signing via the API key."+ exit 0+ fi+ certificate_path="$RUNNER_TEMP/apple-distribution.p12"+ printf '%s' "$certificate" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$certificate" | base64 -D > "$certificate_path"+ password=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD // empty' "$secrets")+ [ -z "$password" ] || echo "::add-mask::$password"+ {+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PATH=$certificate_path"+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD=$password"+ } >> "$GITHUB_ENV"+ echo "Wrote Apple Distribution certificate to $certificate_path"+ fi+ shell: bash+ env:+ DOPPLER_TOKEN: ${{ secrets.IOS_RELEASE_DOPPLER_TOKEN }}+ IOS_DISTRIBUTION_CERTIFICATE: '1'+ - id: build-check+ name: Check the build number is unused in App Store Connect+ run: |-+ nix develop --command bash -euo pipefail -c '+ cd apps/web+ bun scripts/ios-app-store.mjs status --require-unused-build+ '+ shell: bash+ - name: Configure signing identity+ run: |+ set -euo pipefail+ # The credentials step decodes the optional .p12 from Doppler and exports its+ # path; without one, xcodebuild uses cloud signing through the API key+ # (-allowProvisioningUpdates).+ certificate_path="${APPLE_DISTRIBUTION_CERTIFICATE_PATH:-}"+ if [ -z "$certificate_path" ]; then+ echo "No Apple Distribution certificate; relying on Xcode cloud signing" \+ "via the App Store Connect API key."+ exit 0+ fi++ # Mirror configure_signing_identity.sh (DMG builds): the System keychain keeps+ # the identity visible to xcodebuild without per-user keychain unlocking.+ sudo security import "$certificate_path" \+ -k /Library/Keychains/System.keychain \+ -P "${APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD:-}" \+ -A \+ -T /usr/bin/codesign \+ -T /usr/bin/security+ sudo security set-key-partition-list \+ -S apple-tool:,apple:,codesign: \+ -s \+ -k "" \+ /Library/Keychains/System.keychain || true++ identity=$(security find-identity -v -p codesigning /Library/Keychains/System.keychain \+ | awk -F '"' '/Apple Distribution/ { print $2; exit }')+ if [ -z "$identity" ]; then+ echo "No Apple Distribution identity found in System.keychain after import" >&2+ security find-identity -v -p codesigning /Library/Keychains/System.keychain >&2 || true+ exit 1+ fi+ echo "Using signing identity: $identity"+ shell: bash+ - name: Build and upload to App Store Connect+ if: steps.build-check.outputs.uploaded != 'true'+ run: |-+ nix develop --command bash -euo pipefail -c '+ bun install --frozen-lockfile+ cd apps/web+ just ios-release --no-bump+ '+ shell: bash+ env:+ VITE_POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}+ IOS_RELEASE_PR: ${{ github.event.pull_request.number }}+ - name: Require the PR's native code to be unchanged since the build+ run: |+ # --- native tree ------------------------------------------------------------+ # Hash identifying "the iOS native code" at a commit: every tracked blob under+ # apps/web/tauri except the paths that never reach the iOS binary. Android-only+ # code is recognised by Tauri's naming convention — a path component that is+ # `android`, starts with `android_` / `android.`, or contains `.android.`+ # (the android_* plugins, every android/ directory, android.rs / android.json,+ # android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+ # cfg(target_os = "android")) — plus the desktop updater manifest and editor+ # config. The release stamps uploaded builds+ # with it, the merge gate compares the live build's stamp against the merge+ # result's, and the drift / head guards compare commits with it. Must match+ # nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+ # Check path filter (web_app_check_main/ios_native_check.rs).+ NATIVE_TREE_PATH=apps/web/tauri+ export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++ # native_tree_hash <commit>: prints the hash, fails if the path is missing.+ # (--full-tree: ls-tree otherwise narrows its output to the current directory,+ # which would silently hash nothing when run from apps/web.)+ native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+ }++ # native_tree_fetch <sha>: make a commit that is not in this checkout (a new+ # PR head, GitHub's test merge commit, the pre-push head) available to+ # native_tree_hash. Checkouts here don't persist credentials, so authenticate+ # the way actions/checkout does. Fails if the commit is unreachable (a+ # force-pushed-away head).+ native_tree_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+ # 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).+ built_tree=$(native_tree_hash HEAD)+ built=$(jq -r '.bundle.iOS.bundleVersion' apps/web/tauri/src-tauri/tauri.ios.conf.json)+ 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+ 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+ 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+ shell: bash+ - name: Submit for App Review+ run: |-+ nix develop --command bash -euo pipefail -c '+ cd apps/web+ bun scripts/ios-app-store.mjs submit+ '+ shell: bash+ env:+ IOS_RELEASE_PR: ${{ github.event.pull_request.number }}+ - name: Comment on the PR+ if: success() || failure()+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b+ with:+ github-token: ${{ secrets.GITHUB_TOKEN }}+ script: |+ const fs = require('fs');+ const confPath = 'apps/web/tauri/src-tauri/tauri.ios.conf.json';+ const conf = fs.existsSync(confPath)+ ? JSON.parse(fs.readFileSync(confPath, 'utf8'))+ : { version: '?', bundle: { iOS: { bundleVersion: '?' } } };+ const version = conf.version;+ const build = conf.bundle.iOS.bundleVersion;+ const runUrl =+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` ++ `/actions/runs/${context.runId}`;+ const success = '${{ job.status }}' === 'success';+ const body = success+ ? [+ `📱 iOS ${version} (build ${build}) was uploaded to TestFlight and submitted for App Review.`,+ '',+ 'When Apple approves it, the version releases to the App Store automatically,',+ 'the **iOS Release Watch** workflow re-runs the **iOS 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 iOS native build floor committed in `min-native-build.json`, prompting older installs to update.',+ '',+ `[Workflow run](${runUrl})`,+ ].join('\n')+ : [+ `📱 iOS App Store release for ${version} (build ${build}) **failed** — see the [workflow run](${runUrl}).`,+ '',+ 'Fix the problem, then remove and re-add the `ios-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: ios-app-store-release-${{ github.event.pull_request.number }}diff --git a/.github/workflows/ios-native-check-label.yml b/.github/workflows/ios-native-check-label.ymlnew file mode 100644index 0000000000..ed2e3606b2--- /dev/null+++ b/.github/workflows/ios-native-check-label.yml@@ -0,0 +1,73 @@+# 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+'on':+ pull_request:+ types:+ - labeled+ - unlabeled+ branches:+ - 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+ runs-on: namespace-profile-linux-tiny-no-cache+ permissions:+ actions: write+ pull-requests: read+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ 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+ # 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')+ if [[ "$current" != "$HEAD_SHA" ]]; then+ echo "PR head moved from ${HEAD_SHA:0:10} to ${current:0:10}; its run reads the labels itself. Nothing to re-run."+ exit 0+ fi+ deadline=$(( $(date +%s) + 25 * 60 ))+ while true; do+ run=$(gh run list --repo "$GH_REPO" --workflow web-app-check-main.yml --commit "$HEAD_SHA" \+ --json databaseId,status,conclusion --limit 1 --jq '.[0] // empty')+ if [[ -z "$run" ]]; then+ echo "No Web App Pr Checks run for ${HEAD_SHA:0:10} yet; nothing to re-run (the next push runs the gate with the current labels)."+ exit 0+ fi+ run_id=$(jq -r '.databaseId' <<<"$run")+ status=$(jq -r '.status' <<<"$run")+ if [[ "$status" == "completed" ]]; then+ if [[ "$(jq -r '.conclusion' <<<"$run")" == "cancelled" ]]; then+ echo "Run ${run_id} was cancelled (superseded); nothing to re-run."+ exit 0+ fi+ 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+ 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')+ if [[ -z "$job_id" ]]; then+ echo "Run ${run_id} has no iOS Native Check 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."+ gh run rerun --repo "$GH_REPO" --job "$job_id"+ shell: bashdiff --git a/.github/workflows/ios-release-drift.yml b/.github/workflows/ios-release-drift.ymlnew file mode 100644index 0000000000..e7d140fff0--- /dev/null+++ b/.github/workflows/ios-release-drift.yml@@ -0,0 +1,218 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_drift.rs+name: iOS Release Drift+'on':+ pull_request:+ types:+ - synchronize+jobs:+ drift:+ if: contains(github.event.pull_request.labels.*.name, 'ios-update') && github.event.pull_request.head.repo.full_name == github.repository+ name: iOS Release Drift+ runs-on: namespace-profile-linux-tiny-no-cache+ permissions:+ actions: write+ contents: read+ pull-requests: 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'+ - id: detect+ name: Detect native changes in this push+ run: |+ # --- native tree ------------------------------------------------------------+ # Hash identifying "the iOS native code" at a commit: every tracked blob under+ # apps/web/tauri except the paths that never reach the iOS binary. Android-only+ # code is recognised by Tauri's naming convention — a path component that is+ # `android`, starts with `android_` / `android.`, or contains `.android.`+ # (the android_* plugins, every android/ directory, android.rs / android.json,+ # android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+ # cfg(target_os = "android")) — plus the desktop updater manifest and editor+ # config. The release stamps uploaded builds+ # with it, the merge gate compares the live build's stamp against the merge+ # result's, and the drift / head guards compare commits with it. Must match+ # nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+ # Check path filter (web_app_check_main/ios_native_check.rs).+ NATIVE_TREE_PATH=apps/web/tauri+ export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++ # native_tree_hash <commit>: prints the hash, fails if the path is missing.+ # (--full-tree: ls-tree otherwise narrows its output to the current directory,+ # which would silently hash nothing when run from apps/web.)+ native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+ }++ # native_tree_fetch <sha>: make a commit that is not in this checkout (a new+ # PR head, GitHub's test merge commit, the pre-push head) available to+ # native_tree_hash. Checkouts here don't persist credentials, so authenticate+ # the way actions/checkout does. Fails if the commit is unreachable (a+ # force-pushed-away head).+ native_tree_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 ios-update. Compare the native tree+ # 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 build still matches.+ if native_tree_fetch "$BEFORE_SHA" && before_tree=$(native_tree_hash "$BEFORE_SHA"); then :; else+ before_tree=unknown+ fi+ native_tree_fetch "$AFTER_SHA"+ after_tree=$(native_tree_hash "$AFTER_SHA")+ echo "native tree before: ${before_tree}"+ echo "native tree after: ${after_tree}"+ if [[ "$before_tree" == "$after_tree" ]]; then+ echo "changed=false" >> "$GITHUB_OUTPUT"+ echo "No native changes in this push; the release stays valid."+ else+ echo "changed=true" >> "$GITHUB_OUTPUT"+ echo "Native code changed; the released build is stale."+ fi+ shell: bash+ env:+ BEFORE_SHA: ${{ github.event.before }}+ AFTER_SHA: ${{ github.event.after }}+ - 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 ios-app-store-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 build of the old head)."+ gh run cancel "$run_id" --repo "$GH_REPO" || true+ done+ # Wait for them to stop: a run already inside `submit` could+ # otherwise submit after the withdrawal below looked for nothing.+ 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; withdrawing anyway."+ break+ fi+ sleep 10+ done+ done+ shell: bash+ env:+ HEAD_REF: ${{ github.event.pull_request.head.ref }}+ - name: Setup Bun+ if: steps.detect.outputs.changed == 'true'+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6+ with:+ bun-version: '1.3.13'+ - name: Fetch App Store Connect credentials from Doppler+ if: steps.detect.outputs.changed == 'true'+ run: |+ set -euo pipefail+ # Fetch the App Store Connect credentials from Doppler (ios-release/prd) —+ # the same shape as the DMG workflow's notarization step — and hand them to+ # later steps the way the iOS scripts expect them:+ # APPLE_API_KEY / APPLE_API_ISSUER exported via GITHUB_ENV+ # ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8 the private key, where+ # altool, tauri (APPLE_API_KEY_PATH default) and ios-app-store.mjs look+ # With IOS_DISTRIBUTION_CERTIFICATE=1 the optional Apple Distribution .p12 is+ # decoded to $RUNNER_TEMP and exported as APPLE_DISTRIBUTION_CERTIFICATE_PATH+ # / _PASSWORD for the signing step.+ if [ -z "${DOPPLER_TOKEN:-}" ]; then+ echo "DOPPLER_TOKEN is empty: the IOS_RELEASE_DOPPLER_TOKEN secret is missing, or this is a fork PR (secrets are not available to forks; a maintainer must run the release from a branch in this repository, or add skip-ios-update if the change is non-breaking)." >&2+ exit 1+ fi++ umask 077+ secrets=$(mktemp)+ trap 'rm -f "$secrets"' EXIT+ curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=ios-release&config=prd&format=json' \+ > "$secrets"++ required() {+ jq -er --arg name "$1" '.[$name] | strings | select(length > 0)' "$secrets" \+ || { echo "ios-release/prd is missing $1" >&2; exit 1; }+ }+ key_id=$(required APPLE_API_KEY_ID)+ issuer=$(required APPLE_API_ISSUER)++ key_dir="$HOME/.appstoreconnect/private_keys"+ mkdir -p "$key_dir"+ key_path="$key_dir/AuthKey_${key_id}.p8"+ required APPLE_API_PRIVATE_KEY > "$key_path"+ echo "::add-mask::$issuer"+ {+ echo "APPLE_API_KEY=$key_id"+ echo "APPLE_API_ISSUER=$issuer"+ } >> "$GITHUB_ENV"+ echo "Wrote App Store Connect API key $key_id to $key_path"++ if [ "${IOS_DISTRIBUTION_CERTIFICATE:-}" = "1" ]; then+ certificate=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_BASE64 // empty' "$secrets")+ if [ -z "$certificate" ]; then+ echo "No APPLE_DISTRIBUTION_CERTIFICATE_BASE64 in ios-release/prd; the build will" \+ "rely on Xcode cloud signing via the API key."+ exit 0+ fi+ certificate_path="$RUNNER_TEMP/apple-distribution.p12"+ printf '%s' "$certificate" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$certificate" | base64 -D > "$certificate_path"+ password=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD // empty' "$secrets")+ [ -z "$password" ] || echo "::add-mask::$password"+ {+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PATH=$certificate_path"+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD=$password"+ } >> "$GITHUB_ENV"+ echo "Wrote Apple Distribution certificate to $certificate_path"+ fi+ shell: bash+ env:+ DOPPLER_TOKEN: ${{ secrets.IOS_RELEASE_DOPPLER_TOKEN }}+ - id: withdraw+ name: Withdraw the PR's App Store submission+ if: steps.detect.outputs.changed == 'true'+ run: bun scripts/ios-app-store.mjs withdraw --pr "$PR_NUMBER"+ working-directory: apps/web+ - name: Remove the ios-update label+ if: always() && steps.detect.outputs.changed == 'true'+ run: gh pr edit "$PR_NUMBER" --repo "$GH_REPO" --remove-label ios-update+ shell: bash+ - name: Comment on the PR+ if: always() && steps.detect.outputs.changed == 'true'+ run: |+ set -euo pipefail+ bump='cd apps/web && doppler run --project ios-release --config prd -- just ios-bump'+ if [[ "$WITHDRAW_OUTCOME" != "success" ]]; then+ body="🚨 Native changes were pushed to this PR after its App Store release started, but withdrawing the App Review submission **failed** (see the [workflow run](${RUN_URL})). If a submission is pending, remove it from review in App Store Connect by hand so the stale build cannot go live. The \`ios-update\` label was removed; when the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`ios-update\`."+ elif [[ -n "$LIVE" ]]; then+ body="🚨 Native changes were pushed to this PR after Apple had already approved iOS ${LIVE}, so that build is (or is about to be) live with native code this PR no longer matches. Bump (\`${bump}\`), commit, re-add the \`ios-update\` label, and ship the follow-up as soon as possible. The label was removed."+ else+ body="📱 Native code changed after this PR's App Store release started, so the release was stopped: any in-progress build was cancelled and any pending App Review submission withdrawn (nothing stale can go live), and the \`ios-update\` label was removed. When the PR is ready again, bump (\`${bump}\`; the marketing version stays, the build number moves), commit, push, and re-add \`ios-update\`."+ fi+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"+ shell: bash+ env:+ LIVE: ${{ steps.withdraw.outputs.live }}+ WITHDRAW_OUTCOME: ${{ steps.withdraw.outcome }}+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}diff --git a/.github/workflows/ios-release-watch.yml b/.github/workflows/ios-release-watch.ymlnew file mode 100644index 0000000000..96f8037ca4--- /dev/null+++ b/.github/workflows/ios-release-watch.yml@@ -0,0 +1,279 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_watch.rs+name: iOS Release Watch+'on':+ schedule:+ - cron: '*/30 * * * *'+ workflow_dispatch: {}+permissions:+ actions: write+ contents: read+ pull-requests: write+jobs:+ watch:+ name: Re-run the iOS Native Check once the App Store 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 an App Store release+ run: |+ set -euo pipefail+ prs=$(gh pr list --repo "$GH_REPO" --label ios-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 ios-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'+ - name: Fetch App Store Connect credentials from Doppler+ if: steps.prs.outputs.count != '0'+ run: |+ set -euo pipefail+ # Fetch the App Store Connect credentials from Doppler (ios-release/prd) —+ # the same shape as the DMG workflow's notarization step — and hand them to+ # later steps the way the iOS scripts expect them:+ # APPLE_API_KEY / APPLE_API_ISSUER exported via GITHUB_ENV+ # ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8 the private key, where+ # altool, tauri (APPLE_API_KEY_PATH default) and ios-app-store.mjs look+ # With IOS_DISTRIBUTION_CERTIFICATE=1 the optional Apple Distribution .p12 is+ # decoded to $RUNNER_TEMP and exported as APPLE_DISTRIBUTION_CERTIFICATE_PATH+ # / _PASSWORD for the signing step.+ if [ -z "${DOPPLER_TOKEN:-}" ]; then+ echo "DOPPLER_TOKEN is empty: the IOS_RELEASE_DOPPLER_TOKEN secret is missing, or this is a fork PR (secrets are not available to forks; a maintainer must run the release from a branch in this repository, or add skip-ios-update if the change is non-breaking)." >&2+ exit 1+ fi++ umask 077+ secrets=$(mktemp)+ trap 'rm -f "$secrets"' EXIT+ curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=ios-release&config=prd&format=json' \+ > "$secrets"++ required() {+ jq -er --arg name "$1" '.[$name] | strings | select(length > 0)' "$secrets" \+ || { echo "ios-release/prd is missing $1" >&2; exit 1; }+ }+ key_id=$(required APPLE_API_KEY_ID)+ issuer=$(required APPLE_API_ISSUER)++ key_dir="$HOME/.appstoreconnect/private_keys"+ mkdir -p "$key_dir"+ key_path="$key_dir/AuthKey_${key_id}.p8"+ required APPLE_API_PRIVATE_KEY > "$key_path"+ echo "::add-mask::$issuer"+ {+ echo "APPLE_API_KEY=$key_id"+ echo "APPLE_API_ISSUER=$issuer"+ } >> "$GITHUB_ENV"+ echo "Wrote App Store Connect API key $key_id to $key_path"++ if [ "${IOS_DISTRIBUTION_CERTIFICATE:-}" = "1" ]; then+ certificate=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_BASE64 // empty' "$secrets")+ if [ -z "$certificate" ]; then+ echo "No APPLE_DISTRIBUTION_CERTIFICATE_BASE64 in ios-release/prd; the build will" \+ "rely on Xcode cloud signing via the API key."+ exit 0+ fi+ certificate_path="$RUNNER_TEMP/apple-distribution.p12"+ printf '%s' "$certificate" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$certificate" | base64 -D > "$certificate_path"+ password=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD // empty' "$secrets")+ [ -z "$password" ] || echo "::add-mask::$password"+ {+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PATH=$certificate_path"+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD=$password"+ } >> "$GITHUB_ENV"+ echo "Wrote Apple Distribution certificate to $certificate_path"+ fi+ shell: bash+ env:+ DOPPLER_TOKEN: ${{ secrets.IOS_RELEASE_DOPPLER_TOKEN }}+ - name: Re-run the check on PRs whose release is live+ if: steps.prs.outputs.count != '0'+ run: |+ # --- native tree ------------------------------------------------------------+ # Hash identifying "the iOS native code" at a commit: every tracked blob under+ # apps/web/tauri except the paths that never reach the iOS binary. Android-only+ # code is recognised by Tauri's naming convention — a path component that is+ # `android`, starts with `android_` / `android.`, or contains `.android.`+ # (the android_* plugins, every android/ directory, android.rs / android.json,+ # android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+ # cfg(target_os = "android")) — plus the desktop updater manifest and editor+ # config. The release stamps uploaded builds+ # with it, the merge gate compares the live build's stamp against the merge+ # result's, and the drift / head guards compare commits with it. Must match+ # nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+ # Check path filter (web_app_check_main/ios_native_check.rs).+ NATIVE_TREE_PATH=apps/web/tauri+ export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++ # native_tree_hash <commit>: prints the hash, fails if the path is missing.+ # (--full-tree: ls-tree otherwise narrows its output to the current directory,+ # which would silently hash nothing when run from apps/web.)+ native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+ }++ # native_tree_fetch <sha>: make a commit that is not in this checkout (a new+ # PR head, GitHub's test merge commit, the pre-push head) available to+ # native_tree_hash. Checkouts here don't persist credentials, so authenticate+ # the way actions/checkout does. Fails if the commit is unreachable (a+ # force-pushed-away head).+ native_tree_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 `ios-update` (PRS: [{number, sha, merge}]):+ #+ # 1. Drift: if the PR's in-flight App Store submission was built from native+ # code the PR head no longer has, withdraw it, drop the label and comment —+ # what the `iOS Release Drift` workflow does on push, except GitHub does+ # not run pull_request workflows on a PR that conflicts with main, so a+ # native push to such a PR only gets caught here.+ # 2. Ask App Store Connect whether the iOS version + build committed at the+ # PR head is live, built from the native tree the PR's merge result would+ # have (`merge` is GitHub's test merge commit; the gate hashes the same).+ # When it is, and the PR's latest `iOS 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.+ cd apps/web+ conf_path="apps/web/tauri/src-tauri/tauri.ios.conf.json"+ bump='cd apps/web && doppler run --project ios-release --config prd -- just ios-bump'++ check_pr() {+ local pr=$1 number sha merge conf version build head_tree native_tree run run_id status run_url job conclusion job_id reruns outputs withdrawn live+ number=$(jq -r '.number' <<<"$pr")+ sha=$(jq -r '.sha' <<<"$pr")+ merge=$(jq -r '.merge // empty' <<<"$pr")+ conf=$(gh api "repos/${GH_REPO}/contents/${conf_path}?ref=${sha}" --jq '.content' | base64 --decode)+ version=$(jq -r '.version' <<<"$conf")+ build=$(jq -r '.bundle.iOS.bundleVersion' <<<"$conf")++ # 1. Drift check against the head's native code.+ native_tree_fetch "$sha"+ head_tree=$(native_tree_hash "$sha")+ outputs="$RUNNER_TEMP/withdraw-${number}.out"+ : >"$outputs"+ GITHUB_OUTPUT="$outputs" bun scripts/ios-app-store.mjs withdraw --pr "$number" --unless-tree "$head_tree" \+ >"$RUNNER_TEMP/withdraw-${number}.log" 2>&1 || true+ sed 's/^/ /' "$RUNNER_TEMP/withdraw-${number}.log"+ withdrawn=$(sed -n 's/^withdrawn=//p' "$outputs")+ live=$(sed -n 's/^live=//p' "$outputs")+ if [[ "$withdrawn" == "true" || -n "$live" ]]; then+ gh pr edit "$number" --remove-label ios-update+ if [[ -n "$live" ]]; then+ gh pr comment "$number" --body "🚨 Native changes were pushed to this PR after Apple had already approved iOS ${live}, so that build is (or is about to be) live with native code this PR no longer matches. Bump (\`${bump}\`), commit, re-add the \`ios-update\` label, and ship the follow-up as soon as possible. The label was removed."+ else+ gh pr comment "$number" --body "📱 Native code changed after this PR's App Store release started (the push-time drift check could not run — does the PR conflict with \`main\`?), so the pending App Review submission was withdrawn and the \`ios-update\` label removed. When the PR is ready again, bump (\`${bump}\`; the marketing version stays, the build number moves), commit, push, and re-add \`ios-update\`."+ fi+ echo "PR #${number}: stale submission handled; label removed"+ return 0+ fi++ # 2. Live check against the merge result.+ if [[ -z "$merge" ]]; then+ echo "PR #${number}: no merge commit (conflicts with main?); cannot check the merge result"+ return 0+ fi+ native_tree_fetch "$merge"+ native_tree=$(native_tree_hash "$merge")+ echo "PR #${number}: iOS ${version} (build ${build}) at ${sha:0:10}, merge-result native tree ${native_tree:0:10}"++ if ! bun scripts/ios-app-store.mjs status --require-live \+ --version "$version" --build "$build" --native-tree "$native_tree" \+ >"$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 the App Store"++ 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 == "iOS Native Check") | {id: .databaseId, conclusion}')+ if [[ -z "$job" ]]; then+ echo " run ${run_id} has no iOS Native Check job; skipping"+ return 0+ fi+ job_id=$(jq -r '.id' <<<"$job")+ conclusion=$(jq -r '.conclusion' <<<"$job")+ if [[ "$conclusion" == "success" ]]; then+ echo " iOS Native Check already passed"+ return 0+ fi+ if [[ "$conclusion" != "failure" ]]; then+ echo " iOS 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.+ # Counted by our own comments: the run's attempt number is shared with+ # label re-runs and "re-run failed jobs" clicks for flaky tests.+ reruns=$(gh pr view "$number" --json comments --jq \+ "[.comments[].body | select(contains(\"Re-ran the **iOS Native Check**\")) | select(contains(\"iOS ${version} (build ${build})\"))] | length")+ if (( reruns >= 2 )); then+ echo " iOS Native Check already re-run ${reruns} times and still failing; not re-running again — see ${run_url}"+ return 0+ fi+ echo " re-running iOS 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 "📱 iOS ${version} (build ${build}) is live on the App Store. Re-ran the **iOS 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 }}diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.ymlindex faaef4da5e..4244b58312 100644--- a/.github/workflows/release-production.yml+++ b/.github/workflows/release-production.yml@@ -105,9 +105,9 @@ jobs:- name: Build for Productionworking-directory: apps/webrun: just build-prod+ # MIN_NATIVE_BUILD_ANDROID / MIN_NATIVE_BUILD_IOS come from+ # apps/web/min-native-build.json inside `just build-prod`.env:- MIN_NATIVE_BUILD_ANDROID: "1"- MIN_NATIVE_BUILD_IOS: "185"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/tracesdiff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.ymlindex 89f110ce9a..630862fb3a 100644--- a/.github/workflows/web-app-check-main.yml+++ b/.github/workflows/web-app-check-main.yml@@ -360,6 +360,204 @@ jobs:- name: Teardown Nixif: always()uses: './.github/actions/teardown-nix'+ ios-native-check:+ name: iOS Native Check+ runs-on: namespace-profile-linux-tiny-no-cache+ permissions:+ contents: read+ pull-requests: read+ steps:+ - name: Checkout Repo+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10+ - id: native-filter+ name: Detect native iOS changes+ uses: dorny/paths-filter@d1c1ffe0248fe513906c8e24db8ea791d46f8590+ with:+ predicate-quantifier: every+ filters: |+ ios_native:+ - 'apps/web/tauri/**'+ - '!apps/web/tauri/**/android/**'+ - '!apps/web/tauri/**/android_*'+ - '!apps/web/tauri/**/android_*/**'+ - '!apps/web/tauri/**/android.*'+ - '!apps/web/tauri/**/*.android.*'+ - '!apps/web/tauri/desktop-release.json'+ - '!apps/web/tauri/.helix/**'+ - id: labels+ name: Read the PR's current labels+ if: steps.native-filter.outputs.ios_native == '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-ios-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 }}+ - name: Setup Bun+ if: steps.native-filter.outputs.ios_native == 'true' && steps.labels.outputs.skip != 'true'+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6+ with:+ bun-version: '1.3.13'+ - name: Verify iOS release numbers were bumped+ if: steps.native-filter.outputs.ios_native == '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+ env:+ BASE_BRANCH: ${{ github.base_ref }}+ BASE_REF: origin/${{ github.base_ref }}+ working-directory: apps/web+ - name: Fetch App Store Connect credentials from Doppler+ if: steps.native-filter.outputs.ios_native == 'true' && steps.labels.outputs.skip != 'true'+ run: |+ set -euo pipefail+ # Fetch the App Store Connect credentials from Doppler (ios-release/prd) —+ # the same shape as the DMG workflow's notarization step — and hand them to+ # later steps the way the iOS scripts expect them:+ # APPLE_API_KEY / APPLE_API_ISSUER exported via GITHUB_ENV+ # ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8 the private key, where+ # altool, tauri (APPLE_API_KEY_PATH default) and ios-app-store.mjs look+ # With IOS_DISTRIBUTION_CERTIFICATE=1 the optional Apple Distribution .p12 is+ # decoded to $RUNNER_TEMP and exported as APPLE_DISTRIBUTION_CERTIFICATE_PATH+ # / _PASSWORD for the signing step.+ if [ -z "${DOPPLER_TOKEN:-}" ]; then+ echo "DOPPLER_TOKEN is empty: the IOS_RELEASE_DOPPLER_TOKEN secret is missing, or this is a fork PR (secrets are not available to forks; a maintainer must run the release from a branch in this repository, or add skip-ios-update if the change is non-breaking)." >&2+ exit 1+ fi++ umask 077+ secrets=$(mktemp)+ trap 'rm -f "$secrets"' EXIT+ curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=ios-release&config=prd&format=json' \+ > "$secrets"++ required() {+ jq -er --arg name "$1" '.[$name] | strings | select(length > 0)' "$secrets" \+ || { echo "ios-release/prd is missing $1" >&2; exit 1; }+ }+ key_id=$(required APPLE_API_KEY_ID)+ issuer=$(required APPLE_API_ISSUER)++ key_dir="$HOME/.appstoreconnect/private_keys"+ mkdir -p "$key_dir"+ key_path="$key_dir/AuthKey_${key_id}.p8"+ required APPLE_API_PRIVATE_KEY > "$key_path"+ echo "::add-mask::$issuer"+ {+ echo "APPLE_API_KEY=$key_id"+ echo "APPLE_API_ISSUER=$issuer"+ } >> "$GITHUB_ENV"+ echo "Wrote App Store Connect API key $key_id to $key_path"++ if [ "${IOS_DISTRIBUTION_CERTIFICATE:-}" = "1" ]; then+ certificate=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_BASE64 // empty' "$secrets")+ if [ -z "$certificate" ]; then+ echo "No APPLE_DISTRIBUTION_CERTIFICATE_BASE64 in ios-release/prd; the build will" \+ "rely on Xcode cloud signing via the API key."+ exit 0+ fi+ certificate_path="$RUNNER_TEMP/apple-distribution.p12"+ printf '%s' "$certificate" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$certificate" | base64 -D > "$certificate_path"+ password=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD // empty' "$secrets")+ [ -z "$password" ] || echo "::add-mask::$password"+ {+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PATH=$certificate_path"+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD=$password"+ } >> "$GITHUB_ENV"+ echo "Wrote Apple Distribution certificate to $certificate_path"+ fi+ shell: bash+ env:+ DOPPLER_TOKEN: ${{ secrets.IOS_RELEASE_DOPPLER_TOKEN }}+ - name: Require the App Store release to be live+ if: steps.native-filter.outputs.ios_native == 'true' && steps.labels.outputs.skip != 'true'+ run: |+ # --- native tree ------------------------------------------------------------+ # Hash identifying "the iOS native code" at a commit: every tracked blob under+ # apps/web/tauri except the paths that never reach the iOS binary. Android-only+ # code is recognised by Tauri's naming convention — a path component that is+ # `android`, starts with `android_` / `android.`, or contains `.android.`+ # (the android_* plugins, every android/ directory, android.rs / android.json,+ # android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+ # cfg(target_os = "android")) — plus the desktop updater manifest and editor+ # config. The release stamps uploaded builds+ # with it, the merge gate compares the live build's stamp against the merge+ # result's, and the drift / head guards compare commits with it. Must match+ # nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+ # Check path filter (web_app_check_main/ios_native_check.rs).+ NATIVE_TREE_PATH=apps/web/tauri+ export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++ # native_tree_hash <commit>: prints the hash, fails if the path is missing.+ # (--full-tree: ls-tree otherwise narrows its output to the current directory,+ # which would silently hash nothing when run from apps/web.)+ native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+ }++ # native_tree_fetch <sha>: make a commit that is not in this checkout (a new+ # PR head, GitHub's test merge commit, the pre-push head) available to+ # native_tree_hash. Checkouts here don't persist credentials, so authenticate+ # the way actions/checkout does. Fails if the commit is unreachable (a+ # force-pushed-away head).+ native_tree_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+ # 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_tree_fetch "$merge"+ native_tree=$(native_tree_hash "$merge")+ echo "Merge result ${merge:0:10}: native tree ${native_tree}"+ bun scripts/ios-app-store.mjs status --require-live --native-tree "$native_tree"+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ working-directory: apps/web+ - name: Skipped via label+ if: steps.native-filter.outputs.ios_native == 'true' && steps.labels.outputs.skip == 'true'+ run: echo "Native iOS changes detected, but the skip-ios-update label says they don't break the native/web contract — skipping the App Store release gate."status-check:needs:- path-check@@ -369,6 +567,7 @@ jobs:- test- cycles- build+ - ios-native-checkif: always()name: Web App Status Checkruns-on: namespace-profile-linux-tiny-no-cache@@ -382,15 +581,19 @@ jobs:echo "test: ${{ needs.test.result }}"echo "cycles: ${{ needs.cycles.result }}"echo "build: ${{ needs.build.result }}"+ echo "ios-native-check: ${{ needs.ios-native-check.result }}"- # Fail if any job failed (skipped and success are both OK)+ # 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.path-check.result }}" == "failure" ]] || \[[ "${{ needs.typescript.result }}" == "failure" ]] || \[[ "${{ needs.generated-code.result }}" == "failure" ]] || \[[ "${{ needs.biome-check.result }}" == "failure" ]] || \[[ "${{ needs.test.result }}" == "failure" ]] || \[[ "${{ needs.cycles.result }}" == "failure" ]] || \- [[ "${{ needs.build.result }}" == "failure" ]]; then+ [[ "${{ needs.build.result }}" == "failure" ]] || \+ [[ "${{ needs.ios-native-check.result }}" == "failure" ]] || \+ [[ "${{ needs.ios-native-check.result }}" == "cancelled" ]]; thenecho "One or more jobs failed"exit 1fidiff --git a/CLAUDE.md b/CLAUDE.mdindex 269d072067..c6f21ae369 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -54,6 +54,7 @@ Real files live in `.agents/`; tool-specific directories only symlink to it.| Rust code, builds, or tests | [Rust development](docs/development/rust.md) || 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) || 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.mdnew file mode 100644index 0000000000..d4b0d03cc7--- /dev/null+++ b/apps/web/docs/ios-releases.md@@ -0,0 +1,209 @@+# iOS releases and breaking Tauri changes++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+depends on new native code must therefore never be deployed before the+matching native build is downloadable, and users on older native builds must+be pushed to update before they receive that bundle.++Four generated workflows (plus a gate job in the web app PR checks) and a+checked-in `min-native-build.json` enforce this end to end.++## The flow for a PR with breaking native changes++1. **`iOS Native Check`**, a job of the web app PR checks+ (`.github/workflows/web-app-check-main.yml`), runs on every PR against+ `main`. The required `Web App Status Check` depends on it, so no branch+ ruleset change is needed. If the PR touches the iOS native code it+ requires:+ - the iOS release numbers to be bumped relative to `main`, and+ - that exact version + build to be **live on the App Store**.++ Until both hold, the check fails and the PR cannot merge.+2. You bump the numbers locally and commit the result:++ ```bash+ cd apps/web && doppler run --project ios-release --config prd -- just ios-bump+ ```++ This bumps the build number in `tauri/src-tauri/tauri.ios.conf.json`,+ raises the `ios` floor in `min-native-build.json` to it, syncs the+ generated Apple project metadata, and bumps the marketing version+ (`2.0.9` → `2.0.10`) **only if the committed one has already shipped** —+ a version that was never released, or whose submission was withdrawn,+ keeps its string and just gets a new build. The build number is one above+ the larger of the committed number and the highest build App Store+ Connect has ever seen, which is why the command runs through Doppler: a+ release made by hand (Xcode Organizer, `just ios-release`) whose number+ was never committed would otherwise be reused, and the floor derived from+ it would be wrong. Without credentials the bump still runs but warns (and+ bumps the version unconditionally); the release workflow re-checks the+ number against App Store Connect before building and fails with a re-bump+ instruction if it collides.+3. Add the **`ios-update`** label to the PR — once it is ready to merge: the+ **`iOS App Store Release`** workflow+ (`.github/workflows/ios-app-store-release.yml`) first refuses drafts and+ PRs with failing checks (pending ones are waited on, up to 30 minutes), then builds the app from+ the PR head on the Namespace macOS runner inside the Nix dev shell (like+ the `ios-preview` label), uploads it to TestFlight, waits for App Store+ Connect processing + export compliance, and submits it for App Review+ (release type: automatic after approval). It comments the outcome+ on the PR. To merge the moment Apple approves, click **Enable+ auto-merge** (squash) on the PR: GitHub then merges it as soon as+ `iOS Native Check` passes. (The workflow doesn't enable auto-merge+ itself: that would need a user token, because a merge set up by the+ Actions token doesn't trigger the push-to-`main` workflows such as the+ dev redeploy.) To retry after a failure, remove and re-add the label.+4. Wait for Apple to approve. The version releases automatically, and the+ **`iOS Release Watch`** workflow (`.github/workflows/ios-release-watch.yml`,+ every 30 minutes) notices: for each open PR labeled `ios-update` it asks+ App Store Connect whether the version + build at the PR head is live and,+ when it is, re-runs the PR's failed `iOS Native Check` job and comments. The+ gate turns green on its own and the PR merges if auto-merge is on.+ (Re-running the job by hand works too. The watcher stops after two+ automatic re-runs — counted by its own comments on the PR — so a check+ failing for another reason doesn't retry forever, and GitHub refuses to+ re-run runs older than 30 days: after a review that long, push a commit to+ get a fresh run.)+5. The next prod web deploy (`just build-prod`) reads both platform floors+ from `min-native-build.json` into `MIN_NATIVE_BUILD_ANDROID` /+ `MIN_NATIVE_BUILD_IOS`, so `dist/bundle-manifest.json` carries+ `minNativeBuilds.ios` = the new build number. Installed apps on older+ native builds stop applying OTA bundles and show the "update from the+ App Store" prompt instead (`NativeUpdateRequired` in+ `src/lib/tauri/TauriProvider.tsx`). The Android floor is independent; see+ `docs/development/android.md`.++The bump is deliberately a local command rather than something the label+workflow pushes: a `GITHUB_TOKEN` push never re-triggers required checks, so+a CI-pushed bump commit would wedge the PR.++### Non-breaking tauri changes++If the tauri change doesn't break the native/web contract (comments, dev-only+tooling, desktop-only config), add the **`skip-ios-update`** label instead;+the **`iOS Native Check Label`** workflow re-runs just the gate job (and the+status check that depends on it) when that label is added or removed, so the+gate passes without a release and without re-running the whole web suite.+That workflow is not a required check: it waits for the web suite run to+finish first (up to 25 minutes), and the release preconditions ignore it. For a non-breaking change you still want+to ship to the App Store, `just ios-bump --no-min` bumps the versions without+raising the floor.++## Several native PRs at once++Version + build number alone don't identify a PR's native code: two PRs+bumped from the same `main` get the same numbers. So the release stamps each+uploaded build with a hash of the native code it was built from (in the+build's TestFlight "What to Test" text), and the checks use it. "Native+code" is everything under `apps/web/tauri` except what never reaches the iOS+binary: anything Android-only by Tauri's naming convention (a path component+`android`, `android_*`, `android.*` or `*.android.*` — the `android_*`+plugins, every `android/` directory, `android.rs`, `tauri.android.conf.json`+and so on), `desktop-release.json`, and `.helix/`. The rule is defined once,+in `scripts/ios_native_tree.sh` next to the workflow sources, mirrored in+`ios-app-store.mjs` and the gate's path filter. The checks:++- **Collision check** (release workflow, before building): the+ marketing version must be above the latest App Store release, and a+ build at or above the PR's number with a different stamp — another PR, or+ 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.+- **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+ with).+ Native commits pushed after the release, native code that landed on main+ since (merge main into the PR), or another PR's build that shares the+ numbers, all fail with "bump and re-release": the floor the merge would+ set must describe a build that really contains main's native code.+ Web-only (and Android-only) commits don't change the hash and stay green.+ The flip side: any merge to `main` that touches the iOS native code while+ a release is in review (even a `skip-ios-update` one) changes the merge+ result's hash, so that release has to be bumped and redone after merging+ `main`.+- **One version in flight**: App Store Connect allows one iOS version in+ review at a time, so the second PR's `submit` fails naming the version+ that blocks it. Once that one ships (or is removed from review in App+ Store Connect), remove and re-add `ios-update`; the uploaded build is+ reused. A rejected or abandoned submission blocks everyone until someone+ removes it from review.++In practice: native PRs ship through Apple one at a time, each with its own+number, and the first to release wins its number; the others are told to+re-bump at the earliest check that can know.++## Pushing to a PR after the label++The label means "release this and merge it when Apple approves", so the+release only starts on a PR that is ready to merge. Pushes afterwards:++- **Web-only commits** need nothing. The native tree is unchanged, the gate+ stays green, and the reviewed build's embedded web bundle is replaced over+ the air after the merge like every other OTA update.+- **Native commits** make the uploaded build stale, and a stale build Apple+ approves would go straight to the App Store. The+ **`iOS Release Drift`** workflow (`.github/workflows/ios-release-drift.yml`)+ runs on every push to a labeled PR and, when `apps/web/tauri` changed,+ cancels any release run still building, withdraws the PR's submission from+ review (the API equivalent of "Remove from Review"), removes the+ `ios-update` label, and comments. GitHub does not run `pull_request`+ workflows on a PR that conflicts with `main`, so a native push to such a+ 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+ (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+ build (with automatic release that means it is live or minutes away),+ nothing can be withdrawn: the comment says so, and the follow-up release+ should ship as soon as possible.++## Credentials note++The gate and the watcher run `ios-app-store.mjs` from the PR's own merge+result with the same App Manager key the release uses, on every same-repo+PR with native changes (fork PRs get no secrets and fail the gate closed).+A collaborator branch could therefore drive App Store Connect with that+key. If that matters, give the gate a second, Developer-role key in Doppler+(reads suffice for `status`); the watcher's `withdraw` needs App Manager.++## Manual / TestFlight-only releases++`just ios-release` still does a full local build + TestFlight upload without+any Xcode UI (it bumps only the build number). **Commit the bumped number**,+whichever way you release — the automated flow treats the committed build+number as the newest native code, and `just ios-bump` only catches an+uncommitted one when it can ask App Store Connect. It uses the+same toolchain split as `just ios-build` (`scripts/ios-native-env.sh`), so run+it from the Nix dev shell like any other iOS build. See the header of+`scripts/ios-release.sh` for the credentials it needs (`doppler run --project+ios-release --config prd -- just ios-release` covers them), and+`scripts/ios-app-store.mjs` for the underlying App Store Connect commands+(`wait-build`, `submit`, `status`).++## One-time repository setup++- **Labels**: create `ios-update` and `skip-ios-update`.+- **Branch protection**: nothing to do — the gate is a job of the web app PR+ checks, and the already-required `Web App Status Check` fails when it+ fails.+- **Doppler project `ios-release`, config `prd`** (same shape as+ `macos-release/prd`, which the desktop notarization uses; that key has only+ the Developer role, which cannot submit for review, hence a separate key):+ - `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, `APPLE_API_PRIVATE_KEY` — an App+ Store Connect team API key with the **App Manager** role (Users and+ Access → Integrations → Team Keys) and the contents of its+ `AuthKey_<ID>.p8`+ - optional `APPLE_DISTRIBUTION_CERTIFICATE_BASE64` /+ `APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD` — a base64-encoded Apple+ Distribution `.p12`; without it the release workflow relies on Xcode+ cloud signing through the API key.+- **GitHub secrets**:+ - `IOS_RELEASE_DOPPLER_TOKEN` — a Doppler service token with read access to+ `ios-release/prd`, used by the iOS workflows+ - `POSTHOG_API_KEY` (already present) — embedded as `VITE_POSTHOG_API_KEY`+ in the release builddiff --git a/apps/web/justfile b/apps/web/justfileindex 1790c50e74..3ef53542a2 100644--- a/apps/web/justfile+++ b/apps/web/justfile@@ -54,6 +54,22 @@ ios-build-sim prebuilt="false": ios-prepare--config '{"build":{"beforeBuildCommand":"","frontendDist":"../../dist"}}' \-- --no-default-features+# iOS: full release — build, upload to App Store Connect/TestFlight, and set+# export compliance, no Xcode UI. Requires APPLE_API_KEY + APPLE_API_ISSUER+# (one-time setup in the script header). Flags: --no-bump --skip-validate --no-wait+ios-release *ARGS:+ bash scripts/ios-release.sh {{ARGS}}++# iOS: bump the release numbers for an App Store release (build number, the+# iOS floor in min-native-build.json, and the marketing version if the+# committed one has already shipped) and sync gen/apple metadata. Run it+# through Doppler so it can ask App Store Connect (`doppler run --project+# ios-release --config prd -- just ios-bump`), then commit the result before+# adding the `ios-update` label to a PR with breaking native changes. Flags:+# --no-min (non-breaking App Store release) --build-only (TestFlight iteration)+ios-bump *ARGS:+ bun scripts/ios-bump-version.mjs {{ARGS}}+# iOS generated project prep. Keep native bundle metadata in sync with# tauri.ios.conf.json, then prepare ignored local Swift dependencies.ios-prepare:@@ -137,7 +153,14 @@ build-staging: build-wasmMODE=staging NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun buildbun scripts/cache-wasm/cli.ts package-dist --dist dist+# Production bundles carry the native build floors checked in at+# min-native-build.json (schema 3 manifest, see scripts/write-bundle-manifest.mjs);+# `just ios-bump` raises the iOS one. Explicit MIN_NATIVE_BUILD_* env still wins.build-prod: build-wasm+ #!/usr/bin/env bash+ set -euo pipefail+ export MIN_NATIVE_BUILD_ANDROID="${MIN_NATIVE_BUILD_ANDROID:-$(bun -e "console.log(require('./min-native-build.json').android)")}"+ export MIN_NATIVE_BUILD_IOS="${MIN_NATIVE_BUILD_IOS:-$(bun -e "console.log(require('./min-native-build.json').ios)")}"MODE=production NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun buildbun scripts/cache-wasm/cli.ts package-dist --dist distdiff --git a/apps/web/min-native-build.json b/apps/web/min-native-build.jsonnew file mode 100644index 0000000000..fa56e299f2--- /dev/null+++ b/apps/web/min-native-build.json@@ -0,0 +1,4 @@+{+ "android": 1,+ "ios": 185+}diff --git a/apps/web/scripts/ios-app-store.mjs b/apps/web/scripts/ios-app-store.mjsnew file mode 100644index 0000000000..26aeafa2d9--- /dev/null+++ b/apps/web/scripts/ios-app-store.mjs@@ -0,0 +1,1100 @@+// App Store Connect automation for the iOS app — one executable, several+// commands sharing auth, config defaults, and app lookup:+//+// wait-build Poll until an uploaded build finishes processing and its+// export compliance is resolved (i.e. TestFlight-ready).+// ITSAppUsesNonExemptEncryption=false in src-tauri/Info.ios.plist+// answers the encryption questionnaire during processing+// (exempt encryption only); if App Store Connect still+// reports the question as unanswered (shown as "Missing+// Compliance" in TestFlight) this fails so the plist regression+// is caught rather than papered over.+//+// submit Attach the processed build to an App Store version (created+// on demand with releaseType AFTER_APPROVAL), fill in empty+// "What's New" texts, and submit it for App Review. Safe to+// re-run: an already-submitted version is a no-op success.+//+// status Report the App Store state of a version. With --require-live+// it exits non-zero unless exactly this version+build is live+// on the App Store, built from --native-tree (or this checkout's+// native code) — the gate the `iOS Native Check` job runs on+// PRs with native iOS changes.+//+// Auth (same values as ios-release.sh):+// APPLE_API_KEY App Store Connect API Key ID+// APPLE_API_ISSUER Issuer ID+// APPLE_API_KEY_P8 contents of the AuthKey .p8, or+// APPLE_API_KEY_PATH path to AuthKey_<KEYID>.p8 (defaults to+// ~/.appstoreconnect/private_keys/AuthKey_<KEYID>.p8)+// Doppler's names (ios-release/prd: APPLE_API_KEY_ID, APPLE_API_ISSUER,+// APPLE_API_PRIVATE_KEY) are accepted as fallbacks, so locally+// doppler run --project ios-release --config prd -- bun scripts/ios-app-store.mjs …+// works as-is. CI fetches the same secrets and writes the .p8 to the default path.+//+// --bundle-id / --version / --build default to the identifier in+// tauri/src-tauri/tauri.conf.json and the version / bundleVersion in+// tauri/src-tauri/tauri.ios.conf.json, so CI can run the commands bare.+//+// Usage:+// bun scripts/ios-app-store.mjs wait-build [--timeout-minutes 30]+// bun scripts/ios-app-store.mjs submit [--whats-new "release notes"]+// bun scripts/ios-app-store.mjs status [--require-live] [--require-unused-build]+// bun scripts/ios-app-store.mjs release-info+// bun scripts/ios-app-store.mjs withdraw --pr <number>+//+// release-info prints JSON for ios-bump-version.mjs: the highest build number+// App Store Connect has seen (any version, TestFlight included), whether the+// committed marketing version has ever been released, and the highest version+// string — so hand-made releases can't make the committed numbers fall behind+// and the marketing version only moves once it has actually shipped.+//+// withdraw removes PR <number>'s in-flight submission from review (the build's+// stamp names the PR) — the drift workflow runs it when native code is pushed+// after a release, so a stale build can never go live. submit later takes+// that version record over (renaming it if the version string moved).+//+// Provenance: version + build number alone don't identify a PR's native code+// (two PRs bumped from the same base get the same numbers), so wait-build+// stamps each uploaded build with the hash of the native code it was built+// from (nativeTreeHash(): the filtered `git ls-tree` of apps/web/tauri, or+// --native-tree) in its+// TestFlight "What to Test" text. status's collision check (with+// --require-unused-build, before the release builds) fails when a build at+// or above ours exists with a different stamp — another PR or a hand release — and+// reports `uploaded=true` (GITHUB_OUTPUT) when it is our own upload, so a+// release retry skips the build. The live check (--require-live) requires the+// live build's stamp to match this checkout's native tree — in the merge gate+// that checkout is the PR's merge result, so native code that landed on main+// after the release also fails it (the shipped build lacks it).++import { execFileSync } from "node:child_process";+import { appendFileSync, readFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { exit } from "node:process";+import { fileURLToPath } from "node:url";++const API_BASE = "https://api.appstoreconnect.apple.com";+const POLL_INTERVAL_MS = 30_000;++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++// appVersionState values that mean "users can download this version from the+// App Store". READY_FOR_SALE is the deprecated appStoreState spelling.+const LIVE_STATES = new Set(["READY_FOR_DISTRIBUTION", "READY_FOR_SALE"]);++// States past the point of submission — re-running `submit` on these is a+// no-op, not an error.+const SUBMITTED_STATES = new Set([+ "WAITING_FOR_REVIEW",+ "IN_REVIEW",+ "ACCEPTED",+ "PENDING_APPLE_RELEASE",+ "PENDING_DEVELOPER_RELEASE",+ "PROCESSING_FOR_DISTRIBUTION",+ "PROCESSING_FOR_APP_STORE",+ ...LIVE_STATES,+]);++// Past review: Apple approved the version and nothing can withdraw it any+// more — with release type "after approval" it is minutes from live.+const APPROVED_STATES = new Set([+ "ACCEPTED",+ "PENDING_APPLE_RELEASE",+ "PENDING_DEVELOPER_RELEASE",+ "PROCESSING_FOR_DISTRIBUTION",+ "PROCESSING_FOR_APP_STORE",+]);++// Versions that shipped and were superseded or pulled — never in flight.+const RETIRED_STATES = new Set([+ "REPLACED_WITH_NEW_VERSION",+ "REMOVED_FROM_SALE",+ "DEVELOPER_REMOVED_FROM_SALE",+ "NOT_APPLICABLE",+]);++// Review submission states that can still be withdrawn.+const WITHDRAWABLE_SUBMISSION_STATES = new Set([+ "READY_FOR_REVIEW",+ "WAITING_FOR_REVIEW",+ "IN_REVIEW",+ "UNRESOLVED_ISSUES",+]);++const BOOLEAN_FLAGS = new Set(["require-live", "require-unused-build"]);++/// "The native code": every tracked blob under this directory except what+/// never reaches the iOS binary — anything Android-only by Tauri's naming+/// convention (a path component `android`, `android_*`, `android.*` or+/// `*.android.*`), the desktop updater manifest, editor config. Must match+/// `native_tree_hash` in tooling/xtask/.../workflows/scripts/ios_native_tree.sh+/// and the iOS Native Check path filter.+const NATIVE_TREE_PATH = "apps/web/tauri";+const NATIVE_TREE_EXCLUDE = /(^|\/)android([_.\/]|$)|\.android\.|^desktop-release\.json$|^\.helix\//;+const STAMP_RE = /native tree ([0-9a-f]{40})/;+const STAMP_PR_RE = /for PR #(\d+)/;++function parseArgs(argv) {+ const args = {};+ for (let i = 0; i < argv.length; i += 1) {+ const flag = argv[i];+ if (!flag?.startsWith("--")) {+ console.error(`Malformed arguments near ${JSON.stringify(flag)}`);+ exit(2);+ }+ const name = flag.slice(2);+ if (BOOLEAN_FLAGS.has(name)) {+ args[name] = true;+ continue;+ }+ const value = argv[i + 1];+ if (value === undefined || value.startsWith("--")) {+ console.error(`Flag ${flag} requires a value`);+ exit(2);+ }+ args[name] = value;+ i += 1;+ }+ return args;+}++const [command, ...rest] = process.argv.slice(2);+if (!["wait-build", "submit", "status", "release-info", "withdraw"].includes(command ?? "")) {+ console.error(+ "Usage: ios-app-store.mjs <wait-build|submit|status|release-info|withdraw> [flags]",+ );+ exit(2);+}+const args = parseArgs(rest);++const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+function readJson(relative) {+ return JSON.parse(readFileSync(path.join(appDir, relative), "utf8"));+}++const bundleId =+ args["bundle-id"] ?? readJson("tauri/src-tauri/tauri.conf.json").identifier;++/// Hash of this checkout's native tree (--native-tree overrides, e.g. the+/// watcher, whose checkout is main), or null outside a git checkout.+function nativeTreeHash() {+ if (args["native-tree"]) {+ return args["native-tree"];+ }+ try {+ const git = (gitArgs, input) =>+ execFileSync("git", gitArgs, {+ cwd: appDir,+ encoding: "utf8",+ input,+ stdio: ["pipe", "pipe", "ignore"],+ });+ // --full-tree: ls-tree otherwise narrows its output to the cwd (apps/web).+ const listing = git(["ls-tree", "-r", "--full-tree", `HEAD:${NATIVE_TREE_PATH}`])+ .split("\n")+ .filter((line) => line && !NATIVE_TREE_EXCLUDE.test(line.split("\t")[1]))+ .map((line) => `${line}\n`)+ .join("");+ return git(["hash-object", "--stdin"], listing).trim();+ } catch {+ return null;+ }+}++function setGitHubOutput(name, value) {+ if (process.env.GITHUB_OUTPUT) {+ appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);+ }+}+const iosConf = readJson("tauri/src-tauri/tauri.ios.conf.json");+const version = args.version ?? iosConf.version;+const build = args.build ?? iosConf.bundle?.iOS?.bundleVersion;+if (!bundleId || !version || !build) {+ console.error(+ "Could not resolve --bundle-id / --version / --build from flags or tauri config.",+ );+ exit(2);+}++// Unset CI env vars surface as empty strings, so || (not ??) throughout.+const keyId = process.env.APPLE_API_KEY || process.env.APPLE_API_KEY_ID;+const issuerId = process.env.APPLE_API_ISSUER;+if (!keyId || !issuerId) {+ console.error("APPLE_API_KEY (or APPLE_API_KEY_ID) and APPLE_API_ISSUER must be set.");+ exit(2);+}++const pem =+ process.env.APPLE_API_KEY_P8 ||+ process.env.APPLE_API_PRIVATE_KEY ||+ readFileSync(+ process.env.APPLE_API_KEY_PATH ||+ path.join(os.homedir(), ".appstoreconnect", "private_keys", `AuthKey_${keyId}.p8`),+ "utf8",+ );+const privateKey = await importPrivateKey(pem);++async function importPrivateKey(pemText) {+ const base64 = pemText+ .replace(/-----(?:BEGIN|END) PRIVATE KEY-----/g, "")+ .replace(/\s+/g, "");+ const der = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+ return crypto.subtle.importKey(+ "pkcs8",+ der,+ { name: "ECDSA", namedCurve: "P-256" },+ false,+ ["sign"],+ );+}++function base64url(bytes) {+ return Buffer.from(bytes).toString("base64url");+}++// App Store Connect JWTs must be short-lived (max 20 minutes); mint a fresh+// one per request instead of tracking expiry.+async function makeToken() {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "ES256", kid: keyId, typ: "JWT" };+ const payload = { iss: issuerId, iat: now, exp: now + 600, aud: "appstoreconnect-v1" };+ const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;+ // WebCrypto ECDSA signatures are already in the raw r||s form JOSE requires.+ const signature = await crypto.subtle.sign(+ { name: "ECDSA", hash: "SHA-256" },+ privateKey,+ new TextEncoder().encode(signingInput),+ );+ return `${signingInput}.${base64url(new Uint8Array(signature))}`;+}++const RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];++/// One App Store Connect call. Network errors, 429 and 5xx are retried with+/// backoff: a single hiccup must not kill a run that has already uploaded a+/// build (that would leave the build unstamped and the number burnt). Other+/// non-2xx responses are fatal; `onError` gets a chance to explain first.+async function api(pathname, { method = "GET", body, onError } = {}) {+ let response;+ for (let attempt = 0; ; attempt += 1) {+ try {+ response = await fetch(`${API_BASE}${pathname}`, {+ method,+ headers: {+ Authorization: `Bearer ${await makeToken()}`,+ ...(body ? { "Content-Type": "application/json" } : {}),+ },+ body: body ? JSON.stringify(body) : undefined,+ });+ } catch (error) {+ response = { ok: false, status: 0, text: async () => String(error) };+ }+ const transient = response.status === 0 || response.status === 429 || response.status >= 500;+ if (!transient || attempt >= RETRY_DELAYS_MS.length) break;+ const delay = RETRY_DELAYS_MS[attempt];+ console.warn(+ `${method} ${pathname} → ${response.status || "network error"}: ${await response.text()}; ` ++ `retrying in ${delay / 1000}s (${attempt + 1}/${RETRY_DELAYS_MS.length}).`,+ );+ await sleep(delay);+ }+ if (!response.ok) {+ const text = await response.text();+ console.error(`${method} ${pathname} → ${response.status}: ${text}`);+ if (onError) {+ await onError(response.status);+ }+ exit(1);+ }+ return response.status === 204 ? null : response.json();+}++const apps = await api(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}`);+const app = apps.data[0];+if (!app) {+ console.error(`No App Store Connect app found for bundle id ${bundleId}.`);+ exit(1);+}+const testflightUrl = `https://appstoreconnect.apple.com/apps/${app.id}/testflight/ios`;+const distributionUrl = `https://appstoreconnect.apple.com/apps/${app.id}/distribution`;++/// The uploaded build record for this version+build, or null if App Store+/// Connect hasn't registered it yet.+async function findBuild() {+ const builds = await api(+ `/v1/builds?filter[app]=${app.id}` ++ `&filter[version]=${encodeURIComponent(build)}` ++ `&filter[preReleaseVersion.version]=${encodeURIComponent(version)}` ++ `&sort=-uploadedDate&limit=1`,+ );+ return builds.data[0] ?? null;+}++/// The highest build number uploaded for the app across all marketing+/// versions, as { number, version }, or null when nothing was ever uploaded.+/// Build numbers are compared numerically; non-integer ones are ignored.+async function highestUploadedBuild() {+ let pathname =+ `/v1/builds?filter[app]=${app.id}&include=preReleaseVersion` ++ "&fields[builds]=version,preReleaseVersion&fields[preReleaseVersions]=version" ++ "&sort=-uploadedDate&limit=200";+ let highest = null;+ while (pathname) {+ const page = await api(pathname);+ const preReleaseVersions = new Map(+ (page.included ?? [])+ .filter((record) => record.type === "preReleaseVersions")+ .map((record) => [record.id, record.attributes.version]),+ );+ for (const record of page.data) {+ if (!/^\d+$/.test(record.attributes.version)) continue;+ const number = Number(record.attributes.version);+ if (highest && number <= highest.number) continue;+ const preReleaseId = record.relationships?.preReleaseVersion?.data?.id;+ highest = {+ id: record.id,+ number,+ version: preReleaseVersions.get(preReleaseId) ?? "unknown",+ };+ }+ const next = page.links?.next;+ pathname = next ? next.replace(API_BASE, "") : null;+ }+ return highest;+}++/// The stamp on an uploaded build (its TestFlight "What to Test" text) as+/// { tree, pr }, or null for builds uploaded outside the release flow.+async function buildStamp(buildId) {+ const localizations = await api(`/v1/builds/${buildId}/betaBuildLocalizations?limit=10`);+ for (const localization of localizations.data) {+ const text = localization.attributes.whatsNew ?? "";+ const match = STAMP_RE.exec(text);+ if (match) {+ return { tree: match[1], pr: STAMP_PR_RE.exec(text)?.[1] ?? null };+ }+ }+ return null;+}++/// The PR number this run releases for (the stamp carries it, so later runs+/// can tell their own in-flight submission from another PR's), or null.+const releasePr = process.env.IOS_RELEASE_PR || null;++/// Record which native tree a processed build was built from, in its en-US+/// TestFlight "What to Test" text (readable back through the API).+async function stampBuild(buildRecord) {+ const tree = nativeTreeHash();+ if (!tree) {+ console.warn(+ "WARNING: not in a git checkout and no --native-tree given; the build is not " ++ "stamped with its native tree, so the merge gate will not accept it.",+ );+ return;+ }+ const pr = releasePr ? ` for PR #${releasePr}` : "";+ const whatsNew = `Built by ios-release.sh${pr} from native tree ${tree}.`;+ const localizations = await api(+ `/v1/builds/${buildRecord.id}/betaBuildLocalizations?limit=10`,+ );+ const existing = localizations.data.find(+ (localization) => localization.attributes.locale === "en-US",+ );+ if (existing) {+ await api(`/v1/betaBuildLocalizations/${existing.id}`, {+ method: "PATCH",+ body: {+ data: { type: "betaBuildLocalizations", id: existing.id, attributes: { whatsNew } },+ },+ });+ } else {+ await api("/v1/betaBuildLocalizations", {+ method: "POST",+ body: {+ data: {+ type: "betaBuildLocalizations",+ attributes: { locale: "en-US", whatsNew },+ relationships: { build: { data: { type: "builds", id: buildRecord.id } } },+ },+ },+ });+ }+ console.log(`Stamped build ${build} with native tree ${tree}.`);+}++/// Fail when a build at or above ours exists that is not our own upload: the+/// floor `min-native-build.json` derives from our number assumes it is the+/// newest native code, and the gate must never accept another PR's build+/// that happens to share our version + number. Our own earlier upload (same+/// version, same stamp) is a retry: report uploaded=true so the release+/// workflow skips the build and goes straight to submit.+async function requireUnusedBuild() {+ const rebump = `Re-bump past it and commit:+ cd apps/web && doppler run --project ios-release --config prd -- just ios-bump+${testflightUrl}`;+ // App Store Connect won't accept a version string at or below the latest+ // release, and the bump only moves the version once the committed one has+ // shipped — so a shipped version here means the PR is behind the store.+ const released = await highestReleasedVersion();+ if (compareVersions(version, released) <= 0) {+ console.error(`Marketing version ${version} is not above the latest App Store release ${released}. ${rebump}`);+ exit(1);+ }+ console.log(`Marketing version ${version} is above the latest App Store release (${released}).`);+ const highest = await highestUploadedBuild();+ if (!highest) {+ console.log("No builds uploaded yet; build number is free.");+ setGitHubOutput("uploaded", "false");+ return;+ }+ if (highest.number > Number(build)) {+ console.error(`Build ${build} is below the highest build App Store Connect has seen: \+build ${highest.number} was uploaded for version ${highest.version}+(a manual release whose number was never committed, or another native PR). ${rebump}`);+ exit(1);+ }+ if (highest.number === Number(build)) {+ const stamp = (await buildStamp(highest.id))?.tree ?? null;+ const ours = nativeTreeHash();+ if (highest.version === version && ours && stamp === ours) {+ console.log(+ `Build ${build} (${version}) was already uploaded from this native tree — ` ++ "a retry; the build and upload can be skipped.",+ );+ setGitHubOutput("uploaded", "true");+ return;+ }+ console.error(`Build ${build} was already uploaded (for version ${highest.version}) from \+different native code: its stamp is ${stamp ?? "missing (uploaded outside the release flow)"}, \+this checkout's native tree is ${ours ?? "unknown (not a git checkout)"}.+Another native PR or a hand release took this number${+ stamp ? "" : " (or a release run died between uploading and stamping it)"+ }. ${rebump}`);+ exit(1);+ }+ console.log(+ `Build ${build} is above the highest uploaded build ` ++ `(${highest.number}, version ${highest.version}).`,+ );+ setGitHubOutput("uploaded", "false");+}++function versionTriple(versionString) {+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(versionString ?? "");+ return match ? match.slice(1).map(Number) : null;+}++function compareVersions(a, b) {+ const [ta, tb] = [versionTriple(a) ?? [0, 0, 0], versionTriple(b) ?? [0, 0, 0]];+ for (let i = 0; i < 3; i += 1) {+ if (ta[i] !== tb[i]) return ta[i] - tb[i];+ }+ return 0;+}++/// All IOS appStoreVersions of the app, every page.+async function allAppStoreVersions() {+ const records = [];+ let pathname = `/v1/apps/${app.id}/appStoreVersions?filter[platform]=IOS&limit=200`;+ while (pathname) {+ const page = await api(pathname);+ records.push(...page.data);+ const next = page.links?.next;+ pathname = next ? next.replace(API_BASE, "") : null;+ }+ return records;+}++function isInFlight(record) {+ const state = versionState(record);+ return !LIVE_STATES.has(state) && !RETIRED_STATES.has(state);+}++/// The highest marketing version that has ever shipped (live or retired), or+/// "0.0.0" when none has.+async function highestReleasedVersion() {+ return (await allAppStoreVersions())+ .filter((record) => !isInFlight(record))+ .map((record) => record.attributes.versionString)+ .reduce((best, candidate) => (compareVersions(candidate, best) > 0 ? candidate : best), "0.0.0");+}++/// JSON on stdout for ios-bump-version.mjs (details on stderr).+async function releaseInfo() {+ const highest = await highestUploadedBuild();+ const versions = await allAppStoreVersions();+ const committed = versions.find((record) => record.attributes.versionString === version);+ const state = committed ? versionState(committed) : null;+ const highestVersion = versions+ .map((record) => record.attributes.versionString)+ .reduce((best, candidate) => (compareVersions(candidate, best) > 0 ? candidate : best), "0.0.0");+ const info = {+ highestBuild: highest?.number ?? 0,+ highestBuildVersion: highest?.version ?? null,+ version,+ versionState: state,+ versionReleased: committed ? !isInFlight(committed) : false,+ highestVersion,+ };+ console.error(+ `Highest uploaded build: ${info.highestBuild} (version ${info.highestBuildVersion ?? "n/a"}); ` ++ `version ${version}: ${state ?? "no App Store record"}` ++ `${info.versionReleased ? " (released)" : " (never released)"}; ` ++ `highest App Store version: ${highestVersion}.`,+ );+ console.log(JSON.stringify(info));+}++/// Withdraw an in-flight review submission. Returns true when one was+/// withdrawn, false when there was nothing withdrawable.+async function cancelOpenSubmission() {+ const submissions = await api(+ `/v1/reviewSubmissions?filter[app]=${app.id}&filter[platform]=IOS` ++ `&filter[state]=${[...WITHDRAWABLE_SUBMISSION_STATES].join(",")}&limit=25`,+ );+ const submission = submissions.data[0];+ if (!submission) {+ return false;+ }+ await api(`/v1/reviewSubmissions/${submission.id}`, {+ method: "PATCH",+ body: {+ data: {+ type: "reviewSubmissions",+ id: submission.id,+ attributes: { canceled: true },+ },+ },+ });+ console.log(+ `Withdrew review submission ${submission.id} (was ${submission.attributes.state}).`,+ );+ // Cancellation is asynchronous (CANCELING → COMPLETE); creating a new+ // submission while it is still in progress is rejected.+ const deadline = Date.now() + 5 * 60_000;+ while (true) {+ const current = await api(`/v1/reviewSubmissions/${submission.id}`);+ const state = current.data.attributes.state;+ if (!WITHDRAWABLE_SUBMISSION_STATES.has(state) && state !== "CANCELING") {+ console.log(`Review submission ${submission.id} is now ${state}.`);+ return true;+ }+ if (Date.now() > deadline) {+ console.error(`Review submission ${submission.id} is still ${state} after 5 minutes; try again later.`);+ exit(1);+ }+ await sleep(10_000);+ }+}++/// The in-flight App Store version whose attached build is stamped with the+/// given PR number, as { record, buildNumber }, or null.+async function inFlightVersionForPr(pr) {+ for (const record of await allAppStoreVersions()) {+ if (!isInFlight(record)) continue;+ const attached = await api(`/v1/appStoreVersions/${record.id}/build`);+ if (!attached.data) continue;+ const stamp = await buildStamp(attached.data.id);+ if (stamp?.pr === String(pr)) {+ return { record, buildNumber: attached.data.attributes.version, tree: stamp.tree };+ }+ }+ return null;+}++/// `withdraw --pr N`: remove PR N's in-flight submission from review (native+/// code changed after the release, so that build must never go live).+/// GITHUB_OUTPUT gets withdrawn=true|false and, if the PR's version is past+/// the point of withdrawal — approved by Apple or already shipped —+/// live=<version> (<build>) so the caller can warn loudly.+async function withdraw() {+ const pr = args.pr ?? releasePr;+ if (!pr) {+ console.error("withdraw needs --pr <number> (or IOS_RELEASE_PR).");+ exit(2);+ }+ const mine = await inFlightVersionForPr(pr);+ if (mine) {+ const state = versionState(mine.record);+ console.log(+ `PR #${pr}'s App Store version ${mine.record.attributes.versionString} ` ++ `(build ${mine.buildNumber}) is ${state}.`,+ );+ // --unless-tree <hash>: only withdraw a build that no longer matches the+ // PR's native code (the watcher's drift check for PRs the drift workflow+ // cannot see).+ if (args["unless-tree"] && mine.tree === args["unless-tree"]) {+ console.log(`Its build was built from native tree ${mine.tree}, which is still the PR's; nothing to withdraw.`);+ setGitHubOutput("withdrawn", "false");+ return;+ }+ const withdrawn = await cancelOpenSubmission();+ setGitHubOutput("withdrawn", withdrawn ? "true" : "false");+ if (!withdrawn) {+ if (APPROVED_STATES.has(state)) {+ const live = `${mine.record.attributes.versionString} (${mine.buildNumber})`;+ console.error(+ `PR #${pr}'s version ${live} is ${state}: Apple has approved it and the ` ++ "submission can no longer be withdrawn, so that build is going live.",+ );+ setGitHubOutput("live", live);+ } else {+ console.log("No withdrawable review submission; the version is already editable.");+ }+ }+ return;+ }+ setGitHubOutput("withdrawn", "false");+ // Not in flight: either never submitted, or Apple already released it.+ for (const record of await allAppStoreVersions()) {+ if (!LIVE_STATES.has(versionState(record))) continue;+ const attached = await api(`/v1/appStoreVersions/${record.id}/build`);+ if (!attached.data) continue;+ const stamp = await buildStamp(attached.data.id);+ if (stamp?.pr === String(pr)) {+ const live = `${record.attributes.versionString} (${attached.data.attributes.version})`;+ console.log(`PR #${pr}'s version ${live} is already live on the App Store.`);+ setGitHubOutput("live", live);+ return;+ }+ }+ console.log(`PR #${pr} has no in-flight App Store submission; nothing to withdraw.`);+}++/// The IOS appStoreVersion for this marketing version, or null.+async function findAppStoreVersion() {+ const versions = await api(+ `/v1/apps/${app.id}/appStoreVersions` ++ `?filter[versionString]=${encodeURIComponent(version)}` ++ `&filter[platform]=IOS&limit=1`,+ );+ return versions.data[0] ?? null;+}++function versionState(record) {+ return record.attributes.appVersionState ?? record.attributes.appStoreState;+}++async function waitBuild() {+ const timeoutMinutes = Number(args["timeout-minutes"] ?? 30);+ if (!Number.isFinite(timeoutMinutes) || timeoutMinutes <= 0) {+ console.error(`--timeout-minutes must be a positive number, got ${args["timeout-minutes"]}.`);+ exit(2);+ }+ const deadline = Date.now() + timeoutMinutes * 60_000;+ let buildRecord = null;+ while (true) {+ buildRecord = await findBuild();+ const state = buildRecord?.attributes.processingState;+ if (state && state !== "PROCESSING") {+ break;+ }+ if (Date.now() > deadline) {+ console.error(+ `Timed out after ${timeoutMinutes} minutes waiting for build ${version} (${build}) ` ++ `to finish processing. It usually still completes — check TestFlight later:` ++ `\n${testflightUrl}`,+ );+ exit(1);+ }+ console.log(+ buildRecord+ ? `Build ${version} (${build}) is processing…`+ : `Waiting for build ${version} (${build}) to appear in App Store Connect…`,+ );+ await sleep(POLL_INTERVAL_MS);+ }++ const state = buildRecord.attributes.processingState;+ if (state !== "VALID") {+ console.error(+ `Build ${version} (${build}) finished processing with state ${state}. ` ++ `Check App Store Connect for details:\n${testflightUrl}`,+ );+ exit(1);+ }+ console.log(`Build ${version} (${build}) processed successfully.`);++ // Stamp before anything else can fail: a retry then recognises the upload+ // as ours (uploaded=true) instead of demanding a re-bump.+ await stampBuild(buildRecord);++ const compliance = buildRecord.attributes.usesNonExemptEncryption;+ if (compliance === null || compliance === undefined) {+ console.error(+ "Export compliance is unanswered — ITSAppUsesNonExemptEncryption did not make " ++ 'it into the uploaded binary. The build will show as "Missing Compliance" ' ++ `in TestFlight until answered manually in App Store Connect:\n${testflightUrl}`,+ );+ exit(1);+ }+ console.log(`Export compliance resolved (usesNonExemptEncryption=${compliance}).`);+ console.log(`Build is ready for TestFlight: ${testflightUrl}`);+}++/// App Store Connect allows one iOS version in flight (anything that is not+/// live or retired) at a time. Explain which one blocks us instead of+/// surfacing the raw 409 from creating ours.+async function explainVersionInFlight() {+ const inFlight = (await allAppStoreVersions())+ .filter((record) => record.attributes.versionString !== version)+ .filter(isInFlight)+ .map((record) => `${record.attributes.versionString} (${versionState(record)})`);+ if (inFlight.length === 0) {+ console.error(`Could not create App Store version ${version}, and no other version is in flight.+If this followed a retried request the record may already exist: remove and re-add+the ios-update label to pick it up.\n${distributionUrl}`);+ return;+ }+ console.error(`Could not create App Store version ${version}: App Store Connect allows one iOS+version in flight at a time, and these are: ${inFlight.join(", ")}.+Wait for it to ship (another native PR's release) or remove it from review in App+Store Connect, then remove and re-add the ios-update label — the uploaded build+${build} is reused, only the submission is retried.+${distributionUrl}`);+}++async function submit() {+ const buildRecord = await findBuild();+ if (buildRecord?.attributes.processingState !== "VALID") {+ console.error(+ `Build ${version} (${build}) is not processed yet ` ++ `(state ${buildRecord?.attributes.processingState ?? "missing"}). ` ++ "Run `ios-app-store.mjs wait-build` first.",+ );+ exit(1);+ }++ let versionRecord = await findAppStoreVersion();+ if (versionRecord && SUBMITTED_STATES.has(versionState(versionRecord))) {+ const attached = await api(`/v1/appStoreVersions/${versionRecord.id}/build`);+ const attachedNumber = attached.data?.attributes.version ?? null;+ if (attachedNumber === build) {+ console.log(+ `App Store version ${version} (${build}) is already submitted ` ++ `(state ${versionState(versionRecord)}); nothing to do.\n${distributionUrl}`,+ );+ return;+ }+ // Submitted with another build. Ours (same PR, i.e. a stale submission+ // the drift workflow didn't get to) is withdrawn and replaced below;+ // anyone else's is left alone.+ const state = versionState(versionRecord);+ const stamp = attached.data ? await buildStamp(attached.data.id) : null;+ if (!LIVE_STATES.has(state) && releasePr && stamp?.pr === releasePr) {+ console.log(+ `App Store version ${version} is ${state} with this PR's stale build ` ++ `${attachedNumber}; withdrawing it to resubmit with build ${build}.`,+ );+ if (!(await cancelOpenSubmission())) {+ console.error(+ `App Store version ${version} (build ${attachedNumber}) is ${state}: past the point ` ++ "where a submission can be withdrawn, so that build will ship. Bump " ++ "(`just ios-bump`), commit, and re-add the ios-update label to release " ++ `build ${build} as the follow-up.\n${distributionUrl}`,+ );+ exit(1);+ }+ } else if (LIVE_STATES.has(state)) {+ console.error(+ `App Store version ${version} is already live with build ${attachedNumber ?? "none"}` ++ (stamp?.pr ? ` (released for PR #${stamp.pr})` : " (released outside the release flow)") ++ ", so the version string is used up. `just ios-bump` moves the marketing version: " ++ `bump, commit, and re-add the ios-update label.\n${distributionUrl}`,+ );+ exit(1);+ } else {+ console.error(+ `App Store version ${version} is ${state} with build ${attachedNumber ?? "none"}, ` ++ `not this PR's build ${build}` ++ (stamp?.pr ? ` (uploaded for PR #${stamp.pr})` : " (uploaded outside the release flow)") ++ ". App Store Connect allows one version in flight at a time: wait for it to " ++ "ship (then `just ios-bump` moves the version) or remove it from review in App " ++ `Store Connect, then remove and re-add the ios-update label — the uploaded build ${build} ` ++ `is reused.\n${distributionUrl}`,+ );+ exit(1);+ }+ }+ // Take over this PR's own in-flight version from an earlier release whose+ // version string has since moved on (its submission was withdrawn by the+ // drift workflow, or is withdrawn here): App Store Connect allows one+ // editable version, and its version string can be changed until approval.+ if (!versionRecord && releasePr) {+ const mine = await inFlightVersionForPr(releasePr);+ if (mine) {+ const from = mine.record.attributes.versionString;+ console.log(+ `Taking over this PR's in-flight App Store version ${from} ` ++ `(build ${mine.buildNumber}, ${versionState(mine.record)}) as ${version}.`,+ );+ await cancelOpenSubmission();+ versionRecord = (+ await api(`/v1/appStoreVersions/${mine.record.id}`, {+ method: "PATCH",+ body: {+ data: {+ type: "appStoreVersions",+ id: mine.record.id,+ attributes: { versionString: version },+ },+ },+ })+ ).data;+ console.log(`Renamed App Store version ${from} → ${version}.`);+ }+ }+ if (!versionRecord) {+ versionRecord = (+ await api("/v1/appStoreVersions", {+ method: "POST",+ onError: explainVersionInFlight,+ body: {+ data: {+ type: "appStoreVersions",+ attributes: {+ platform: "IOS",+ versionString: version,+ // Release to the App Store as soon as Apple approves — the+ // merge gate (`status --require-live`) waits for exactly that.+ releaseType: "AFTER_APPROVAL",+ },+ relationships: {+ app: { data: { type: "apps", id: app.id } },+ },+ },+ },+ })+ ).data;+ console.log(`Created App Store version ${version}.`);+ } else {+ console.log(+ `Reusing App Store version ${version} (state ${versionState(versionRecord)}).`,+ );+ }++ await api(`/v1/appStoreVersions/${versionRecord.id}/relationships/build`, {+ method: "PATCH",+ body: { data: { type: "builds", id: buildRecord.id } },+ });+ console.log(`Attached build ${build} to version ${version}.`);++ // App Review rejects an update without "What's New" text. New versions+ // inherit the previous version's metadata but start with it empty, so fill+ // it in (an explicit --whats-new always overwrites).+ const whatsNew = args["whats-new"];+ const localizations = await api(+ `/v1/appStoreVersions/${versionRecord.id}/appStoreVersionLocalizations?limit=50`,+ );+ for (const localization of localizations.data) {+ if (!whatsNew && localization.attributes.whatsNew) {+ continue;+ }+ await api(`/v1/appStoreVersionLocalizations/${localization.id}`, {+ method: "PATCH",+ body: {+ data: {+ type: "appStoreVersionLocalizations",+ id: localization.id,+ attributes: {+ whatsNew: whatsNew ?? "Bug fixes and performance improvements.",+ },+ },+ },+ });+ console.log(`Set What's New for ${localization.attributes.locale}.`);+ }++ const openSubmissions = await api(+ `/v1/reviewSubmissions?filter[app]=${app.id}&filter[platform]=IOS` ++ `&filter[state]=READY_FOR_REVIEW,WAITING_FOR_REVIEW,IN_REVIEW,UNRESOLVED_ISSUES&limit=25`,+ );+ // Reuse the open submission that already holds our version (a retry after+ // a lost response, or a version whose review raised issues); otherwise an+ // in-progress submission for something else blocks us, and a draft one+ // (READY_FOR_REVIEW) is reused.+ const holdsOurVersion = async (candidate) => {+ const items = await api(`/v1/reviewSubmissions/${candidate.id}/items?limit=50`);+ return items.data.some(+ (item) => item.relationships?.appStoreVersion?.data?.id === versionRecord.id,+ );+ };+ let submission = null;+ for (const candidate of openSubmissions.data) {+ if (await holdsOurVersion(candidate)) {+ if (candidate.attributes.state !== "READY_FOR_REVIEW") {+ console.log(+ `App Store version ${version} (${build}) is already in a review submission ` ++ `(state ${candidate.attributes.state}); nothing to do.\n${distributionUrl}`,+ );+ return;+ }+ submission = candidate;+ break;+ }+ }+ if (!submission) {+ const blocking = openSubmissions.data.find(+ (candidate) => candidate.attributes.state !== "READY_FOR_REVIEW",+ );+ if (blocking) {+ console.error(+ `A review submission is already in progress (state ${blocking.attributes.state}) ` ++ `and it does not contain version ${version}. Resolve it in App Store Connect first:` ++ `\n${distributionUrl}`,+ );+ exit(1);+ }+ submission = openSubmissions.data[0] ?? null;+ }+ if (!submission) {+ submission = (+ await api("/v1/reviewSubmissions", {+ method: "POST",+ body: {+ data: {+ type: "reviewSubmissions",+ attributes: { platform: "IOS" },+ relationships: {+ app: { data: { type: "apps", id: app.id } },+ },+ },+ },+ })+ ).data;+ }++ const items = await api(+ `/v1/reviewSubmissions/${submission.id}/items?include=appStoreVersion&limit=50`,+ );+ const hasOurVersion = items.data.some(+ (item) => item.relationships?.appStoreVersion?.data?.id === versionRecord.id,+ );+ if (!hasOurVersion) {+ await api("/v1/reviewSubmissionItems", {+ method: "POST",+ body: {+ data: {+ type: "reviewSubmissionItems",+ relationships: {+ reviewSubmission: {+ data: { type: "reviewSubmissions", id: submission.id },+ },+ appStoreVersion: {+ data: { type: "appStoreVersions", id: versionRecord.id },+ },+ },+ },+ },+ });+ }++ await api(`/v1/reviewSubmissions/${submission.id}`, {+ method: "PATCH",+ body: {+ data: {+ type: "reviewSubmissions",+ id: submission.id,+ attributes: { submitted: true },+ },+ },+ });+ console.log(+ `Submitted ${version} (${build}) for App Review. Track it at:\n${distributionUrl}`,+ );+}++async function status() {+ const requireLive = args["require-live"] === true;+ // The collision check is a pre-build check: once our version is live it is+ // the latest release, and later TestFlight uploads (another PR's) are+ // irrelevant — the live version + build + stamp below is the proof.+ if (args["require-unused-build"] === true) {+ await requireUnusedBuild();+ }+ const versionRecord = await findAppStoreVersion();++ const fail = (reason) => {+ console.error(`${reason}++This PR changes native iOS code, so iOS ${version} (build ${build}) must be+live on the App Store before merging (after the merge, the next prod deploy+applies the iOS native build floor committed in min-native-build.json and+prompts older installs to update):+ - Not started yet? Add the \`ios-update\` label to the PR to build, upload,+ and submit it for review.+ - Submitted? Wait for Apple to approve and release it. The \`iOS Release+ Watch\` workflow re-runs this check within half an hour of the release+ (or re-run it yourself).+ - If these tauri changes don't break the native/web contract, add the+ \`skip-ios-update\` label instead.+${distributionUrl}`);+ exit(1);+ };++ if (!versionRecord) {+ console.log(`No App Store version ${version} exists for ${bundleId}.`);+ if (requireLive) {+ fail(`App Store version ${version} has not been created.`);+ }+ return;+ }++ const state = versionState(versionRecord);+ const attachedBuild = await api(`/v1/appStoreVersions/${versionRecord.id}/build`);+ const attachedBuildNumber = attachedBuild.data?.attributes.version ?? null;+ console.log(+ `App Store version ${version}: state ${state}, ` ++ `build ${attachedBuildNumber ?? "not attached"}.`,+ );+ if (!requireLive) {+ return;+ }++ if (RETIRED_STATES.has(state)) {+ fail(+ `App Store version ${version} was live but has been superseded (state ${state}), ` ++ "so the store build may lack this PR's native code. Bump (`just ios-bump` moves " ++ "the version), commit, and re-add the ios-update label to release again.",+ );+ }+ if (!LIVE_STATES.has(state)) {+ fail(`App Store version ${version} is not live yet (state ${state}).`);+ }+ if (attachedBuildNumber !== build) {+ fail(+ `App Store version ${version} is live but was built from build ` ++ `${attachedBuildNumber ?? "unknown"}, not this PR's build ${build}.`,+ );+ }+ const stamp = (await buildStamp(attachedBuild.data.id))?.tree ?? null;+ const ours = nativeTreeHash();+ if (!ours || stamp !== ours) {+ console.error(`App Store version ${version} (${build}) is live, but that build was not built from+the native code this merge would produce: its stamp is ${stamp ?? "missing (uploaded outside the release flow)"},+the merge result's native tree (${NATIVE_TREE_PATH}) is ${ours ?? "unknown"}.+Either native commits were pushed to this PR after the release, native code landed+on main since the release (so the merge would contain code the shipped build lacks),+or another PR / a hand release shipped the same version + build number. Merging main+alone cannot fix it: bump again, commit, and re-add the ios-update label so what will+actually be merged gets released:+ cd apps/web && doppler run --project ios-release --config prd -- just ios-bump+${distributionUrl}`);+ exit(1);+ }+ console.log(`App Store version ${version} (${build}) is live, built from this native tree.`);+}++if (command === "wait-build") {+ await waitBuild();+} else if (command === "submit") {+ await submit();+} else if (command === "release-info") {+ await releaseInfo();+} else if (command === "withdraw") {+ await withdraw();+} else {+ await status();+}diff --git a/apps/web/scripts/ios-build.sh b/apps/web/scripts/ios-build.shindex 260a01e030..9d0f9807d5 100644--- a/apps/web/scripts/ios-build.sh+++ b/apps/web/scripts/ios-build.sh@@ -20,16 +20,7 @@ script_dir="$(\cd "$(dirname "$0")" && pwd)"source "$script_dir/ios-native-env.sh"ios_resolve_toolchain aarch64-apple-ios-# Production analytics must be configured before Vite embeds the key.-if [[ -z "${VITE_POSTHOG_API_KEY:-}" ]]; then- if ! VITE_POSTHOG_API_KEY="$(doppler secrets get VITE_POSTHOG_API_KEY \- --project web-release --config prd --plain --raw --no-check-version 2>/dev/null)" \- || [[ -z "$VITE_POSTHOG_API_KEY" ]]; then- echo "Unable to fetch VITE_POSTHOG_API_KEY. Install the Doppler CLI and authenticate with read access to web-release/prd, or supply VITE_POSTHOG_API_KEY in the environment." >&2- exit 1- fi-fi-export VITE_POSTHOG_API_KEY+ios_require_posthog_key# The web/WASM build keeps its original toolchain. Switch to Apple tools only# for the native build, and skip Tauri's hook because it has already run here.diff --git a/apps/web/scripts/ios-bump-version.mjs b/apps/web/scripts/ios-bump-version.mjsnew file mode 100644index 0000000000..9a1c82467f--- /dev/null+++ b/apps/web/scripts/ios-bump-version.mjs@@ -0,0 +1,185 @@+// Bump the iOS release numbers in one place, then sync the generated Apple+// project metadata so everything stays consistent:+//+// default App Store release for a breaking native change (the+// `ios-update` PR flow): bump the marketing version's+// patch component and the build number, and raise the iOS+// floor in min-native-build.json to the new build number so+// the next prod web deploy (`just build-prod` →+// MIN_NATIVE_BUILD_IOS) refuses to run on older native+// builds and prompts the App Store update.+// --no-min App Store release that does NOT break older native+// builds: bump marketing version + build number only.+// --build-only TestFlight iteration: bump only the build number+// (same marketing version; used by ios-release.sh).+//+// The new build number is one above the larger of the committed number and+// the highest build App Store Connect has ever seen for the app (hand-made+// releases don't always get committed, and the native build floor assumes+// numbers only go up). The marketing version only moves once the committed+// one has actually been released: a re-release after native changes (whose+// first submission was withdrawn) keeps its version and just takes a new+// build number. Both need the App Store Connect credentials:+// doppler run --project ios-release --config prd -- just ios-bump+// Without them the bump still works but warns: the build number is+// unverified and the marketing version is bumped unconditionally (safe, if+// sometimes unnecessary).+//+// Writes: tauri/src-tauri/tauri.ios.conf.json, min-native-build.json, and the+// synced gen/apple plists + project.yml (via sync-ios-bundle-metadata.mjs).+// Commit all of them.++import { execFileSync } from "node:child_process";+import { appendFileSync, readFileSync, writeFileSync } from "node:fs";+import path from "node:path";+import { exit } from "node:process";+import { fileURLToPath } from "node:url";++const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const iosConfPath = path.join(appDir, "tauri", "src-tauri", "tauri.ios.conf.json");+const minNativeBuildPath = path.join(appDir, "min-native-build.json");++const flags = new Set(process.argv.slice(2));+for (const flag of flags) {+ if (!["--no-min", "--build-only"].includes(flag)) {+ console.error(`Unknown argument: ${flag}. Usage: ios-bump-version.mjs [--no-min|--build-only]`);+ exit(2);+ }+}+if (flags.has("--no-min") && flags.has("--build-only")) {+ console.error("--no-min and --build-only are mutually exclusive.");+ exit(2);+}+const buildOnly = flags.has("--build-only");+const raiseMinNativeBuild = !buildOnly && !flags.has("--no-min");++const iosConf = JSON.parse(readFileSync(iosConfPath, "utf8"));++/// What App Store Connect knows (see `ios-app-store.mjs release-info`), or+/// null when no credentials are available (with a warning — a stale committed+/// number would then go unnoticed).+function releaseInfo() {+ const hasCredentials =+ (process.env.APPLE_API_KEY || process.env.APPLE_API_KEY_ID) && process.env.APPLE_API_ISSUER;+ if (!hasCredentials) {+ console.warn(+ "WARNING: no App Store Connect credentials, so the new build number is only " ++ "based on the committed one (a release made by hand without committing its " ++ "number would collide) and the marketing version is bumped unconditionally. " ++ "To be safe, run:\n doppler run --project ios-release --config prd -- just ios-bump",+ );+ return null;+ }+ const output = execFileSync(+ "bun",+ [path.join(appDir, "scripts", "ios-app-store.mjs"), "release-info"],+ { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] },+ ).trim();+ try {+ return JSON.parse(output);+ } catch {+ console.error(`Unexpected release-info output: ${JSON.stringify(output)}`);+ exit(1);+ }+}++function versionTriple(version) {+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version ?? "");+ return match ? match.slice(1).map(Number) : null;+}++function compareVersions(a, b) {+ const [ta, tb] = [versionTriple(a) ?? [0, 0, 0], versionTriple(b) ?? [0, 0, 0]];+ for (let i = 0; i < 3; i += 1) {+ if (ta[i] !== tb[i]) return ta[i] - tb[i];+ }+ return 0;+}++const currentBuild = iosConf.bundle?.iOS?.bundleVersion;+if (!/^\d+$/.test(currentBuild ?? "")) {+ console.error(+ `bundleVersion ${JSON.stringify(currentBuild)} in ${path.relative(appDir, iosConfPath)} ` ++ "is not a plain integer; fix it manually before bumping.",+ );+ exit(1);+}+const info = releaseInfo();+const uploadedBuild = info?.highestBuild ?? null;+if (uploadedBuild !== null && uploadedBuild > Number(currentBuild)) {+ console.log(+ `App Store Connect already has build ${uploadedBuild}, above the committed ` ++ `${currentBuild} (a release made by hand?); bumping past it.`,+ );+}+const newBuild = String(Math.max(Number(currentBuild), uploadedBuild ?? 0) + 1);+iosConf.bundle.iOS.bundleVersion = newBuild;++let newVersion = iosConf.version;+if (!buildOnly) {+ if (!versionTriple(iosConf.version)) {+ console.error(+ `version ${JSON.stringify(iosConf.version)} in ${path.relative(appDir, iosConfPath)} ` ++ 'is not of the form "major.minor.patch"; fix it manually before bumping.',+ );+ exit(1);+ }+ // A higher version already on the store (a hand release) makes the+ // committed string unusable even if it never shipped: App Store Connect+ // refuses version strings at or below the latest release.+ const higherShipped = info && compareVersions(info.highestVersion, iosConf.version) > 0;+ if (info && !info.versionReleased && !higherShipped) {+ console.log(+ `Version ${iosConf.version} has not been released to the App Store ` ++ `(${info.versionState ?? "no App Store record"}); keeping it.`,+ );+ } else {+ if (info && !info.versionReleased && higherShipped) {+ console.log(+ `Version ${iosConf.version} was never released, but App Store Connect already ` ++ `has ${info.highestVersion} above it.`,+ );+ }+ // Released (or unknown): next patch above both the committed version and+ // the highest version App Store Connect has (a hand release that was+ // never committed).+ const base =+ info && compareVersions(info.highestVersion, iosConf.version) > 0+ ? info.highestVersion+ : iosConf.version;+ if (base !== iosConf.version) {+ console.log(`App Store Connect already has version ${base}; bumping past it.`);+ }+ const [major, minor, patch] = versionTriple(base);+ newVersion = `${major}.${minor}.${patch + 1}`;+ iosConf.version = newVersion;+ }+}++writeFileSync(iosConfPath, `${JSON.stringify(iosConf, null, 2)}\n`);+console.log(+ buildOnly+ ? `Bumped build number: ${currentBuild} → ${newBuild} (version stays ${newVersion}).`+ : `Bumped iOS release: ${iosConf.version === newVersion && info && !info.versionReleased ? `${newVersion} (${currentBuild} → ${newBuild})` : `${newVersion} (${newBuild})`}.`,+);++if (raiseMinNativeBuild) {+ const floors = JSON.parse(readFileSync(minNativeBuildPath, "utf8"));+ floors.ios = Number(newBuild);+ writeFileSync(minNativeBuildPath, `${JSON.stringify(floors, null, 2)}\n`);+ console.log(+ `Raised the iOS native build floor to ${newBuild} — after this merges and prod ` ++ "deploys, older native builds will be prompted to update from the App Store.",+ );+}++execFileSync("bun", [path.join(appDir, "scripts", "sync-ios-bundle-metadata.mjs")], {+ stdio: "inherit",+});++if (process.env.GITHUB_OUTPUT) {+ appendFileSync(+ process.env.GITHUB_OUTPUT,+ `version=${newVersion}\nbuild=${newBuild}\n`,+ );+}diff --git a/apps/web/scripts/ios-native-env.sh b/apps/web/scripts/ios-native-env.shindex d25b6a31b7..fcb7402561 100644--- a/apps/web/scripts/ios-native-env.sh+++ b/apps/web/scripts/ios-native-env.sh@@ -49,3 +49,16 @@ ios_activate_toolchain() {# Use the same per-user directory as the Xcode build phase.export TMPDIR="$(/usr/bin/getconf DARWIN_USER_TEMP_DIR)"}++ios_require_posthog_key() {+ # Production analytics must be configured before Vite embeds the key.+ if [[ -z "${VITE_POSTHOG_API_KEY:-}" ]]; then+ if ! VITE_POSTHOG_API_KEY="$(doppler secrets get VITE_POSTHOG_API_KEY \+ --project web-release --config prd --plain --raw --no-check-version 2>/dev/null)" \+ || [[ -z "$VITE_POSTHOG_API_KEY" ]]; then+ echo "Unable to fetch VITE_POSTHOG_API_KEY. Install the Doppler CLI and authenticate with read access to web-release/prd, or supply VITE_POSTHOG_API_KEY in the environment." >&2+ exit 1+ fi+ fi+ export VITE_POSTHOG_API_KEY+}diff --git a/apps/web/scripts/ios-release.sh b/apps/web/scripts/ios-release.shnew file mode 100755index 0000000000..b74f00db41--- /dev/null+++ b/apps/web/scripts/ios-release.sh@@ -0,0 +1,151 @@+#!/usr/bin/env bash+# ios-release.sh — build, sign, and upload the iOS app to App Store Connect /+# TestFlight with no Xcode UI.+#+# Replaces the manual flow (just ios-build → Xcode: Archive → Validate →+# Distribute App → App Store Connect encryption questionnaire):+# 1. Bumps bundle.iOS.bundleVersion in tauri.ios.conf.json (--no-bump)+# 2. just ios-prepare (sync plist metadata, prepare SwiftPM deps)+# 3. just build-tauri — the frontend + wasm build, on the original (Nix)+# toolchain, exactly as ios-build.sh does it+# 4. cargo tauri ios build --export-method app-store-connect, with Apple's+# toolchain activated (ios-native-env.sh) and the prebuilt dist+# (xcodebuild archive + distribution-signed IPA export; the API key env+# vars below are forwarded by tauri as xcodebuild -authenticationKey…)+# 5. xcrun altool --validate-app / --upload-app (--skip-validate)+# 6. Polls the App Store Connect API until the build finishes processing+# and confirms export compliance is set (--no-wait)+#+# The encryption questionnaire is answered at build time by+# ITSAppUsesNonExemptEncryption=false in src-tauri/Info.ios.plist (exempt+# encryption only); step 6 fails if App Store Connect reports the question as+# still unanswered.+#+# Credentials: the App Store Connect team API key (App Manager role) lives in+# Doppler as ios-release/prd APPLE_API_KEY_ID / APPLE_API_ISSUER /+# APPLE_API_PRIVATE_KEY, which this script accepts directly:+# doppler run --project ios-release --config prd -- just ios-release+# (the key is written to ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8, where+# altool insists on finding it). Or set APPLE_API_KEY=<key id>+# APPLE_API_ISSUER=<issuer id> with the .p8 in that directory or at+# APPLE_API_KEY_PATH.+#+# CI runs this via the `iOS App Store Release` workflow (add the `ios-update`+# label to a PR; see docs/ios-releases.md and+# tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs),+# which handles the runner setup and passes --no-bump — the PR carries the+# version bump (`just ios-bump`).+#+# Usage: scripts/ios-release.sh [--no-bump] [--skip-validate] [--no-wait]++set -euo pipefail++APP_DIR="$(\cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+\cd "$APP_DIR"+source scripts/ios-native-env.sh++IOS_CONF="tauri/src-tauri/tauri.ios.conf.json"+TAURI_CONF="tauri/src-tauri/tauri.conf.json"+IPA_DIR="tauri/src-tauri/gen/apple/build/arm64"++BUMP=1+VALIDATE=1+WAIT=1+for arg in "$@"; do+ case "$arg" in+ --no-bump) BUMP=0 ;;+ --skip-validate) VALIDATE=0 ;;+ --no-wait) WAIT=0 ;;+ *) echo "Unknown argument: $arg" >&2; exit 2 ;;+ esac+done++step() { printf "\n\033[1;36m▸ %s\033[0m\n" "$*"; }+fail() { printf "\n\033[1;31m✗ %s\033[0m\n" "$*" >&2; exit 1; }++step "Pre-flight"+command -v bun >/dev/null || fail "bun not installed."+command -v just >/dev/null || fail "just not installed."+command -v cargo-tauri >/dev/null || cargo tauri --version >/dev/null 2>&1 \+ || fail "tauri CLI not installed (cargo install tauri-cli)."+ios_resolve_toolchain aarch64-apple-ios+# Accept Doppler's names (ios-release/prd) as fallbacks for tauri's.+export APPLE_API_KEY="${APPLE_API_KEY:-${APPLE_API_KEY_ID:-}}"+[[ -n "${APPLE_API_KEY:-}" ]] || fail "APPLE_API_KEY not set (App Store Connect API Key ID — see header)."+[[ -n "${APPLE_API_ISSUER:-}" ]] || fail "APPLE_API_ISSUER not set (App Store Connect Issuer ID — see header)."++# altool only searches ./private_keys, ~/private_keys, ~/.private_keys and+# ~/.appstoreconnect/private_keys for AuthKey_<ID>.p8, so make sure the key is+# in the canonical spot; tauri/xcodebuild take an explicit path instead.+CANONICAL_KEY_PATH="$HOME/.appstoreconnect/private_keys/AuthKey_${APPLE_API_KEY}.p8"+if [[ ! -f "$CANONICAL_KEY_PATH" && -z "${APPLE_API_KEY_PATH:-}" && -n "${APPLE_API_PRIVATE_KEY:-${APPLE_API_KEY_P8:-}}" ]]; then+ mkdir -p "$(dirname "$CANONICAL_KEY_PATH")"+ (umask 077 && printf '%s\n' "${APPLE_API_PRIVATE_KEY:-${APPLE_API_KEY_P8:-}}" > "$CANONICAL_KEY_PATH")+ echo "Wrote API key from the environment to $CANONICAL_KEY_PATH."+fi+if [[ -z "${APPLE_API_KEY_PATH:-}" ]]; then+ [[ -f "$CANONICAL_KEY_PATH" ]] \+ || fail "API key not found at $CANONICAL_KEY_PATH. Put AuthKey_${APPLE_API_KEY}.p8 there or set APPLE_API_KEY_PATH."+ export APPLE_API_KEY_PATH="$CANONICAL_KEY_PATH"+elif [[ ! -f "$APPLE_API_KEY_PATH" ]]; then+ fail "APPLE_API_KEY_PATH points to a missing file: $APPLE_API_KEY_PATH"+fi+if [[ ! -f "$CANONICAL_KEY_PATH" ]]; then+ mkdir -p "$(dirname "$CANONICAL_KEY_PATH")"+ cp "$APPLE_API_KEY_PATH" "$CANONICAL_KEY_PATH"+ chmod 600 "$CANONICAL_KEY_PATH"+ echo "Copied API key to $CANONICAL_KEY_PATH (required by altool)."+fi++BUNDLE_ID="$(bun -e "console.log(JSON.parse(require('node:fs').readFileSync('$TAURI_CONF', 'utf8')).identifier)")"++if [[ "$BUMP" == 1 ]]; then+ step "Bumping build number"+ bun scripts/ios-bump-version.mjs --build-only+fi+BUILD_NUMBER="$(bun -e "console.log(JSON.parse(require('node:fs').readFileSync('$IOS_CONF', 'utf8')).bundle.iOS.bundleVersion)")"+MARKETING_VERSION="$(bun -e "console.log(JSON.parse(require('node:fs').readFileSync('$IOS_CONF', 'utf8')).version)")"+echo "Releasing $BUNDLE_ID $MARKETING_VERSION ($BUILD_NUMBER)"++step "Preparing iOS project"+just ios-prepare++# Same split as ios-build.sh: the web/wasm build keeps its original toolchain,+# Apple's tools take over only for the native build, and Tauri's build hook is+# skipped because it has already run here.+step "Building the frontend bundle"+ios_require_posthog_key+just build-tauri++step "Archiving and exporting IPA (this takes a while)"+ios_activate_toolchain+(\cd tauri/src-tauri && "$ios_cargo" tauri ios build --export-method app-store-connect --ci \+ --config '{"build":{"beforeBuildCommand":"","frontendDist":"../../dist"}}')++IPA="$(ls -t "$IPA_DIR"/*.ipa 2>/dev/null | head -1 || true)"+[[ -n "$IPA" ]] || fail "No IPA found in $IPA_DIR after build."+echo "IPA: $IPA"++if [[ "$VALIDATE" == 1 ]]; then+ step "Validating with App Store Connect"+ xcrun altool --validate-app --type ios -f "$IPA" \+ --apiKey "$APPLE_API_KEY" --apiIssuer "$APPLE_API_ISSUER"+fi++step "Uploading to App Store Connect"+xcrun altool --upload-app --type ios -f "$IPA" \+ --apiKey "$APPLE_API_KEY" --apiIssuer "$APPLE_API_ISSUER"++if [[ "$WAIT" == 1 ]]; then+ step "Waiting for App Store Connect to process build $BUILD_NUMBER"+ bun scripts/ios-app-store.mjs wait-build \+ --bundle-id "$BUNDLE_ID" \+ --version "$MARKETING_VERSION" \+ --build "$BUILD_NUMBER"+fi++printf "\n\033[1;32m✓ %s %s (%s) uploaded to App Store Connect.\033[0m\n" \+ "$BUNDLE_ID" "$MARKETING_VERSION" "$BUILD_NUMBER"+if [[ "$BUMP" == 1 ]]; then+ echo "Don't forget to commit the version bump ($IOS_CONF and synced plists)."+fidiff --git a/apps/web/scripts/ios-verify-native-bump.mjs b/apps/web/scripts/ios-verify-native-bump.mjsnew file mode 100644index 0000000000..9c6d42e388--- /dev/null+++ b/apps/web/scripts/ios-verify-native-bump.mjs@@ -0,0 +1,120 @@+// Verify this branch bumped the iOS release numbers relative to the base+// branch. Fail-fast guard used by the `iOS Native Check` merge gate and by+// `iOS App Store Release` before spending ~40 minutes building: a PR with+// native iOS changes must ship a new App Store release, which requires+// - a marketing version no lower than the base's (it only moves once the+// committed one has shipped — a re-release keeps it),+// - a higher build number, and+// - the iOS floor in min-native-build.json either raised to that build+// number, so the next prod web deploy locks out older native builds, or+// left exactly as the base has it (`just ios-bump --no-min`: a release+// older installs don't need). Run `just ios-bump` to do all three; see+// scripts/ios-bump-version.mjs. Whether the version is above the latest+// App Store release is checked by `ios-app-store.mjs status`, which can+// ask App Store Connect.+//+// The base ref defaults to origin/main; override with BASE_REF. Requires the+// base ref to be fetched (CI checks out with full history).++import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import path from "node:path";+import { exit } from "node:process";+import { fileURLToPath } from "node:url";++const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const baseRef = process.env.BASE_REF || "origin/main";++// Repo-root-relative paths, as `git show <ref>:<path>` requires.+const IOS_CONF = "apps/web/tauri/src-tauri/tauri.ios.conf.json";+const MIN_NATIVE_BUILD = "apps/web/min-native-build.json";++function baseFile(repoPath) {+ try {+ return execFileSync("git", ["-C", appDir, "show", `${baseRef}:${repoPath}`], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ });+ } catch {+ return null;+ }+}++const baseConfText = baseFile(IOS_CONF);+if (baseConfText === null) {+ console.error(+ `Could not read ${IOS_CONF} at ${baseRef} — is the base ref fetched?`,+ );+ exit(1);+}+const baseConf = JSON.parse(baseConfText);+const headConf = JSON.parse(+ readFileSync(path.join(appDir, "tauri", "src-tauri", "tauri.ios.conf.json"), "utf8"),+);+const headMin = JSON.parse(readFileSync(path.join(appDir, "min-native-build.json"), "utf8"));+const baseMinText = baseFile(MIN_NATIVE_BUILD);+const baseMinIos = baseMinText === null ? null : JSON.parse(baseMinText).ios;++const baseVersion = baseConf.version;+const headVersion = headConf.version;+const baseBuild = Number(baseConf.bundle?.iOS?.bundleVersion);+const headBuild = Number(headConf.bundle?.iOS?.bundleVersion);++function versionTriple(version) {+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version ?? "");+ return match ? match.slice(1).map(Number) : null;+}++const errors = [];++function compareTriples(a, b) {+ for (let i = 0; i < 3; i += 1) {+ if (a[i] !== b[i]) return a[i] - b[i];+ }+ return 0;+}++const baseTriple = versionTriple(baseVersion);+const headTriple = versionTriple(headVersion);+if (!headTriple) {+ errors.push(`version ${JSON.stringify(headVersion)} is not "major.minor.patch".`);+} else if (baseTriple && compareTriples(headTriple, baseTriple) < 0) {+ errors.push(+ `version is ${headVersion}, below ${baseRef}'s ${baseVersion} — it must not go backwards.`,+ );+}++if (!Number.isInteger(headBuild)) {+ errors.push(`bundleVersion ${JSON.stringify(headConf.bundle?.iOS?.bundleVersion)} is not an integer.`);+} else if (Number.isInteger(baseBuild) && headBuild <= baseBuild) {+ errors.push(+ `bundleVersion is ${headBuild}, but ${baseRef} is already at ${baseBuild} — it must increase.`,+ );+}++if (headMin.ios !== headBuild && headMin.ios !== baseMinIos) {+ errors.push(+ `min-native-build.json has ios ${headMin.ios}, expected the new build number ` ++ `${headBuild} so older native builds get locked out after the prod deploy` ++ (baseMinIos === null ? "." : ` (or ${baseMinIos}, unchanged from ${baseRef}, for a release older installs don't need).`),+ );+}++if (errors.length > 0) {+ console.error(+ `This PR changes native iOS code but has not bumped the iOS release numbers vs ${baseRef}:`,+ );+ for (const error of errors) {+ console.error(` - ${error}`);+ }+ console.error(+ "\nRun `just ios-bump` in apps/web and commit the result " ++ "(tauri.ios.conf.json, min-native-build.json, and the synced gen/apple metadata).",+ );+ exit(1);+}++console.log(+ `iOS release numbers are bumped: ${baseVersion} (${baseBuild}) → ${headVersion} (${headBuild}), ` ++ `iOS floor ${headMin.ios}${headMin.ios === headBuild ? "" : " (unchanged: older installs are not locked out)"}.`,+);diff --git a/apps/web/tauri/src-tauri/Info.ios.plist b/apps/web/tauri/src-tauri/Info.ios.plistindex 6dcd8080cd..724ad17d67 100644--- a/apps/web/tauri/src-tauri/Info.ios.plist+++ b/apps/web/tauri/src-tauri/Info.ios.plist@@ -18,6 +18,13 @@</array></dict></dict>+ <!-- The app only uses exempt encryption (HTTPS / OS-provided crypto), so+ App Store Connect's questionnaire resolves to "no documentation+ required". Declaring that here answers it for every uploaded build+ instead of by hand per build. Keep gen/apple/project.yml and+ gen/apple/app_iOS/Info.plist in sync. -->+ <key>ITSAppUsesNonExemptEncryption</key>+ <false/><key>UIBackgroundModes</key><array><string>audio</string>diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex b9f4341d74..d7927ada9b 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -182,7 +182,10 @@ GraphQL hydration checkpoints require the nativethrough the bundle updater, set `MIN_NATIVE_BUILD_ANDROID` to the first AndroidversionCode that implements the command and `MIN_NATIVE_BUILD_IOS` to the firstiOS CFBundleVersion that implements it. Set both together: build numbers are-independent. The schema 3 manifest carries `minNativeBuilds: { android, ios }`;+independent. Production builds (`just build-prod`) read both from+`apps/web/min-native-build.json`; `just ios-bump` raises the iOS one (see+`apps/web/docs/ios-releases.md`). The schema 3 manifest carries+`minNativeBuilds: { android, ios }`;the endpoint returns the requesting platform's minimum in its existing response.The updater checks that minimum during extraction, restore, and application.Old schema 2 updaters reject schema 3 and continue using their existing bundle.diff --git a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plistindex ae0b916dc4..e9b6a55fc2 100644--- a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist@@ -29,6 +29,8 @@</array><key>CFBundleVersion</key><string>187</string>+ <key>ITSAppUsesNonExemptEncryption</key>+ <false/><key>LSApplicationQueriesSchemes</key><array><string>macro</string>diff --git a/apps/web/tauri/src-tauri/gen/apple/project.yml b/apps/web/tauri/src-tauri/gen/apple/project.ymlindex 6affaced55..df94837adf 100644--- a/apps/web/tauri/src-tauri/gen/apple/project.yml+++ b/apps/web/tauri/src-tauri/gen/apple/project.yml@@ -60,6 +60,10 @@ targets:- UIInterfaceOrientationLandscapeRightCFBundleShortVersionString: 2.0.10CFBundleVersion: "187"+ # Exempt encryption only (HTTPS / OS crypto): answers App Store+ # Connect's export-compliance questionnaire for every build. Keep in+ # sync with src-tauri/Info.ios.plist.+ ITSAppUsesNonExemptEncryption: falseCFBundleURLTypes:- CFBundleURLSchemes:- macrodiff --git a/docs/development/android.md b/docs/development/android.mdindex 1b61556264..2726764d6b 100644--- a/docs/development/android.md+++ b/docs/development/android.md@@ -195,7 +195,8 @@ both apps claim the same `macro://` authentication and navigation callbacks.`MIN_NATIVE_BUILD_ANDROID` remains a separate compatibility floor. For the firstbuild with runtime GraphQL SDL and schema 3 OTA support (#7724 and #7303), it is-**1**. Set it alongside `MIN_NATIVE_BUILD_IOS` when building the OTA frontend.+**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 frontendrequires newer native capabilities. Older date-coded test APKs exceed this floor,so retire them rather than relying on it to exclude those test installs.diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows.rs b/tooling/xtask/crates/xtask_workflows/src/workflows.rsindex 50a10dc740..901c7a6ecd 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows.rs@@ -37,7 +37,11 @@ mod deploy_web_app;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 path_validation;mod publish_sdk;mod pulumi_preview_pr;@@ -286,6 +290,26 @@ const WORKFLOWS: &[WorkflowFile] = &[file_name: "release-sdk.yml",render_yaml: || render_gh_workflow(release_sdk::release_sdk)(),},+ WorkflowFile {+ slug: "ios_app_store_release",+ file_name: "ios-app-store-release.yml",+ 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)(),+ },+ WorkflowFile {+ slug: "ios_release_drift",+ file_name: "ios-release-drift.yml",+ render_yaml: || render_gh_workflow(ios_release_drift::ios_release_drift)(),+ },+ WorkflowFile {+ slug: "ios_release_watch",+ file_name: "ios-release-watch.yml",+ render_yaml: || render_gh_workflow(ios_release_watch::ios_release_watch)(),+ },WorkflowFile {slug: "pulumi_preview_pr",file_name: "pulumi_preview_pr.yml",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.rsnew file mode 100644index 0000000000..f2a61ed85b--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_app_store_release.rs@@ -0,0 +1,273 @@+//! `iOS App Store Release` — add the `ios-update` label to a PR with breaking+//! native (Tauri) changes and this workflow builds the iOS app from the PR+//! head, uploads it to TestFlight, and submits it for App Review — the release+//! the `iOS Native Check` merge gate (a job of [`super::web_app_check_main`]) then waits on+//! ([`super::ios_release_watch`] re-runs the gate once Apple releases it).+//! The success comment tells the author to enable GitHub auto-merge on the+//! PR if they want it merged the moment Apple approves. The workflow does not+//! enable it itself: that would need a user token (a merge set up by the+//! Actions token does not trigger the push-to-main workflows, the dev+//! redeploy among them), and nobody's PAT belongs in a repo secret.+//!+//! The PR must already contain the version bump (`just ios-bump` in+//! `apps/web`, committed): the workflow verifies it and fails fast otherwise.+//! Bumping from CI would need a push with a PAT — a `GITHUB_TOKEN` push never+//! re-triggers the PR's required checks, wedging the PR — so the bump stays a+//! one-command local step and release retries stay label-driven (remove and+//! re-add `ios-update`).+//!+//! Runs like [`super::ios_preview`]: the Namespace macOS runner, with+//! cargo-tauri, bun, just, wasm-pack and the pinned toolchain (which carries+//! `aarch64-apple-ios`) from the Nix dev shell. `ios-release.sh` does the+//! Nix-vs-Xcode toolchain split itself through `ios-native-env.sh`, so one+//! `nix develop` invocation covers the whole build.+//!+//! Credentials come from Doppler (`ios-release/prd`, read with the+//! `IOS_RELEASE_DOPPLER_TOKEN` service token, like the DMG workflow's+//! `macos-release/prd`): the App Store Connect team API key (App Manager+//! role) and optionally an Apple Distribution certificate; without the+//! certificate xcodebuild uses cloud signing through the API key.++use gh_workflow::{+ Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,+ Step, Use, Workflow,+};++use crate::workflows::{runners, steps, vars};++/// Build the workflow.+pub fn ios_app_store_release() -> Workflow {+ Workflow::new("iOS App Store Release")+ .on(Event::default()+ .pull_request(PullRequest::default().add_type(PullRequestType::Labeled)))+ .concurrency(Concurrency::new(Expression::new(+ "ios-app-store-release-${{ github.event.pull_request.number }}",+ )))+ .add_job("release", release_job())+}++fn release_job() -> Job {+ Job::default()+ .name("iOS App Store Release")+ // Same-repo PRs only: the release needs the App Store Connect secrets,+ // which fork PRs don't receive anyway.+ .cond(Expression::new(+ "github.event.label.name == 'ios-update' && \+ github.event.pull_request.head.repo.full_name == github.repository",+ ))+ .runs_on(runners::Runner::MacOsArm.to_string())+ // Device build + upload + up to 30 minutes of App Store Connect+ // processing; the simulator preview alone measured ~11 minutes cold.+ .timeout_minutes(90u32)+ .permissions(+ Permissions::default()+ .checks(Level::Read)+ .contents(Level::Read)+ .pull_requests(Level::Write)+ // `gh pr checks` also reads commit statuses (the CLA check).+ .statuses(Level::Read),+ )+ .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(require_cli_tools())+ .add_step(preconditions())+ .add_step(steps::install_nix_macos())+ .add_step(verify_bump())+ .add_step(fetch_credentials())+ .add_step(require_unused_build())+ .add_step(configure_signing())+ .add_step(build_and_upload())+ .add_step(head_guard())+ .add_step(submit_for_review())+ .add_step(pr_comment())+}++/// `ios-update` means "release this and merge it when Apple approves", so the+/// PR must already be mergeable: not a draft, every other check on the head+/// commit green (pending ones are waited on). Fails before the long build.+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/ios_release_preconditions.sh")+ ))+ .shell("bash")+ .add_env(("HEAD_SHA", "${{ github.event.pull_request.head.sha }}"))+ .add_env(("WAIT_MINUTES", "30"))+}++/// The pre-build steps run outside the Nix dev shell (it isn't installed+/// yet) and need `gh` + `jq`; the Namespace macOS image is not guaranteed to+/// ship them.+fn require_cli_tools() -> Step<Run> {+ Step::new("Ensure gh and jq are installed")+ .run(indoc::indoc! {r#"+ set -euo pipefail+ for tool in gh jq; do+ if ! command -v "$tool" >/dev/null; then+ echo "${tool} missing on this runner; installing with Homebrew."+ brew install "$tool"+ fi+ done+ gh --version | head -1+ jq --version+ "#})+ .shell("bash")+}++/// Native code pushed while the build ran would make the upload stale; don't+/// submit it (the drift workflow also withdraws after the fact).+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/ios_release_head_guard.sh")+ ))+ .shell("bash")+}++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 }}"))+ // Full history so the bump check can diff against the base branch.+ .add_with(("fetch-depth", 0))+ .add_with(("persist-credentials", false))+}++/// Run a command in `apps/web` inside the Nix dev shell.+fn in_dev_shell(name: &str, commands: &str) -> Step<Run> {+ Step::new(name)+ .run(format!(+ "nix develop --command bash -euo pipefail -c '\n{commands}'"+ ))+ .shell("bash")+}++fn verify_bump() -> Step<Run> {+ in_dev_shell(+ "Verify iOS release numbers were bumped",+ " cd apps/web\n bun scripts/ios-verify-native-bump.mjs\n",+ )+ .add_env((+ "BASE_REF",+ "origin/${{ github.event.pull_request.base.ref }}",+ ))+}++/// Writes the API key where altool/tauri/the scripts look for it and exports+/// `APPLE_API_KEY` / `APPLE_API_ISSUER` (plus the optional distribution+/// certificate path) through `GITHUB_ENV` for the steps below.+fn fetch_credentials() -> Step<Run> {+ Step::new("Fetch App Store Connect credentials from Doppler")+ .run(include_str!("scripts/ios_app_store_connect_credentials.sh"))+ .shell("bash")+ .add_env(("DOPPLER_TOKEN", vars::IOS_RELEASE_DOPPLER_TOKEN))+ .add_env(("IOS_DISTRIBUTION_CERTIFICATE", "1"))+}++/// Fail before the (long) build if App Store Connect already holds a build at+/// or above this PR's number that is not our own upload — another native PR+/// bumped from the same base, or a hand-made release whose bump was never+/// committed; the floor derived from the number would otherwise be wrong.+/// Our own earlier upload (same version, same native-tree stamp) sets+/// `uploaded=true`, and the build step is skipped: a retry goes straight to+/// submit, since Apple rejects re-uploading a build number anyway.+fn require_unused_build() -> Step<Run> {+ in_dev_shell(+ "Check the build number is unused in App Store Connect",+ " cd apps/web\n bun scripts/ios-app-store.mjs status --require-unused-build\n",+ )+ .id("build-check")+}++fn configure_signing() -> Step<Run> {+ Step::new("Configure signing identity")+ .run(include_str!("scripts/ios_release_signing.sh"))+ .shell("bash")+}++/// Build, validate, upload, and wait for App Store Connect processing ++/// export compliance — the PR already carries the bump, hence `--no-bump`.+/// The PostHog key is what `ios-build.sh` would otherwise pull from Doppler.+/// `wait-build` stamps the processed build with the native tree it was built+/// from (and the PR number), which the merge gate later verifies.+fn build_and_upload() -> Step<Run> {+ in_dev_shell(+ "Build and upload to App Store Connect",+ " bun install --frozen-lockfile\n cd apps/web\n just ios-release --no-bump\n",+ )+ .if_condition(Expression::new(+ "steps.build-check.outputs.uploaded != 'true'",+ ))+ .add_env(("VITE_POSTHOG_API_KEY", vars::POSTHOG_API_KEY))+ .add_env(("IOS_RELEASE_PR", "${{ github.event.pull_request.number }}"))+}++/// `IOS_RELEASE_PR` lets `submit` recognise (and take over) this PR's own+/// earlier in-flight version from its build stamp.+fn submit_for_review() -> Step<Run> {+ in_dev_shell(+ "Submit for App Review",+ " cd apps/web\n bun scripts/ios-app-store.mjs submit\n",+ )+ .add_env(("IOS_RELEASE_PR", "${{ github.event.pull_request.number }}"))+}++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 fs = require('fs');+ const confPath = 'apps/web/tauri/src-tauri/tauri.ios.conf.json';+ const conf = fs.existsSync(confPath)+ ? JSON.parse(fs.readFileSync(confPath, 'utf8'))+ : { version: '?', bundle: { iOS: { bundleVersion: '?' } } };+ const version = conf.version;+ const build = conf.bundle.iOS.bundleVersion;+ const runUrl =+ `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` ++ `/actions/runs/${context.runId}`;+ const success = '${{ job.status }}' === 'success';+ const body = success+ ? [+ `📱 iOS ${version} (build ${build}) was uploaded to TestFlight and submitted for App Review.`,+ '',+ 'When Apple approves it, the version releases to the App Store automatically,',+ 'the **iOS Release Watch** workflow re-runs the **iOS 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 iOS native build floor committed in `min-native-build.json`, prompting older installs to update.',+ '',+ `[Workflow run](${runUrl})`,+ ].join('\n')+ : [+ `📱 iOS App Store release for ${version} (build ${build}) **failed** — see the [workflow run](${runUrl}).`,+ '',+ 'Fix the problem, then remove and re-add the `ios-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/ios_native_check_label.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rsnew file mode 100644index 0000000000..5eb1f41111--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_native_check_label.rs@@ -0,0 +1,55 @@+//! `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/ios_release_drift.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_drift.rsnew file mode 100644index 0000000000..1eea060df4--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_drift.rs@@ -0,0 +1,180 @@+//! `iOS Release Drift` — runs on every push to a PR that carries the+//! `ios-update` label, i.e. a PR whose iOS build is (or is about to be) in+//! App Review. Web-only pushes are fine: the embedded web bundle is replaced+//! over the air after the merge. Native pushes make the uploaded build+//! stale, and with release type "after approval" a stale build Apple approves+//! goes straight to the App Store — so when `apps/web/tauri` changed this+//! workflow:+//!+//! 1. cancels any [`super::ios_app_store_release`] run still building the+//! old head and waits for it to stop,+//! 2. withdraws the PR's submission from review in App Store Connect+//! (`ios-app-store.mjs withdraw`, found by the PR number in the build+//! stamp) so nothing stale can go live,+//! 3. removes the `ios-update` label (which also stops+//! [`super::ios_release_watch`] watching the PR), and+//! 4. comments what to do: bump, commit, re-add the label. The re-release+//! keeps the marketing version and `submit` takes the withdrawn version+//! record over.+//!+//! If Apple had already approved or released the stale build there is+//! nothing to withdraw; the comment then says so loudly.++use gh_workflow::{+ Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run, Step, Use,+ Workflow,+};++use crate::workflows::{runners, steps, vars};++const CHANGED: &str = "steps.detect.outputs.changed == 'true'";++/// Build the workflow.+pub fn ios_release_drift() -> Workflow {+ Workflow::new("iOS 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("iOS Release Drift")+ .cond(Expression::new(+ "contains(github.event.pull_request.labels.*.name, 'ios-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)+ .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(detect())+ .add_step(cancel_release_runs())+ .add_step(setup_bun())+ .add_step(fetch_credentials())+ .add_step(withdraw())+ .add_step(remove_label())+ .add_step(comment())+}++fn changed() -> Expression {+ Expression::new(CHANGED)+}++fn detect() -> Step<Run> {+ Step::new("Detect native changes in this push")+ .run(concat!(+ include_str!("scripts/ios_native_tree.sh"),+ include_str!("scripts/ios_release_drift.sh")+ ))+ .id("detect")+ .shell("bash")+ .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 ios-app-store-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 build of the old head)."+ gh run cancel "$run_id" --repo "$GH_REPO" || true+ done+ # Wait for them to stop: a run already inside `submit` could+ # otherwise submit after the withdrawal below looked for nothing.+ 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; withdrawing anyway."+ break+ fi+ sleep 10+ done+ done+ "#})+ .if_condition(changed())+ .shell("bash")+ .add_env(("HEAD_REF", "${{ github.event.pull_request.head.ref }}"))+}++fn setup_bun() -> Step<Use> {+ Step::new("Setup Bun")+ .uses(+ "oven-sh",+ "setup-bun",+ "0c5077e51419868618aeaa5fe8019c62421857d6",+ ) // v2.2.0+ .if_condition(changed())+ .add_with(("bun-version", "1.3.13"))+}++fn fetch_credentials() -> Step<Run> {+ Step::new("Fetch App Store Connect credentials from Doppler")+ .run(include_str!("scripts/ios_app_store_connect_credentials.sh"))+ .shell("bash")+ .if_condition(changed())+ .add_env(("DOPPLER_TOKEN", vars::IOS_RELEASE_DOPPLER_TOKEN))+}++fn withdraw() -> Step<Run> {+ Step::new("Withdraw the PR's App Store submission")+ .run("bun scripts/ios-app-store.mjs withdraw --pr \"$PR_NUMBER\"")+ .id("withdraw")+ .if_condition(changed())+ .working_directory(xtask_paths::repo_dir!("apps/web"))+}++/// `always()`: even if the withdrawal call failed (App Store Connect or+/// Doppler hiccup), the label must come off and someone must be told —+/// otherwise the stale build stays in review unnoticed.+fn after_withdraw() -> Expression {+ Expression::new(format!("always() && {CHANGED}"))+}++fn remove_label() -> Step<Run> {+ Step::new("Remove the ios-update label")+ .run("gh pr edit \"$PR_NUMBER\" --repo \"$GH_REPO\" --remove-label ios-update")+ .if_condition(after_withdraw())+ .shell("bash")+}++fn comment() -> Step<Run> {+ Step::new("Comment on the PR")+ .run(indoc::indoc! {r#"+ set -euo pipefail+ bump='cd apps/web && doppler run --project ios-release --config prd -- just ios-bump'+ if [[ "$WITHDRAW_OUTCOME" != "success" ]]; then+ body="🚨 Native changes were pushed to this PR after its App Store release started, but withdrawing the App Review submission **failed** (see the [workflow run](${RUN_URL})). If a submission is pending, remove it from review in App Store Connect by hand so the stale build cannot go live. The \`ios-update\` label was removed; when the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`ios-update\`."+ elif [[ -n "$LIVE" ]]; then+ body="🚨 Native changes were pushed to this PR after Apple had already approved iOS ${LIVE}, so that build is (or is about to be) live with native code this PR no longer matches. Bump (\`${bump}\`), commit, re-add the \`ios-update\` label, and ship the follow-up as soon as possible. The label was removed."+ else+ body="📱 Native code changed after this PR's App Store release started, so the release was stopped: any in-progress build was cancelled and any pending App Review submission withdrawn (nothing stale can go live), and the \`ios-update\` label was removed. When the PR is ready again, bump (\`${bump}\`; the marketing version stays, the build number moves), commit, push, and re-add \`ios-update\`."+ fi+ gh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"+ "#})+ .if_condition(after_withdraw())+ .shell("bash")+ .add_env(("LIVE", "${{ steps.withdraw.outputs.live }}"))+ .add_env(("WITHDRAW_OUTCOME", "${{ steps.withdraw.outcome }}"))+ .add_env((+ "RUN_URL",+ "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}",+ ))+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_watch.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_watch.rsnew file mode 100644index 0000000000..4f91b5d311--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/ios_release_watch.rs@@ -0,0 +1,109 @@+//! `iOS Release Watch` — half-hourly cron closing the loop of the `iOS+//! Native Check` gate (a job of [`super::web_app_check_main`]): that check+//! fails on a PR with breaking native changes until the matching iOS version+//! is live on the App Store, and nothing on GitHub's side notices when Apple+//! releases it. This workflow looks at every open PR labeled `ios-update`+//! (the label that started the [`super::ios_app_store_release`] run), asks+//! App Store Connect whether the version + build committed at the PR head is+//! live (built from the native tree of the PR's merge result, like the gate+//! checks), and when it is, re-runs the PR's failed `iOS 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.+//!+//! It also backs up [`super::ios_release_drift`]: GitHub does not run+//! pull_request workflows on a PR that conflicts with main, so a native push+//! to such a PR is only noticed here — the in-flight build's stamp is+//! compared with the head's native code and a stale submission withdrawn.+//!+//! Credentials come from Doppler like the other two iOS workflows; the+//! common case (no labeled PRs) exits before fetching anything.++use gh_workflow::{+ Event, Expression, Job, Level, Permissions, Run, Schedule, Step, Use, Workflow,+ WorkflowDispatch,+};++use crate::workflows::{runners, steps, vars};++/// `true` when the first step found at least one PR to look at.+const HAS_PRS: &str = "steps.prs.outputs.count != '0'";++/// Build the workflow.+pub fn ios_release_watch() -> Workflow {+ Workflow::new("iOS Release Watch")+ .on(Event::default()+ .add_schedule(Schedule::new("*/30 * * * *"))+ .workflow_dispatch(WorkflowDispatch::default()))+ .permissions(+ Permissions::default()+ .actions(Level::Write)+ .contents(Level::Read)+ .pull_requests(Level::Write),+ )+ .add_job("watch", watch_job())+}++fn watch_job() -> Job {+ Job::default()+ .name("Re-run the iOS Native Check once the App Store 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(fetch_credentials())+ .add_step(rerun_live_checks())+}++fn gated() -> Expression {+ Expression::new(HAS_PRS)+}++fn find_prs() -> Step<Run> {+ Step::new("Find PRs waiting on an App Store release")+ .run(indoc::indoc! {r#"+ set -euo pipefail+ prs=$(gh pr list --repo "$GH_REPO" --label ios-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 ios-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 fetch_credentials() -> Step<Run> {+ Step::new("Fetch App Store Connect credentials from Doppler")+ .run(include_str!("scripts/ios_app_store_connect_credentials.sh"))+ .shell("bash")+ .if_condition(gated())+ .add_env(("DOPPLER_TOKEN", vars::IOS_RELEASE_DOPPLER_TOKEN))+}++fn rerun_live_checks() -> Step<Run> {+ Step::new("Re-run the check on PRs whose release is live")+ .run(concat!(+ include_str!("scripts/ios_native_tree.sh"),+ include_str!("scripts/ios_release_watch.sh")+ ))+ .shell("bash")+ .if_condition(gated())+ .add_env(("PRS", "${{ steps.prs.outputs.prs }}"))+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/path_validation.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/path_validation.rsindex 2040f26fef..0de314325b 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/path_validation.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/path_validation.rs@@ -178,6 +178,9 @@ fn validate_dorny_filters(filters: &str, repo_root: &Path, context: &str) -> Resyaml_key(group_name))})?;+ // `!pattern` excludes paths matched by an earlier pattern; the+ // excluded paths must exist like any other.+ let pattern = pattern.strip_prefix('!').unwrap_or(pattern);validate_glob(pattern,repo_root,@@ -278,6 +281,27 @@ jobs:assert!(error.contains("definitely-missing"));}+ #[test]+ fn validates_negated_embedded_path_filters_like_positive_ones() {+ let yaml = r#"+jobs:+ check:+ steps:+ - name: Filter+ uses: dorny/paths-filter@v3+ with:+ filters: |+ changed:+ - apps/web/tauri/**+ - '!apps/web/tauri/android_*/**'+"#;+ validate("fixture.yml", yaml, &xtask_paths::repo_root()).unwrap();++ let yaml = yaml.replace("android_*", "definitely-missing");+ let error = validate("fixture.yml", &yaml, &xtask_paths::repo_root()).unwrap_err();+ assert!(format!("{error:#}").contains("matches no paths"));+ }+#[test]fn rejects_missing_embedded_path_filters() {let yaml = r#"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_app_store_connect_credentials.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_app_store_connect_credentials.shnew file mode 100644index 0000000000..8fb5679186--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_app_store_connect_credentials.sh@@ -0,0 +1,59 @@+set -euo pipefail+# Fetch the App Store Connect credentials from Doppler (ios-release/prd) —+# the same shape as the DMG workflow's notarization step — and hand them to+# later steps the way the iOS scripts expect them:+# APPLE_API_KEY / APPLE_API_ISSUER exported via GITHUB_ENV+# ~/.appstoreconnect/private_keys/AuthKey_<ID>.p8 the private key, where+# altool, tauri (APPLE_API_KEY_PATH default) and ios-app-store.mjs look+# With IOS_DISTRIBUTION_CERTIFICATE=1 the optional Apple Distribution .p12 is+# decoded to $RUNNER_TEMP and exported as APPLE_DISTRIBUTION_CERTIFICATE_PATH+# / _PASSWORD for the signing step.+if [ -z "${DOPPLER_TOKEN:-}" ]; then+ echo "DOPPLER_TOKEN is empty: the IOS_RELEASE_DOPPLER_TOKEN secret is missing, or this is a fork PR (secrets are not available to forks; a maintainer must run the release from a branch in this repository, or add skip-ios-update if the change is non-breaking)." >&2+ exit 1+fi++umask 077+secrets=$(mktemp)+trap 'rm -f "$secrets"' EXIT+curl --fail --silent --show-error --retry 3 \+ --header "Authorization: Bearer $DOPPLER_TOKEN" \+ 'https://api.doppler.com/v3/configs/config/secrets/download?project=ios-release&config=prd&format=json' \+ > "$secrets"++required() {+ jq -er --arg name "$1" '.[$name] | strings | select(length > 0)' "$secrets" \+ || { echo "ios-release/prd is missing $1" >&2; exit 1; }+}+key_id=$(required APPLE_API_KEY_ID)+issuer=$(required APPLE_API_ISSUER)++key_dir="$HOME/.appstoreconnect/private_keys"+mkdir -p "$key_dir"+key_path="$key_dir/AuthKey_${key_id}.p8"+required APPLE_API_PRIVATE_KEY > "$key_path"+echo "::add-mask::$issuer"+{+ echo "APPLE_API_KEY=$key_id"+ echo "APPLE_API_ISSUER=$issuer"+} >> "$GITHUB_ENV"+echo "Wrote App Store Connect API key $key_id to $key_path"++if [ "${IOS_DISTRIBUTION_CERTIFICATE:-}" = "1" ]; then+ certificate=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_BASE64 // empty' "$secrets")+ if [ -z "$certificate" ]; then+ echo "No APPLE_DISTRIBUTION_CERTIFICATE_BASE64 in ios-release/prd; the build will" \+ "rely on Xcode cloud signing via the API key."+ exit 0+ fi+ certificate_path="$RUNNER_TEMP/apple-distribution.p12"+ printf '%s' "$certificate" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$certificate" | base64 -D > "$certificate_path"+ password=$(jq -r '.APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD // empty' "$secrets")+ [ -z "$password" ] || echo "::add-mask::$password"+ {+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PATH=$certificate_path"+ echo "APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD=$password"+ } >> "$GITHUB_ENV"+ echo "Wrote Apple Distribution certificate to $certificate_path"+fidiff --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.shnew file mode 100644index 0000000000..65c961bb20--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_live.sh@@ -0,0 +1,26 @@+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_tree_fetch "$merge"+native_tree=$(native_tree_hash "$merge")+echo "Merge result ${merge:0:10}: native tree ${native_tree}"+bun scripts/ios-app-store.mjs status --require-live --native-tree "$native_tree"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/ios_native_check_rerun.shnew file mode 100644index 0000000000..016435bad3--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_check_rerun.sh@@ -0,0 +1,45 @@+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+# 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')+if [[ "$current" != "$HEAD_SHA" ]]; then+ echo "PR head moved from ${HEAD_SHA:0:10} to ${current:0:10}; its run reads the labels itself. Nothing to re-run."+ exit 0+fi+deadline=$(( $(date +%s) + 25 * 60 ))+while true; do+ run=$(gh run list --repo "$GH_REPO" --workflow web-app-check-main.yml --commit "$HEAD_SHA" \+ --json databaseId,status,conclusion --limit 1 --jq '.[0] // empty')+ if [[ -z "$run" ]]; then+ echo "No Web App Pr Checks run for ${HEAD_SHA:0:10} yet; nothing to re-run (the next push runs the gate with the current labels)."+ exit 0+ fi+ run_id=$(jq -r '.databaseId' <<<"$run")+ status=$(jq -r '.status' <<<"$run")+ if [[ "$status" == "completed" ]]; then+ if [[ "$(jq -r '.conclusion' <<<"$run")" == "cancelled" ]]; then+ echo "Run ${run_id} was cancelled (superseded); nothing to re-run."+ exit 0+ fi+ 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+ 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')+if [[ -z "$job_id" ]]; then+ echo "Run ${run_id} has no iOS Native Check 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."+gh run rerun --repo "$GH_REPO" --job "$job_id"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_tree.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_tree.shnew file mode 100644index 0000000000..22e5ec5866--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_native_tree.sh@@ -0,0 +1,38 @@+# --- native tree ------------------------------------------------------------+# Hash identifying "the iOS native code" at a commit: every tracked blob under+# apps/web/tauri except the paths that never reach the iOS binary. Android-only+# code is recognised by Tauri's naming convention — a path component that is+# `android`, starts with `android_` / `android.`, or contains `.android.`+# (the android_* plugins, every android/ directory, android.rs / android.json,+# android_tls.rs, tauri.android.conf.json; the Rust ones are all behind+# cfg(target_os = "android")) — plus the desktop updater manifest and editor+# config. The release stamps uploaded builds+# with it, the merge gate compares the live build's stamp against the merge+# result's, and the drift / head guards compare commits with it. Must match+# nativeTreeHash() in apps/web/scripts/ios-app-store.mjs and the iOS Native+# Check path filter (web_app_check_main/ios_native_check.rs).+NATIVE_TREE_PATH=apps/web/tauri+export NATIVE_TREE_EXCLUDE='(^|/)android([_./]|$)|\.android\.|^desktop-release\.json$|^\.helix/'++# native_tree_hash <commit>: prints the hash, fails if the path is missing.+# (--full-tree: ls-tree otherwise narrows its output to the current directory,+# which would silently hash nothing when run from apps/web.)+native_tree_hash() {+ git rev-parse -q --verify "$1:${NATIVE_TREE_PATH}" >/dev/null || return 1+ git ls-tree -r --full-tree "$1:${NATIVE_TREE_PATH}" \+ | awk -F'\t' '$2 !~ ENVIRON["NATIVE_TREE_EXCLUDE"]' \+ | git hash-object --stdin+}++# native_tree_fetch <sha>: make a commit that is not in this checkout (a new+# PR head, GitHub's test merge commit, the pre-push head) available to+# native_tree_hash. Checkouts here don't persist credentials, so authenticate+# the way actions/checkout does. Fails if the commit is unreachable (a+# force-pushed-away head).+native_tree_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/ios_release_drift.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_drift.shnew file mode 100644index 0000000000..6b5807fda9--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_drift.sh@@ -0,0 +1,19 @@+set -euo pipefail+# A push landed on a PR that carries ios-update. Compare the native tree+# 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 build still matches.+if native_tree_fetch "$BEFORE_SHA" && before_tree=$(native_tree_hash "$BEFORE_SHA"); then :; else+ before_tree=unknown+fi+native_tree_fetch "$AFTER_SHA"+after_tree=$(native_tree_hash "$AFTER_SHA")+echo "native tree before: ${before_tree}"+echo "native tree after: ${after_tree}"+if [[ "$before_tree" == "$after_tree" ]]; then+ echo "changed=false" >> "$GITHUB_OUTPUT"+ echo "No native changes in this push; the release stays valid."+else+ echo "changed=true" >> "$GITHUB_OUTPUT"+ echo "Native code changed; the released build is stale."+fidiff --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.shnew file mode 100644index 0000000000..a8eb45bc60--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_head_guard.sh@@ -0,0 +1,24 @@+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).+built_tree=$(native_tree_hash HEAD)+built=$(jq -r '.bundle.iOS.bundleVersion' apps/web/tauri/src-tauri/tauri.ios.conf.json)+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+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+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 1diff --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.shnew file mode 100644index 0000000000..ed1a1ddf24--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_preconditions.sh@@ -0,0 +1,50 @@+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+# every other check on the head commit passing. Pending checks are waited on+# (the label often lands right after a push); anything failing stops the+# release before the long build. 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)+if [[ "$(jq -r '.isDraft' <<<"$pr_json")" == "true" ]]; then+ echo "PR #${PR_NUMBER} is a draft; mark it ready for review before adding ios-update." >&2+ exit 1+fi+head_sha=$(jq -r '.headRefOid' <<<"$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.+ native_tree_fetch "$head_sha"+ if [[ "$(native_tree_hash "$head_sha")" != "$(native_tree_hash HEAD)" ]]; then+ echo "PR #${PR_NUMBER} got native changes since this run started (${HEAD_SHA:0:10} → ${head_sha:0:10});" \+ "re-add ios-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 native code is unchanged; continuing."+fi++# 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)'+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 ios-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 ios-update once they pass." >&2+ exit 1+ fi+ echo "Waiting for: ${pending}"+ sleep 60+donediff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_signing.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_signing.shnew file mode 100644index 0000000000..b6321ba21b--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_signing.sh@@ -0,0 +1,33 @@+set -euo pipefail+# The credentials step decodes the optional .p12 from Doppler and exports its+# path; without one, xcodebuild uses cloud signing through the API key+# (-allowProvisioningUpdates).+certificate_path="${APPLE_DISTRIBUTION_CERTIFICATE_PATH:-}"+if [ -z "$certificate_path" ]; then+ echo "No Apple Distribution certificate; relying on Xcode cloud signing" \+ "via the App Store Connect API key."+ exit 0+fi++# Mirror configure_signing_identity.sh (DMG builds): the System keychain keeps+# the identity visible to xcodebuild without per-user keychain unlocking.+sudo security import "$certificate_path" \+ -k /Library/Keychains/System.keychain \+ -P "${APPLE_DISTRIBUTION_CERTIFICATE_PASSWORD:-}" \+ -A \+ -T /usr/bin/codesign \+ -T /usr/bin/security+sudo security set-key-partition-list \+ -S apple-tool:,apple:,codesign: \+ -s \+ -k "" \+ /Library/Keychains/System.keychain || true++identity=$(security find-identity -v -p codesigning /Library/Keychains/System.keychain \+ | awk -F '"' '/Apple Distribution/ { print $2; exit }')+if [ -z "$identity" ]; then+ echo "No Apple Distribution identity found in System.keychain after import" >&2+ security find-identity -v -p codesigning /Library/Keychains/System.keychain >&2 || true+ exit 1+fi+echo "Using signing identity: $identity"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_watch.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_watch.shnew file mode 100644index 0000000000..5fee3c4e83--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/ios_release_watch.sh@@ -0,0 +1,127 @@+set -euo pipefail+# For each open PR labeled `ios-update` (PRS: [{number, sha, merge}]):+#+# 1. Drift: if the PR's in-flight App Store submission was built from native+# code the PR head no longer has, withdraw it, drop the label and comment —+# what the `iOS Release Drift` workflow does on push, except GitHub does+# not run pull_request workflows on a PR that conflicts with main, so a+# native push to such a PR only gets caught here.+# 2. Ask App Store Connect whether the iOS version + build committed at the+# PR head is live, built from the native tree the PR's merge result would+# have (`merge` is GitHub's test merge commit; the gate hashes the same).+# When it is, and the PR's latest `iOS 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.+cd apps/web+conf_path="apps/web/tauri/src-tauri/tauri.ios.conf.json"+bump='cd apps/web && doppler run --project ios-release --config prd -- just ios-bump'++check_pr() {+ local pr=$1 number sha merge conf version build head_tree native_tree run run_id status run_url job conclusion job_id reruns outputs withdrawn live+ number=$(jq -r '.number' <<<"$pr")+ sha=$(jq -r '.sha' <<<"$pr")+ merge=$(jq -r '.merge // empty' <<<"$pr")+ conf=$(gh api "repos/${GH_REPO}/contents/${conf_path}?ref=${sha}" --jq '.content' | base64 --decode)+ version=$(jq -r '.version' <<<"$conf")+ build=$(jq -r '.bundle.iOS.bundleVersion' <<<"$conf")++ # 1. Drift check against the head's native code.+ native_tree_fetch "$sha"+ head_tree=$(native_tree_hash "$sha")+ outputs="$RUNNER_TEMP/withdraw-${number}.out"+ : >"$outputs"+ GITHUB_OUTPUT="$outputs" bun scripts/ios-app-store.mjs withdraw --pr "$number" --unless-tree "$head_tree" \+ >"$RUNNER_TEMP/withdraw-${number}.log" 2>&1 || true+ sed 's/^/ /' "$RUNNER_TEMP/withdraw-${number}.log"+ withdrawn=$(sed -n 's/^withdrawn=//p' "$outputs")+ live=$(sed -n 's/^live=//p' "$outputs")+ if [[ "$withdrawn" == "true" || -n "$live" ]]; then+ gh pr edit "$number" --remove-label ios-update+ if [[ -n "$live" ]]; then+ gh pr comment "$number" --body "🚨 Native changes were pushed to this PR after Apple had already approved iOS ${live}, so that build is (or is about to be) live with native code this PR no longer matches. Bump (\`${bump}\`), commit, re-add the \`ios-update\` label, and ship the follow-up as soon as possible. The label was removed."+ else+ gh pr comment "$number" --body "📱 Native code changed after this PR's App Store release started (the push-time drift check could not run — does the PR conflict with \`main\`?), so the pending App Review submission was withdrawn and the \`ios-update\` label removed. When the PR is ready again, bump (\`${bump}\`; the marketing version stays, the build number moves), commit, push, and re-add \`ios-update\`."+ fi+ echo "PR #${number}: stale submission handled; label removed"+ return 0+ fi++ # 2. Live check against the merge result.+ if [[ -z "$merge" ]]; then+ echo "PR #${number}: no merge commit (conflicts with main?); cannot check the merge result"+ return 0+ fi+ native_tree_fetch "$merge"+ native_tree=$(native_tree_hash "$merge")+ echo "PR #${number}: iOS ${version} (build ${build}) at ${sha:0:10}, merge-result native tree ${native_tree:0:10}"++ if ! bun scripts/ios-app-store.mjs status --require-live \+ --version "$version" --build "$build" --native-tree "$native_tree" \+ >"$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 the App Store"++ 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 == "iOS Native Check") | {id: .databaseId, conclusion}')+ if [[ -z "$job" ]]; then+ echo " run ${run_id} has no iOS Native Check job; skipping"+ return 0+ fi+ job_id=$(jq -r '.id' <<<"$job")+ conclusion=$(jq -r '.conclusion' <<<"$job")+ if [[ "$conclusion" == "success" ]]; then+ echo " iOS Native Check already passed"+ return 0+ fi+ if [[ "$conclusion" != "failure" ]]; then+ echo " iOS 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.+ # Counted by our own comments: the run's attempt number is shared with+ # label re-runs and "re-run failed jobs" clicks for flaky tests.+ reruns=$(gh pr view "$number" --json comments --jq \+ "[.comments[].body | select(contains(\"Re-ran the **iOS Native Check**\")) | select(contains(\"iOS ${version} (build ${build})\"))] | length")+ if (( reruns >= 2 )); then+ echo " iOS Native Check already re-run ${reruns} times and still failing; not re-running again — see ${run_url}"+ return 0+ fi+ echo " re-running iOS 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 "📱 iOS ${version} (build ${build}) is live on the App Store. Re-ran the **iOS 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 $faileddiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rsindex a9ae08c271..c25cbe75a6 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs@@ -19,6 +19,7 @@ secret!(DAYTONA_API_KEY);secret!(DD_API_KEY);secret!(DD_APP_KEY);secret!(DOPPLER_TOKEN);+secret!(IOS_RELEASE_DOPPLER_TOKEN);secret!(MACOS_DEVELOPER_ID_CERTIFICATE_BASE64);secret!(MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD);secret!(MACOS_RELEASE_DOPPLER_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.rsindex 0e8e4ed00a..c036b6782c 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@@ -11,6 +11,7 @@ use crate::workflows::{vars,};+mod ios_native_check;#[cfg(test)]mod test;@@ -53,6 +54,7 @@ pub fn web_app_check_main() -> Workflow {.add_job("test", test()).add_job("cycles", cycles()).add_job("build", build())+ .add_job(ios_native_check::JOB_ID, ios_native_check::job()).add_job("status-check", status_check())}@@ -195,7 +197,9 @@ fn build() -> Job {}/// Always-run collector used as the required status check. Its name must stay-/// stable because branch protection can reference it.+/// stable because branch protection can reference it. New gates join the+/// `needs` list (and [`check_job_results`]) rather than the ruleset: the+/// [`ios_native_check`] job is required this way.fn status_check() -> Job {Job::default().name("Web App Status Check")@@ -208,6 +212,7 @@ fn status_check() -> Job {"test".to_string(),"cycles".to_string(),"build".to_string(),+ ios_native_check::JOB_ID.to_string(),]).runs_on(runners::Runner::TinyNoCache.to_string()).add_step(check_job_results())@@ -439,15 +444,19 @@ fn check_job_results() -> Step<Run> {echo "test: ${{ needs.test.result }}"echo "cycles: ${{ needs.cycles.result }}"echo "build: ${{ needs.build.result }}"+ echo "ios-native-check: ${{ needs.ios-native-check.result }}"- # Fail if any job failed (skipped and success are both OK)+ # 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.path-check.result }}" == "failure" ]] || \[[ "${{ needs.typescript.result }}" == "failure" ]] || \[[ "${{ needs.generated-code.result }}" == "failure" ]] || \[[ "${{ needs.biome-check.result }}" == "failure" ]] || \[[ "${{ needs.test.result }}" == "failure" ]] || \[[ "${{ needs.cycles.result }}" == "failure" ]] || \- [[ "${{ needs.build.result }}" == "failure" ]]; then+ [[ "${{ needs.build.result }}" == "failure" ]] || \+ [[ "${{ needs.ios-native-check.result }}" == "failure" ]] || \+ [[ "${{ needs.ios-native-check.result }}" == "cancelled" ]]; thenecho "One or more jobs failed"exit 1fidiff --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.rsnew file mode 100644index 0000000000..c349228c1a--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/ios_native_check.rs@@ -0,0 +1,192 @@+//! `iOS Native Check` — merge gate for PRs that change native iOS (Tauri)+//! code, as a job of the web app PR checks so that `Web App Status Check`+//! (the required status check) covers it without a ruleset change. Web+//! bundles ship over the air, but native changes only reach users through+//! the App Store, so a PR whose bundle depends on new native code must not+//! merge before that native build is actually downloadable. The gate:+//!+//! 1. Detects native changes with a path filter over `apps/web/tauri/**`,+//! minus what never reaches the iOS binary (anything Android-only by+//! name, the desktop updater manifest, editor config) — the same+//! exclusions as the native tree hash in `scripts/ios_native_tree.sh`.+//! The filter needs dorny's `every` quantifier: with the default `some`+//! a negated pattern matches every file outside it, i.e. everything.+//! 2. Verifies the PR bumped the iOS release numbers (`just ios-bump`):+//! marketing version, build number, and `min-native-build.json`.+//! 3. Asks the App Store Connect API whether exactly that version + build is+//! live on the App Store, built from the native tree this PR's current+//! merge result has (fetched through the API, so native code that landed+//! on main after the release also fails it, even on a re-run: the+//! shipped build lacks it), and fails with instructions otherwise — add the+//! `ios-update` label to run the `iOS App Store Release` workflow and+//! wait for Apple's approval; `iOS Release Watch` re-runs this job once+//! the release is live.+//!+//! The App Store Connect key comes from Doppler (`ios-release/prd` via the+//! `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+//! 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+//! stale by then. The job name must stay stable: the release workflow, the+//! watcher and that label workflow find the job by it.++use gh_workflow::{Expression, Job, Level, Permissions, Run, Step, Use};++use crate::workflows::{runners, vars};++/// The job's id in the web app check workflow.+pub(super) const JOB_ID: &str = "ios-native-check";+/// The job's display name (a check run name).+pub(super) const JOB_NAME: &str = "iOS Native Check";++/// The path filter matched native iOS code.+const NATIVE_CHANGED: &str = "steps.native-filter.outputs.ios_native == 'true'";+/// The PR opted out of the gate via the `skip-ios-update` label (as read at+/// run time, see [`read_labels`]), and its negation. Spelled out rather than+/// `!SKIP_LABEL`: in GitHub expressions `!` binds tighter than `==`, so+/// `!a == 'true'` is `(!a) == 'true'`, false whatever `a` is.+const SKIP_LABEL: &str = "steps.labels.outputs.skip == 'true'";+const NOT_SKIPPED: &str = "steps.labels.outputs.skip != 'true'";++pub(super) fn job() -> Job {+ Job::default()+ .name(JOB_NAME)+ .runs_on(runners::Runner::TinyNoCache.to_string())+ // Reads only: the PR's labels and merge commit, and a base-branch fetch.+ .permissions(+ Permissions::default()+ .contents(Level::Read)+ .pull_requests(Level::Read),+ )+ // Shallow: the path filter uses the API, and the bump check fetches+ // the base branch itself, only when it runs.+ .add_step(super::checkout("Checkout Repo", false))+ .add_step(paths_filter())+ .add_step(read_labels())+ .add_step(setup_bun())+ .add_step(verify_bump())+ .add_step(fetch_credentials())+ .add_step(require_live_version())+ .add_step(skip_notice())+}++fn gated() -> Expression {+ Expression::new(format!("{NATIVE_CHANGED} && {NOT_SKIPPED}"))+}++fn paths_filter() -> Step<Use> {+ Step::new("Detect native iOS changes")+ .uses(+ "dorny",+ "paths-filter",+ "d1c1ffe0248fe513906c8e24db8ea791d46f8590",+ ) // v3.0.3+ .id("native-filter")+ .add_with(("predicate-quantifier", "every"))+ .add_with((+ "filters",+ indoc::indoc! {"+ ios_native:+ - 'apps/web/tauri/**'+ - '!apps/web/tauri/**/android/**'+ - '!apps/web/tauri/**/android_*'+ - '!apps/web/tauri/**/android_*/**'+ - '!apps/web/tauri/**/android.*'+ - '!apps/web/tauri/**/*.android.*'+ - '!apps/web/tauri/desktop-release.json'+ - '!apps/web/tauri/.helix/**'+ "},+ ))+}++/// The PR's labels as they are now. `github.event.pull_request.labels` is+/// frozen at the event that started the run, so after the label workflow+/// re-runs this job it would still describe the old label set.+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-ios-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 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 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+ "#})+ .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 }}"))+}++/// Exports `APPLE_API_KEY` / `APPLE_API_ISSUER` via `GITHUB_ENV` and writes+/// the `.p8` where `ios-app-store.mjs` looks for it by default.+fn fetch_credentials() -> Step<Run> {+ Step::new("Fetch App Store Connect credentials from Doppler")+ .run(include_str!(+ "../scripts/ios_app_store_connect_credentials.sh"+ ))+ .shell("bash")+ .if_condition(gated())+ .add_env(("DOPPLER_TOKEN", vars::IOS_RELEASE_DOPPLER_TOKEN))+}++/// Compares the live build's stamp against the native tree of the PR's+/// *current* merge result — exactly what the floor derived from this build+/// claims ships. Asked through the API rather than taken from the checkout:+/// a re-run (the watcher's, the label workflow's, a human's) checks out the+/// merge commit as of the run's original event, which may predate native+/// code landing on main.+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/ios_native_check_live.sh")+ ))+ .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 }}"))+}++fn skip_notice() -> Step<Run> {+ Step::new("Skipped via label")+ .run(+ "echo \"Native iOS changes detected, but the skip-ios-update label says they \+ don't break the native/web contract — skipping the App Store 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/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rsindex 4b16e69dff..b4843bff8b 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@@ -34,6 +34,44 @@ fn nix_dev_shell_does_not_start_typecheck() {);}+/// The iOS merge gate is required through the aggregator, not the ruleset:+/// the status check must depend on it and fail when it fails.+#[test]+fn status_check_requires_the_ios_native_check() {+ let yaml = web_app_check_main().to_string().expect("workflow yaml");+ let gate = job(&yaml, "ios-native-check", "status-check");+ assert!(+ gate.contains("name: iOS Native Check"),+ "gate job name is a check name: {gate}"+ );+ assert!(+ gate.contains("predicate-quantifier: every"),+ "negated path filters need the `every` quantifier: {gate}"+ );+ // `!` binds tighter than `==` in GitHub expressions: `!x == 'true'` is+ // always false, which silently skipped every gated step.+ assert!(+ !gate.contains("!steps.labels"),+ "never negate a comparison with a leading `!`: {gate}"+ );+ assert!(+ gate.contains("steps.labels.outputs.skip != 'true'"),+ "gated steps run when the skip label is absent: {gate}"+ );+ let status = yaml+ .split("\n status-check:\n")+ .nth(1)+ .expect("status-check job");+ assert!(+ status.contains("- ios-native-check"),+ "status-check must need the gate: {status}"+ );+ assert!(+ status.contains("needs.ios-native-check.result }}\" == \"failure\""),+ "status-check must fail when the gate fails: {status}"+ );+}+#[test]fn typecheck_runs_lexical_service_check_and_tests() {let yaml = web_app_check_main().to_string().expect("workflow yaml");