Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(android): predownload updates and enforce Play signing

tianma-iff523d836986c
diff --git a/.github/workflows/android-play-signature-audit.yml b/.github/workflows/android-play-signature-audit.yml
new file mode 100644
index 00000000..7a5c8618
--- /dev/null
+++ b/.github/workflows/android-play-signature-audit.yml
@@ -0,0 +1,58 @@
+name: Audit Android Play Signature
+
+on:
+ workflow_dispatch:
+ inputs:
+ release_tag:
+ description: "Draft Release tag whose Android APK must use the Play app-signing certificate"
+ required: true
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ audit:
+ if: github.repository == 'tianma-if/edgeever'
+ name: Require Play-signed Draft APK
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out the immutable Release tag
+ uses: actions/checkout@v5
+ with:
+ ref: ${{ inputs.release_tag }}
+ fetch-depth: 0
+
+ - name: Validate matching Draft Release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ run: |
+ release="$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}")"
+ test "$(jq -r '.draft' <<<"$release")" = "true"
+ test "$(jq -r '.prerelease' <<<"$release")" = "false"
+ test "$(jq -r '.tag_name' <<<"$release")" = "$RELEASE_TAG"
+ release_target="$(jq -r '.target_commitish' <<<"$release")"
+ test "$(git rev-parse "${RELEASE_TAG}^{commit}")" = "$(git rev-parse "${release_target}^{commit}")"
+
+ - name: Download the Draft Android APK
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ run: |
+ mkdir -p "$RUNNER_TEMP/android-release"
+ gh release download "$RELEASE_TAG" \
+ --repo "$GITHUB_REPOSITORY" \
+ --pattern 'edgeever-android-v*-arm64-v8a.apk' \
+ --dir "$RUNNER_TEMP/android-release"
+ test "$(find "$RUNNER_TEMP/android-release" -type f -name 'edgeever-android-v*-arm64-v8a.apk' | wc -l | tr -d ' ')" = "1"
+ apk_path="$(find "$RUNNER_TEMP/android-release" -type f -name 'edgeever-android-v*-arm64-v8a.apk' -print -quit)"
+ echo "apk_path=$apk_path" >> "$GITHUB_ENV"
+
+ - name: Require the Play app-signing certificate
+ env:
+ ANDROID_PLAY_APP_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ run: |
+ test -n "$ANDROID_PLAY_APP_SIGNER_SHA256"
+ node scripts/verify-android-apk-signature.mjs "$apk_path"
diff --git a/.github/workflows/mobile-build.yml b/.github/workflows/mobile-build.yml
index bd7f2de3..da78e59b 100644
--- a/.github/workflows/mobile-build.yml
+++ b/.github/workflows/mobile-build.yml
@@ -135,7 +135,8 @@ jobs:
- name: Verify existing APK uses the pinned signer
if: steps.plan.outputs.asset_ready == 'true'
env:
- EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: 22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ ANDROID_PLAY_APP_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: ${{ github.event_name == 'release' && secrets.ANDROID_PLAY_APP_SIGNER_SHA256 || format('22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,{0}', secrets.ANDROID_PLAY_APP_SIGNER_SHA256) }}
CURRENT_TAG: ${{ inputs.release_tag || github.event.release.tag_name }}
GH_TOKEN: ${{ github.token }}
run: |
@@ -146,8 +147,27 @@ jobs:
--dir "$RUNNER_TEMP/native-assets"
apk_path="$(find "$RUNNER_TEMP/native-assets" -type f -name 'edgeever-android-v*-arm64-v8a.apk' -print -quit)"
test -n "$apk_path"
+ test -n "$ANDROID_PLAY_APP_SIGNER_SHA256"
node scripts/verify-android-apk-signature.mjs "$apk_path"
+ restore-invalid-published-release:
+ needs: release-plan
+ if: >-
+ ${{
+ always() &&
+ github.repository == 'tianma-if/edgeever' &&
+ github.event_name == 'release' &&
+ needs.release-plan.result == 'failure'
+ }}
+ name: Restore invalid Android Release to Draft
+ runs-on: ubuntu-latest
+ steps:
+ - name: Restore Draft state
+ env:
+ CURRENT_TAG: ${{ github.event.release.tag_name }}
+ GH_TOKEN: ${{ github.token }}
+ run: gh release edit "$CURRENT_TAG" --repo "$GITHUB_REPOSITORY" --draft=true
+
reuse-release-apk:
needs: release-plan
if: >-
@@ -167,7 +187,8 @@ jobs:
- name: Copy latest compatible APK without renaming
env:
CURRENT_TAG: ${{ inputs.release_tag || github.event.release.tag_name }}
- EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: 22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ ANDROID_PLAY_APP_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
GH_TOKEN: ${{ github.token }}
PREVIOUS_TAG: ${{ needs.release-plan.outputs.previous_tag }}
run: |
@@ -178,6 +199,7 @@ jobs:
--dir "$RUNNER_TEMP/native-assets"
test "$(find "$RUNNER_TEMP/native-assets" -type f -name 'edgeever-android-v*-arm64-v8a.apk' | wc -l | tr -d ' ')" = "1"
apk_path="$(find "$RUNNER_TEMP/native-assets" -type f -name 'edgeever-android-v*-arm64-v8a.apk' -print -quit)"
+ test -n "$ANDROID_PLAY_APP_SIGNER_SHA256"
node scripts/verify-android-apk-signature.mjs "$apk_path"
gh release upload "$CURRENT_TAG" "$RUNNER_TEMP/native-assets/"* \
--repo "$GITHUB_REPOSITORY" \
diff --git a/.github/workflows/store-delivery.yml b/.github/workflows/store-delivery.yml
index b31e02c3..2b19bd39 100644
--- a/.github/workflows/store-delivery.yml
+++ b/.github/workflows/store-delivery.yml
@@ -49,7 +49,7 @@ jobs:
ref: ${{ inputs.release_tag }}
fetch-depth: 0
- - name: Validate formal Release and resolve its predecessor
+ - name: Validate Release and resolve its formal predecessor
id: release
env:
GH_TOKEN: ${{ github.token }}
@@ -58,7 +58,8 @@ jobs:
release="$(
gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}"
)"
- test "$(jq -r '.draft' <<<"$release")" = "false"
+ release_is_draft="$(jq -r '.draft' <<<"$release")"
+ test "$release_is_draft" = "true" -o "$release_is_draft" = "false"
test "$(jq -r '.prerelease' <<<"$release")" = "false"
test "$(jq -r '.tag_name' <<<"$release")" = "$RELEASE_TAG"
@@ -70,17 +71,21 @@ jobs:
--jq '.[] | select(.draft == false and .prerelease == false) | .tag_name'
)
previous_tag=""
- current_found="false"
- for candidate in "${release_tags[@]}"; do
- if [[ "$current_found" = "true" ]]; then
- previous_tag="$candidate"
- break
- fi
- if [[ "$candidate" = "$RELEASE_TAG" ]]; then
- current_found="true"
- fi
- done
- test "$current_found" = "true"
+ if [[ "$release_is_draft" = "true" ]]; then
+ previous_tag="${release_tags[0]:-}"
+ else
+ current_found="false"
+ for candidate in "${release_tags[@]}"; do
+ if [[ "$current_found" = "true" ]]; then
+ previous_tag="$candidate"
+ break
+ fi
+ if [[ "$candidate" = "$RELEASE_TAG" ]]; then
+ current_found="true"
+ fi
+ done
+ test "$current_found" = "true"
+ fi
test -n "$previous_tag"
git fetch origin "refs/tags/${previous_tag}:refs/tags/${previous_tag}"
echo "previous_tag=$previous_tag" >> "$GITHUB_OUTPUT"
diff --git a/AGENTS.md b/AGENTS.md
index a7d129d4..cdcd200e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,11 +13,11 @@
1. **Fork 工作流边界**:配置 GitHub Actions 时必须考虑大量用户会 Fork 仓库进行自部署;仅官方仓库需要的 Job 必须使用 `github.repository == 'tianma-if/edgeever'` 门禁,严禁在下游 Fork 中分配 Runner 或执行。
2. **版本号与基线**:`vX.Y.Z`(非 Draft/Prerelease)。发布须显式 `--bump patch|minor|major`(脚本不自动选级);按 SemVer 选择,**禁止因发版节奏把用户可感知的新能力或新平台压成 patch**。递增根目录 `package.json`;含移动端修改时同步 `apps/mobile/app.json` 的 `expo.version` 并递增 `android.versionCode`。上一个正式 Release 为审计基线。
-3. **跨平台 Release 资产**:每个正式 Release 页面必须同时包含 macOS arm64 DMG、macOS x64 DMG 和 Android arm64 APK。若本次未修改对应原生运行时代码、依赖、配置或构建工具,直接复用上一个正式 Release 中已验证的原始资产,保留原文件名与校验和,禁止仅为匹配新版本号而重命名。
+3. **跨平台 Release 资产**:每个正式 Release 页面必须同时包含 macOS arm64 DMG、macOS x64 DMG 和 Android arm64 APK。若本次未修改对应原生运行时代码、依赖、配置或构建工具,直接复用上一个正式 Release 中已验证的原始资产,保留原文件名与校验和,禁止仅为匹配新版本号而重命名。官方仓库正式 Release 中的 Android APK 必须使用固定的 Google Play 应用签名证书;本地上传证书签名的 APK 只能作为 Draft 临时资产,未经 Play 签名替换和发布前门禁核验不得公开。
4. **验证命令**:必须通过 `bun run typecheck`、`bun run typecheck:mobile` 和 `bun run build:web`。
5. **测试职责边界**:正式 Release 必须先在官方仓库及与下游一致的 Ubuntu 环境通过完整非 E2E 测试,严禁将上游自身的测试失败转嫁给下游 Fork 发现。只读部署 Fork 仅同步产品快照且不运行测试;只有显式保留定制改动的 Fork 才验证合并结果,失败时必须保持 `main` 与生产环境不变。
6. **原生资产构建与复用**:由 `scripts/plan-native-release.mjs` 决定重建或复用;桌面资产包含 `apps/web`。修改判定规则时同步更新测试。移动端重建使用 `bun run build:android:apk:local`,签名配置保存在仓库外。
-7. **Draft 内准备资产**:通过带 `release_tag` 的 `workflow_dispatch` 在 Draft 中准备并验证资产;`published` 事件只审计,禁止重新构建或上传。
+7. **Draft 内准备资产**:通过带 `release_tag` 的 `workflow_dispatch` 在 Draft 中准备并验证资产;Android 重建时须在 Draft 阶段完成 Google Play 交付、用 Play 签名 APK 替换临时资产并通过独立签名门禁;`published` 事件只审计,禁止重新构建或上传,签名不符时恢复 Draft。
8. **桌面验证职责**:桌面 Release 工作流负责测试、包结构检查、签名与公证;代理不再重复下载 Draft 或执行本地首次启动验收,除非用户明确要求。
9. **发布后更新**:正式发布后,发布流程默认不得下载、覆盖安装或启动 `/Applications/EdgeEver.app`;已安装的桌面端通过应用内自动更新机制获取新版。仅在用户明确要求时使用 `--install-desktop` 执行原有安装验收,功能体验由用户在实际使用中验证。
10. **失败处理**:工作流或资产审计失败时保持或恢复 Draft,修复后重跑;不得公开已知损坏的 Release。
diff --git a/apps/mobile/.gitignore b/apps/mobile/.gitignore
index 67b75bf9..1bdf3c9d 100644
--- a/apps/mobile/.gitignore
+++ b/apps/mobile/.gitignore
@@ -12,3 +12,5 @@ ios/
# Keep local Expo module sources while excluding their generated artifacts.
!modules/edgeever-keyboard/android/
modules/edgeever-keyboard/android/build/
+!modules/edgeever-app-installer/android/
+modules/edgeever-app-installer/android/build/
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 681e827a..8902d986 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -14,7 +14,6 @@ import { SessionProvider } from "../src/lib/session";
import { MobileThemeProvider, useMobileTheme } from "../src/lib/mobile-theme";
import { MobileLocaleProvider } from "../src/lib/mobile-locale";
import { AppDialogProvider } from "../src/components/AppDialogProvider";
-import { MobileUpdateToast } from "../src/components/MobileUpdateToast";
import { MobileUpdateProvider } from "../src/lib/mobile-update";
void SplashScreen.preventAutoHideAsync();
@@ -94,7 +93,6 @@ export default function RootLayout() {
>
<SessionProvider>
<Stack screenOptions={{ headerShown: false }} />
- <MobileUpdateToast />
</SessionProvider>
</PersistQueryClientProvider>
</MobileUpdateProvider>
diff --git a/apps/mobile/modules/edgeever-app-installer/android/build.gradle b/apps/mobile/modules/edgeever-app-installer/android/build.gradle
new file mode 100644
index 00000000..da4b0db6
--- /dev/null
+++ b/apps/mobile/modules/edgeever-app-installer/android/build.gradle
@@ -0,0 +1,15 @@
+plugins {
+ id 'com.android.library'
+ id 'expo-module-gradle-plugin'
+}
+
+group = 'org.edgeever.installer'
+version = '1.0.0'
+
+android {
+ namespace "org.edgeever.installer"
+ defaultConfig {
+ versionCode 1
+ versionName '1.0.0'
+ }
+}
diff --git a/apps/mobile/modules/edgeever-app-installer/android/src/main/java/org/edgeever/installer/EdgeEverAppInstallerModule.kt b/apps/mobile/modules/edgeever-app-installer/android/src/main/java/org/edgeever/installer/EdgeEverAppInstallerModule.kt
new file mode 100644
index 00000000..b0b749c5
--- /dev/null
+++ b/apps/mobile/modules/edgeever-app-installer/android/src/main/java/org/edgeever/installer/EdgeEverAppInstallerModule.kt
@@ -0,0 +1,110 @@
+package org.edgeever.installer
+
+import android.content.ClipData
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import androidx.core.content.FileProvider
+import expo.modules.kotlin.Promise
+import expo.modules.kotlin.exception.Exceptions
+import expo.modules.kotlin.exception.toCodedException
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+import java.io.File
+
+private const val APK_MIME_TYPE = "application/vnd.android.package-archive"
+private const val INSTALL_PERMISSION_REQUEST_CODE = 2401
+
+class EdgeEverAppInstallerModule : Module() {
+ private val context: Context
+ get() = appContext.reactContext ?: throw Exceptions.ReactContextLost()
+
+ private var pendingFile: File? = null
+ private var pendingPromise: Promise? = null
+
+ override fun definition() = ModuleDefinition {
+ Name("EdgeEverAppInstaller")
+
+ AsyncFunction("install") { fileUri: String, promise: Promise ->
+ if (pendingPromise != null) {
+ promise.reject("ERR_INSTALL_IN_PROGRESS", "Another APK install request is already in progress", null)
+ return@AsyncFunction
+ }
+
+ try {
+ val file = resolveDownloadedApk(fileUri)
+ if (canRequestPackageInstalls()) {
+ openPackageInstaller(file)
+ promise.resolve(true)
+ } else {
+ pendingFile = file
+ pendingPromise = promise
+ val permissionIntent = Intent(
+ Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
+ Uri.parse("package:${context.packageName}")
+ )
+ appContext.throwingActivity.startActivityForResult(permissionIntent, INSTALL_PERMISSION_REQUEST_CODE)
+ }
+ } catch (error: Throwable) {
+ pendingFile = null
+ pendingPromise = null
+ promise.reject(error.toCodedException())
+ }
+ }
+
+ OnActivityResult { _, payload ->
+ if (payload.requestCode != INSTALL_PERMISSION_REQUEST_CODE) {
+ return@OnActivityResult
+ }
+
+ val promise = pendingPromise ?: return@OnActivityResult
+ val file = pendingFile
+ pendingPromise = null
+ pendingFile = null
+
+ if (file == null || !canRequestPackageInstalls()) {
+ promise.resolve(false)
+ return@OnActivityResult
+ }
+
+ try {
+ openPackageInstaller(file)
+ promise.resolve(true)
+ } catch (error: Throwable) {
+ promise.reject(error.toCodedException())
+ }
+ }
+ }
+
+ private fun canRequestPackageInstalls(): Boolean {
+ return Build.VERSION.SDK_INT < Build.VERSION_CODES.O || context.packageManager.canRequestPackageInstalls()
+ }
+
+ private fun resolveDownloadedApk(fileUri: String): File {
+ val uri = Uri.parse(fileUri)
+ require(uri.scheme == "file") { "Expected a local APK file URI" }
+ val path = requireNotNull(uri.path) { "APK file URI has no path" }
+ val file = File(path).canonicalFile
+ val cacheDirectory = context.cacheDir.canonicalFile
+ require(file.path.startsWith(cacheDirectory.path + File.separator)) { "APK must be inside the app cache" }
+ require(file.isFile && file.extension.equals("apk", ignoreCase = true)) { "Downloaded APK does not exist" }
+ return file
+ }
+
+ private fun openPackageInstaller(file: File) {
+ val activity = appContext.throwingActivity
+ val contentUri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.FileSystemFileProvider",
+ file
+ )
+ val intent = Intent(Intent.ACTION_VIEW).apply {
+ setDataAndType(contentUri, APK_MIME_TYPE)
+ clipData = ClipData.newRawUri("EdgeEver update", contentUri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ activity.startActivity(intent)
+ }
+}
diff --git a/apps/mobile/modules/edgeever-app-installer/expo-module.config.json b/apps/mobile/modules/edgeever-app-installer/expo-module.config.json
new file mode 100644
index 00000000..a828c7bc
--- /dev/null
+++ b/apps/mobile/modules/edgeever-app-installer/expo-module.config.json
@@ -0,0 +1,6 @@
+{
+ "platforms": ["android"],
+ "android": {
+ "modules": ["org.edgeever.installer.EdgeEverAppInstallerModule"]
+ }
+}
diff --git a/apps/mobile/modules/edgeever-app-installer/index.ts b/apps/mobile/modules/edgeever-app-installer/index.ts
new file mode 100644
index 00000000..3bf9aabc
--- /dev/null
+++ b/apps/mobile/modules/edgeever-app-installer/index.ts
@@ -0,0 +1,13 @@
+import { requireNativeModule } from "expo";
+
+type EdgeEverAppInstallerNativeModule = {
+ install: (fileUri: string) => Promise<boolean>;
+};
+
+/**
+ * Opens Android's package installer, requesting per-app install permission first when required.
+ * Returns false only when the user comes back without granting that permission.
+ */
+export const installAndroidApk = (fileUri: string) => {
+ return requireNativeModule<EdgeEverAppInstallerNativeModule>("EdgeEverAppInstaller").install(fileUri);
+};
diff --git a/apps/mobile/modules/edgeever-app-installer/package.json b/apps/mobile/modules/edgeever-app-installer/package.json
new file mode 100644
index 00000000..53c21084
--- /dev/null
+++ b/apps/mobile/modules/edgeever-app-installer/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "edgeever-app-installer",
+ "version": "1.0.0",
+ "main": "index.ts",
+ "private": true
+}
diff --git a/apps/mobile/src/components/MobileUpdateCard.tsx b/apps/mobile/src/components/MobileUpdateCard.tsx
index 6d9203bf..93677c71 100644
--- a/apps/mobile/src/components/MobileUpdateCard.tsx
+++ b/apps/mobile/src/components/MobileUpdateCard.tsx
@@ -22,10 +22,12 @@ export const MobileUpdateCard = () => {
: status === "installing"
? (english ? "Opening installer…" : "正在打开安装器…")
: status === "ready"
- ? (english ? "Restart to apply" : "重启以应用")
+ ? updateKind === "install"
+ ? (english ? "Install now" : "立即安装")
+ : (english ? "Restart to apply" : "重启以应用")
: updateKind === "ota"
? (english ? "Download update" : "下载更新")
- : (english ? "Download & install" : "下载并安装");
+ : (english ? "Prepare update" : "准备更新");
return (
<View style={styles.card}>
diff --git a/apps/mobile/src/components/MobileUpdateToast.tsx b/apps/mobile/src/components/MobileUpdateToast.tsx
deleted file mode 100644
index 2e8d22b6..00000000
--- a/apps/mobile/src/components/MobileUpdateToast.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-import { useEffect, useRef, useState } from "react";
-import { Animated, Pressable, StyleSheet, View } from "react-native";
-import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { ArrowUpCircle, X } from "./icons";
-import { Text } from "./LocalizedText";
-import { useMobileLocale } from "../lib/mobile-locale";
-import {
- readMobileUpdateToastDismissedVersion,
- shouldShowMobileUpdateToastForVersion,
- writeMobileUpdateToastDismissedVersion,
-} from "../lib/preferences";
-import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";
-import { useMobileUpdate } from "../lib/mobile-update";
-import { getMobileUpdateToastBottomOffset } from "../lib/mobile-update-toast-layout";
-
-const AUTO_DISMISS_MS = 3_000;
-const FADE_MS = 180;
-
-/**
- * Subtle one-shot toast when an app update is detected.
- * Auto-hides after 3s, and is remembered per installed version until the user upgrades.
- */
-export const MobileUpdateToast = () => {
- const insets = useSafeAreaInsets();
- const { resolvedLocale } = useMobileLocale();
- const { resolvedTheme } = useMobileTheme();
- const { downloadProgress, hasUpdate, installedVersion, openUpdate, status, updateKind } = useMobileUpdate();
- const english = resolvedLocale === "en-US";
- const styles = resolveMobileThemeStyles(baseStyles, resolvedTheme);
- const [storageReady, setStorageReady] = useState(false);
- const [visible, setVisible] = useState(false);
- const dismissedForVersionRef = useRef<string | null>(null);
- const showingDownloadRef = useRef(false);
- const showingRef = useRef(false);
- const opacity = useRef(new Animated.Value(0)).current;
-
- useEffect(() => {
- let active = true;
- void readMobileUpdateToastDismissedVersion().then((value) => {
- if (!active) return;
- dismissedForVersionRef.current = value;
- setStorageReady(true);
- });
- return () => {
- active = false;
- };
- }, []);
-
- useEffect(() => {
- if (!storageReady || !hasUpdate) {
- return;
- }
- if (status === "downloading" || status === "installing") {
- showingDownloadRef.current = true;
- showingRef.current = true;
- setVisible(true);
- Animated.timing(opacity, {
- duration: FADE_MS,
- toValue: 1,
- useNativeDriver: true,
- }).start();
- return;
- }
- if (showingDownloadRef.current) {
- showingDownloadRef.current = false;
- Animated.timing(opacity, {
- duration: FADE_MS,
- toValue: 0,
- useNativeDriver: true,
- }).start(({ finished }) => {
- if (finished) {
- setVisible(false);
- showingRef.current = false;
- }
- });
- return;
- }
- if (!shouldShowMobileUpdateToastForVersion(installedVersion, dismissedForVersionRef.current)) {
- return;
- }
- if (!installedVersion || showingRef.current) {
- return;
- }
-
- showingRef.current = true;
- dismissedForVersionRef.current = installedVersion;
- void writeMobileUpdateToastDismissedVersion(installedVersion);
-
- setVisible(true);
- Animated.timing(opacity, {
- duration: FADE_MS,
- toValue: 1,
- useNativeDriver: true,
- }).start();
-
- const hideTimer = setTimeout(() => {
- Animated.timing(opacity, {
- duration: FADE_MS,
- toValue: 0,
- useNativeDriver: true,
- }).start(({ finished }) => {
- if (finished) {
- setVisible(false);
- showingRef.current = false;
- }
- });
- }, AUTO_DISMISS_MS);
-
- return () => clearTimeout(hideTimer);
- }, [hasUpdate, installedVersion, opacity, status, storageReady]);
-
- if (!visible || !hasUpdate) {
- return null;
- }
-
- const title = status === "downloading"
- ? (english ? "Downloading update" : "正在下载更新")
- : status === "installing"
- ? (english ? "Installer ready" : "安装包已就绪")
- : (english ? "Update available" : "发现新版本");
- const detail = status === "downloading"
- ? `${Math.round((downloadProgress ?? 0) * 100)}%`
- : status === "installing"
- ? (english ? "Opening the system installer" : "正在打开系统安装器")
- : status === "ready"
- ? (english ? "Restart in System info" : "可在系统信息中重启")
- : updateKind === "ota"
- ? (english ? "Optional in-app update" : "可选的应用内更新")
- : (english ? "See System info to update" : "可在系统信息中更新");
-
- const dismiss = () => {
- Animated.timing(opacity, {
- duration: FADE_MS,
- toValue: 0,
- useNativeDriver: true,
- }).start(({ finished }) => {
- if (finished) {
- setVisible(false);
- showingRef.current = false;
- }
- });
- };
-
- return (
- <Animated.View
- accessibilityLiveRegion="polite"
- pointerEvents="box-none"
- style={[
- styles.anchor,
- {
- bottom: getMobileUpdateToastBottomOffset(insets.bottom),
- opacity,
- },
- ]}
- >
- <View style={styles.toast}>
- <Pressable
- accessibilityHint={english ? "Opens the update action" : "打开更新操作"}
- accessibilityLabel={`${title}. ${detail}`}
- accessibilityRole="button"
- onPress={() => {
- if (status !== "downloading" && status !== "installing") {
- dismiss();
- void openUpdate();
- }
- }}
- style={styles.toastBody}
- >
- <View style={styles.iconWrap}>
- <ArrowUpCircle color="#059669" size={14} />
- </View>
- <View style={styles.copy}>
- <Text numberOfLines={1} style={styles.title}>{title}</Text>
- <Text numberOfLines={1} style={styles.detail}>{detail}</Text>
- </View>
- </Pressable>
- <Pressable
- accessibilityLabel={english ? "Dismiss" : "关闭"}
- accessibilityRole="button"
- hitSlop={8}
- onPress={dismiss}
- style={styles.close}
- >
- <X color="#94a3b8" size={14} />
- </Pressable>
- </View>
- </Animated.View>
- );
-};
-
-const baseStyles = StyleSheet.create({
- anchor: {
- alignItems: "center",
- left: 16,
- position: "absolute",
- right: 16,
- zIndex: 40,
- },
- toast: {
- alignItems: "center",
- alignSelf: "center",
- backgroundColor: "#ffffff",
- borderColor: "#d1fae5",
- borderRadius: 999,
- borderWidth: StyleSheet.hairlineWidth,
- elevation: 2,
- flexDirection: "row",
- gap: 2,
- maxWidth: 320,
- minHeight: 40,
- paddingLeft: 8,
- paddingRight: 4,
- paddingVertical: 6,
- shadowColor: "#0f172a",
- shadowOffset: { width: 0, height: 2 },
- shadowOpacity: 0.06,
- shadowRadius: 8,
- },
- toastBody: {
- alignItems: "center",
- flexDirection: "row",
- flexShrink: 1,
- gap: 8,
- minWidth: 0,
- paddingVertical: 2,
- },
- iconWrap: {
- alignItems: "center",
- backgroundColor: "#ecfdf5",
- borderRadius: 999,
- height: 22,
- justifyContent: "center",
- width: 22,
- },
- copy: {
- flexShrink: 1,
- gap: 0,
- minWidth: 0,
- paddingRight: 2,
- },
- title: {
- color: "#0f172a",
- fontSize: 12,
- fontWeight: "700",
- lineHeight: 15,
- },
- detail: {
- color: "#64748b",
- fontSize: 11,
- lineHeight: 14,
- },
- close: {
- alignItems: "center",
- height: 28,
- justifyContent: "center",
- width: 28,
- },
-});
diff --git a/apps/mobile/src/lib/android-apk-update.test.ts b/apps/mobile/src/lib/android-apk-update.test.ts
new file mode 100644
index 00000000..ce069bcf
--- /dev/null
+++ b/apps/mobile/src/lib/android-apk-update.test.ts
@@ -0,0 +1,97 @@
+import { beforeEach, expect, mock, test } from "bun:test";
+import type { MobileRelease } from "./mobile-release";
+
+const cachedFileSizes = new Map<string, number>();
+const installerCalls: string[] = [];
+let downloadCalls = 0;
+let installerResult = true;
+
+class MockFile {
+ readonly uri: string;
+
+ constructor(directory: string, fileName: string) {
+ this.uri = `${directory}/${fileName}`;
+ }
+
+ get exists() {
+ return cachedFileSizes.has(this.uri);
+ }
+
+ get size() {
+ return cachedFileSizes.get(this.uri) ?? 0;
+ }
+
+ delete() {
+ cachedFileSizes.delete(this.uri);
+ }
+
+ static async downloadFileAsync(
+ _url: string,
+ destination: MockFile,
+ options: { onProgress: (progress: { bytesWritten: number; totalBytes: number }) => void }
+ ) {
+ downloadCalls += 1;
+ options.onProgress({ bytesWritten: 24_000_000, totalBytes: 48_000_000 });
+ cachedFileSizes.set(destination.uri, 48_000_000);
+ return destination;
+ }
+}
+
+mock.module("expo-file-system", () => ({
+ File: MockFile,
+ Paths: { cache: "file:///cache" },
+}));
+
+mock.module("../../modules/edgeever-app-installer", () => ({
+ installAndroidApk: async (fileUri: string) => {
+ installerCalls.push(fileUri);
+ return installerResult;
+ },
+}));
+
+const { downloadAndroidApk, installDownloadedAndroidApk } = await import("./android-apk-update");
+
+const release: MobileRelease = {
+ digest: `sha256:${"a".repeat(64)}`,
+ downloadUrl: "https://github.com/tianma-if/edgeever/releases/download/v1.40.0/edgeever-android-v1.40.0-arm64-v8a.apk",
+ fileName: "edgeever-android-v1.40.0-arm64-v8a.apk",
+ size: 48_000_000,
+ version: "1.40.0",
+};
+
+beforeEach(() => {
+ cachedFileSizes.clear();
+ installerCalls.length = 0;
+ downloadCalls = 0;
+ installerResult = true;
+});
+
+test("downloads the APK without opening the installer", async () => {
+ const progress: number[] = [];
+ const fileUri = await downloadAndroidApk(release, ({ progress: value }) => progress.push(value));
+
+ expect(fileUri).toBe(`file:///cache/${release.fileName}`);
+ expect(downloadCalls).toBe(1);
+ expect(installerCalls).toEqual([]);
+ expect(progress).toEqual([0.5, 1]);
+});
+
+test("reuses a complete cached APK", async () => {
+ const cachedUri = `file:///cache/${release.fileName}`;
+ cachedFileSizes.set(cachedUri, release.size);
+ const progress: number[] = [];
+
+ expect(await downloadAndroidApk(release, ({ progress: value }) => progress.push(value))).toBe(cachedUri);
+ expect(downloadCalls).toBe(0);
+ expect(progress).toEqual([1]);
+});
+
+test("opens the installer only after the prepared APK is accepted", async () => {
+ const fileUri = `file:///cache/${release.fileName}`;
+
+ await installDownloadedAndroidApk(fileUri);
+ expect(installerCalls).toEqual([fileUri]);
+
+ installerResult = false;
+ await expect(installDownloadedAndroidApk(fileUri)).rejects.toThrow("Permission to install apps was not granted");
+});
diff --git a/apps/mobile/src/lib/android-apk-update.ts b/apps/mobile/src/lib/android-apk-update.ts
index 883ad1ce..e0998fb9 100644
--- a/apps/mobile/src/lib/android-apk-update.ts
+++ b/apps/mobile/src/lib/android-apk-update.ts
@@ -1,8 +1,5 @@
import type { MobileRelease } from "./mobile-release";
-
-const APK_MIME_TYPE = "application/vnd.android.package-archive";
-const ACTION_VIEW = "android.intent.action.VIEW";
-const FLAG_GRANT_READ_URI_PERMISSION = 1;
+import { installAndroidApk } from "../../modules/edgeever-app-installer";
export type AndroidApkDownloadProgress = {
downloadedBytes: number;
@@ -10,18 +7,22 @@ export type AndroidApkDownloadProgress = {
totalBytes: number;
};
-export const downloadAndInstallAndroidApk = async (
+export const downloadAndroidApk = async (
release: MobileRelease,
- onProgress: (progress: AndroidApkDownloadProgress) => void,
- onDownloaded: () => void
+ onProgress: (progress: AndroidApkDownloadProgress) => void
) => {
- const [{ File, Paths }, LegacyFileSystem, IntentLauncher] = await Promise.all([
- import("expo-file-system"),
- import("expo-file-system/legacy"),
- import("expo-intent-launcher"),
- ]);
+ const { File, Paths } = await import("expo-file-system");
const destination = new File(Paths.cache, release.fileName);
+ if (destination.exists && destination.size === release.size) {
+ onProgress({ downloadedBytes: release.size, progress: 1, totalBytes: release.size });
+ return destination.uri;
+ }
+
+ if (destination.exists) {
+ destination.delete();
+ }
+
try {
const downloadedFile = await File.downloadFileAsync(release.downloadUrl, destination, {
idempotent: true,
@@ -40,13 +41,7 @@ export const downloadAndInstallAndroidApk = async (
}
onProgress({ downloadedBytes: release.size, progress: 1, totalBytes: release.size });
- onDownloaded();
- const contentUri = await LegacyFileSystem.getContentUriAsync(downloadedFile.uri);
- await IntentLauncher.startActivityAsync(ACTION_VIEW, {
- data: contentUri,
- flags: FLAG_GRANT_READ_URI_PERMISSION,
- type: APK_MIME_TYPE,
- });
+ return downloadedFile.uri;
} catch (error) {
if (destination.exists) {
destination.delete();
@@ -54,3 +49,10 @@ export const downloadAndInstallAndroidApk = async (
throw error;
}
};
+
+export const installDownloadedAndroidApk = async (fileUri: string) => {
+ const installerOpened = await installAndroidApk(fileUri);
+ if (!installerOpened) {
+ throw new Error("Permission to install apps was not granted");
+ }
+};
diff --git a/apps/mobile/src/lib/mobile-update-toast-layout.test.ts b/apps/mobile/src/lib/mobile-update-toast-layout.test.ts
deleted file mode 100644
index e6ee0086..00000000
--- a/apps/mobile/src/lib/mobile-update-toast-layout.test.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { getMobileUpdateToastBottomOffset } from "./mobile-update-toast-layout";
-
-describe("mobile update toast layout", () => {
- test("clears the raised create button without a gesture inset", () => {
- expect(getMobileUpdateToastBottomOffset(0)).toBe(92);
- });
-
- test("adds the Android gesture inset below the bottom navigation", () => {
- expect(getMobileUpdateToastBottomOffset(24)).toBe(104);
- });
-});
diff --git a/apps/mobile/src/lib/mobile-update-toast-layout.ts b/apps/mobile/src/lib/mobile-update-toast-layout.ts
deleted file mode 100644
index 7dd65231..00000000
--- a/apps/mobile/src/lib/mobile-update-toast-layout.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { MOBILE_UI_METRICS } from "@edgeever/shared/mobile-ui";
-
-const MIN_SCREEN_EDGE_INSET = 12;
-const FLOATING_CONTROL_CLEARANCE = 12;
-
-/** Keep the update toast above the bottom navigation and its raised create button. */
-export const getMobileUpdateToastBottomOffset = (safeAreaBottom: number): number =>
- Math.max(safeAreaBottom, MIN_SCREEN_EDGE_INSET)
- + MOBILE_UI_METRICS.bottomNavigationHeight
- + MOBILE_UI_METRICS.floatingCreateButtonLift
- + FLOATING_CONTROL_CLEARANCE;
diff --git a/apps/mobile/src/lib/mobile-update.tsx b/apps/mobile/src/lib/mobile-update.tsx
index 146e80bb..e82822a9 100644
--- a/apps/mobile/src/lib/mobile-update.tsx
+++ b/apps/mobile/src/lib/mobile-update.tsx
@@ -4,7 +4,7 @@ import { AppState, Platform, type AppStateStatus } from "react-native";
import * as Updates from "expo-updates";
import { Alert } from "../components/LocalizedText";
import { useMobileLocale } from "./mobile-locale";
-import { downloadAndInstallAndroidApk } from "./android-apk-update";
+import { downloadAndroidApk, installDownloadedAndroidApk } from "./android-apk-update";
import { findNewerMobileRelease, type MobileRelease } from "./mobile-release";
const FOREGROUND_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
@@ -37,15 +37,97 @@ const MobileUpdateContext = createContext<MobileUpdateContextValue>({
export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
const { resolvedLocale } = useMobileLocale();
const [downloadProgress, setDownloadProgress] = useState<number | null>(null);
+ const [downloadedInstallFileUri, setDownloadedInstallFileUri] = useState<string | null>(null);
const [installRelease, setInstallRelease] = useState<MobileRelease | null>(null);
const [status, setStatus] = useState<MobileUpdateStatus>("idle");
const [updateKind, setUpdateKind] = useState<MobileUpdateKind | null>(null);
const activeCheckRef = useRef<Promise<void> | null>(null);
+ const activeDownloadRef = useRef<Promise<string> | null>(null);
const lastAutomaticCheckRef = useRef(0);
+ const pendingInstallPromptRef = useRef<{ fileUri: string; release: MobileRelease } | null>(null);
+ const promptedInstallVersionRef = useRef<string | null>(null);
const isSupported = !__DEV__ && Updates.isEnabled;
const english = resolvedLocale === "en-US";
const installedVersion = Updates.runtimeVersion ?? Constants.expoConfig?.version ?? null;
+ const openPreparedInstaller = useCallback((release: MobileRelease, fileUri: string) => {
+ Alert.alert(
+ english ? "Update ready" : "更新已就绪",
+ english
+ ? `EdgeEver ${release.version} has been downloaded and is ready to install.`
+ : `EdgeEver ${release.version} 安装包已下载完成,可以立即安装。`,
+ [
+ {
+ text: english ? "Later" : "稍后",
+ style: "cancel",
+ },
+ {
+ text: english ? "Install now" : "立即安装",
+ onPress: () => {
+ setStatus("installing");
+ void installDownloadedAndroidApk(fileUri).then(() => {
+ setStatus("ready");
+ }).catch(() => {
+ setStatus("ready");
+ Alert.alert(
+ english ? "Could not open installer" : "无法打开安装器",
+ english
+ ? "Allow EdgeEver to install apps when prompted, then try again."
+ : "请在系统提示时允许 EdgeEver 安装应用,然后重试。"
+ );
+ });
+ },
+ },
+ ]
+ );
+ }, [english]);
+
+ const promptPreparedInstallerWhenActive = useCallback((release: MobileRelease, fileUri: string) => {
+ if (promptedInstallVersionRef.current === release.version) {
+ return;
+ }
+ if (AppState.currentState !== "active") {
+ pendingInstallPromptRef.current = { fileUri, release };
+ return;
+ }
+ pendingInstallPromptRef.current = null;
+ promptedInstallVersionRef.current = release.version;
+ openPreparedInstaller(release, fileUri);
+ }, [openPreparedInstaller]);
+
+ const prepareInstallRelease = useCallback(async (release: MobileRelease, promptWhenReady: boolean) => {
+ setInstallRelease(release);
+ setUpdateKind("install");
+
+ let download = activeDownloadRef.current;
+ if (!download) {
+ setDownloadProgress(0);
+ setStatus("downloading");
+ download = downloadAndroidApk(release, ({ progress }) => setDownloadProgress(progress));
+ activeDownloadRef.current = download;
+ }
+
+ try {
+ const fileUri = await download;
+ setDownloadedInstallFileUri(fileUri);
+ setDownloadProgress(null);
+ setStatus("ready");
+ if (promptWhenReady) {
+ promptPreparedInstallerWhenActive(release, fileUri);
+ }
+ return fileUri;
+ } catch (error) {
+ setDownloadedInstallFileUri(null);
+ setDownloadProgress(null);
+ setStatus("available");
+ throw error;
+ } finally {
+ if (activeDownloadRef.current === download) {
+ activeDownloadRef.current = null;
+ }
+ }
+ }, [promptPreparedInstallerWhenActive]);
+
const runCheck = useCallback((userInitiated: boolean) => {
if (activeCheckRef.current) {
return activeCheckRef.current;
@@ -74,9 +156,18 @@ export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
}
const release = await findNewerMobileRelease(installedVersion);
if (release) {
- setInstallRelease(release);
- setUpdateKind("install");
- setStatus("available");
+ try {
+ await prepareInstallRelease(release, true);
+ } catch {
+ if (userInitiated) {
+ Alert.alert(
+ english ? "Download failed" : "下载失败",
+ english
+ ? "Could not prepare the update package. Check your connection and try again."
+ : "无法准备更新安装包,请检查网络后重试。"
+ );
+ }
+ }
return;
}
} catch {
@@ -107,7 +198,7 @@ export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
activeCheckRef.current = null;
});
return check;
- }, [english, installedVersion, isSupported]);
+ }, [english, installedVersion, isSupported, prepareInstallRelease]);
useEffect(() => {
const attemptAutomaticCheck = () => {
@@ -120,6 +211,10 @@ export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
const timer = setTimeout(attemptAutomaticCheck, 1_500);
const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
if (nextState === "active") {
+ const pendingPrompt = pendingInstallPromptRef.current;
+ if (pendingPrompt) {
+ promptPreparedInstallerWhenActive(pendingPrompt.release, pendingPrompt.fileUri);
+ }
attemptAutomaticCheck();
}
});
@@ -128,50 +223,25 @@ export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
clearTimeout(timer);
subscription.remove();
};
- }, [runCheck]);
+ }, [promptPreparedInstallerWhenActive, runCheck]);
const openUpdate = useCallback(async () => {
if (updateKind === "install") {
if (Platform.OS !== "android" || !installRelease || status === "downloading" || status === "installing") {
return;
}
- const sizeMb = Math.max(1, Math.ceil(installRelease.size / 1024 / 1024));
- Alert.alert(
- english ? "Update available" : "发现新版本",
- english
- ? `EdgeEver ${installRelease.version} is available. Download ${sizeMb} MB and install it now?`
- : `EdgeEver ${installRelease.version} 已发布。是否立即下载 ${sizeMb} MB 安装包并更新?`,
- [
- {
- text: english ? "Cancel" : "取消",
- style: "cancel",
- },
- {
- text: english ? "Download & install" : "下载并安装",
- onPress: () => {
- setDownloadProgress(0);
- setStatus("downloading");
- void downloadAndInstallAndroidApk(
- installRelease,
- ({ progress }) => setDownloadProgress(progress),
- () => setStatus("installing")
- ).then(() => {
- setDownloadProgress(null);
- setStatus("available");
- }).catch(() => {
- setDownloadProgress(null);
- setStatus("available");
- Alert.alert(
- english ? "Update failed" : "更新失败",
- english
- ? "Could not download or open the installer. Try again later."
- : "无法下载安装包或打开系统安装器,请稍后重试。"
- );
- });
- },
- },
- ]
- );
+ if (downloadedInstallFileUri) {
+ openPreparedInstaller(installRelease, downloadedInstallFileUri);
+ return;
+ }
+ void prepareInstallRelease(installRelease, true).catch(() => {
+ Alert.alert(
+ english ? "Download failed" : "下载失败",
+ english
+ ? "Could not prepare the update package. Check your connection and try again."
+ : "无法准备更新安装包,请检查网络后重试。"
+ );
+ });
return;
}
@@ -224,7 +294,7 @@ export const MobileUpdateProvider = ({ children }: { children: ReactNode }) => {
: "无法下载应用内更新,请稍后再试。"
);
}
- }, [english, installRelease, isSupported, status, updateKind]);
+ }, [downloadedInstallFileUri, english, installRelease, isSupported, openPreparedInstaller, prepareInstallRelease, status, updateKind]);
const value = useMemo<MobileUpdateContextValue>(
() => ({
diff --git a/apps/mobile/src/lib/preferences-update-toast.test.ts b/apps/mobile/src/lib/preferences-update-toast.test.ts
deleted file mode 100644
index 6ed083c7..00000000
--- a/apps/mobile/src/lib/preferences-update-toast.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { expect, test } from "bun:test";
-import { shouldShowMobileUpdateToastForVersion } from "./preferences";
-
-test("shows the update toast only once per installed version", () => {
- expect(shouldShowMobileUpdateToastForVersion("1.12.2", null)).toBe(true);
- expect(shouldShowMobileUpdateToastForVersion("1.12.2", "1.12.2")).toBe(false);
-});
-
-test("allows a new toast after the installed package version changes", () => {
- expect(shouldShowMobileUpdateToastForVersion("1.13.0", "1.12.2")).toBe(true);
-});
-
-test("does not show when the installed version is unknown", () => {
- expect(shouldShowMobileUpdateToastForVersion(null, null)).toBe(false);
- expect(shouldShowMobileUpdateToastForVersion(undefined, "1.12.2")).toBe(false);
-});
diff --git a/apps/mobile/src/lib/preferences.ts b/apps/mobile/src/lib/preferences.ts
index dc71d593..d25ebc8f 100644
--- a/apps/mobile/src/lib/preferences.ts
+++ b/apps/mobile/src/lib/preferences.ts
@@ -4,7 +4,6 @@ const MEMO_LIST_DENSITY_KEY = "edgeever.mobile.memoListDensity";
const IMAGE_COMPRESSION_KEY = "edgeever.mobile.imageCompressionEnabled";
const LOCALE_PREFERENCE_KEY = "edgeever.mobile.localePreference";
const THEME_PREFERENCE_KEY = "edgeever.mobile.themePreference";
-const UPDATE_TOAST_DISMISSED_VERSION_KEY = "edgeever.mobile.updateToastDismissedVersion";
export type MobileMemoListDensity = "preview" | "compact";
export type MobileLocalePreference = "system" | "zh-CN" | "en-US";
@@ -38,16 +37,4 @@ export const readMobileThemePreference = async (): Promise<MobileThemePreference
export const writeMobileThemePreference = (theme: MobileThemePreference) => AsyncStorage.setItem(THEME_PREFERENCE_KEY, theme);
-/** Installed app version for which the update toast was already shown (until the user upgrades). */
-export const readMobileUpdateToastDismissedVersion = async () => AsyncStorage.getItem(UPDATE_TOAST_DISMISSED_VERSION_KEY);
-
-export const writeMobileUpdateToastDismissedVersion = (installedVersion: string) =>
- AsyncStorage.setItem(UPDATE_TOAST_DISMISSED_VERSION_KEY, installedVersion);
-
-/** Show the toast only once per installed version while a newer package is available. */
-export const shouldShowMobileUpdateToastForVersion = (
- installedVersion: string | null | undefined,
- dismissedForVersion: string | null | undefined
-) => Boolean(installedVersion) && dismissedForVersion !== installedVersion;
-
const isMobileLocalePreference = (value: unknown): value is MobileLocalePreference => value === "system" || value === "zh-CN" || value === "en-US";
diff --git a/docs/mobile-build.md b/docs/mobile-build.md
index 50d74500..95d207e5 100644
--- a/docs/mobile-build.md
+++ b/docs/mobile-build.md
@@ -75,14 +75,15 @@ audited range includes mobile runtime code, shared mobile packages,
dependencies, native configuration, Android build tooling, or signer
verification.
-This locally signed APK prepares the Draft without requiring a Google Play
-submission. After the matching AAB is delivered, the store-delivery workflow
+This locally signed APK is only a temporary Draft asset and is never accepted
+for formal publication. After the matching AAB is delivered, the store-delivery workflow
downloads Google Play's signed universal APK and replaces the GitHub Release
asset under the established filename. Because the uploaded AAB contains only
`arm64-v8a`, the Play-generated APK also remains arm64-only. Publishing the
Play-signed APK lets Play and GitHub installations update each other without
uninstalling the app. The workflow pins and verifies the Play app-signing
-certificate before replacing the asset.
+certificate before replacing the asset. An independent pre-publication gate
+then verifies that the Draft APK uses only that Play app-signing certificate.
### Recommended local Play build
@@ -122,12 +123,14 @@ Set `EDGE_EVER_ANDROID_ENV_FILE` to use a different secure environment file.
### Automated store delivery
-The GitHub Release workflow never builds or uploads a Play bundle. After a
-formal Release that contains mobile changes is published, use the separate
+The GitHub Release workflow never builds or uploads a Play bundle. Before a
+Draft that contains mobile changes can be published, use the separate
store-delivery workflow. It builds a signed AAB from the immutable Release tag,
preserves the AAB and R8 mapping as Actions artifacts, and uploads the bundle
through EAS Submit. It then replaces the GitHub APK with the Play-signed
-universal APK. See [Mobile Store Delivery](store-delivery.md).
+universal APK. Rerun the release command after that workflow succeeds; it
+audits the Play signer and resumes publication. See
+[Mobile Store Delivery](store-delivery.md).
The upload keystore is only used to prove ownership when uploading bundles;
Google Play App Signing manages the app signing key delivered to users. Keep an
diff --git a/docs/release.md b/docs/release.md
index 3d86c791..2393dba5 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -58,7 +58,12 @@ previous installation check is actually needed.
the desktop application by default; installation remains available as an
explicit option.
Demo deployment continues independently after its Actions URL is printed.
-- Mobile store delivery is not part of this command. See
+- This command does not authorize or run mobile store delivery itself. After
+ Draft native assets are prepared, publication is blocked unless the Android
+ APK uses the Google Play app-signing certificate. If that gate fails, the
+ Release remains a Draft. Run
+ `bun run publish:stores -- --release vX.Y.Z --platform android --android-track production`
+ for that Draft, then rerun the original release command to resume. See
[Mobile Store Delivery](store-delivery.md).
## Registry Credentials
diff --git a/docs/release.zh-CN.md b/docs/release.zh-CN.md
index 9f513ca3..00eb3a2c 100644
--- a/docs/release.zh-CN.md
+++ b/docs/release.zh-CN.md
@@ -49,7 +49,11 @@ bun run release -- \
Docker 镜像并同时写入 GHCR 与腾讯云 TCR 公共镜像、正式发布、关闭 Issue,
默认不安装桌面端应用;安装能力作为显式选项保留。
输出 Actions 链接后,Demo 部署会独立继续执行。
-- 此命令不执行移动端商店交付,详见
+- 此命令不会自行授权或执行移动端商店交付。Draft 原生资产准备完成后,发布
+ 命令会强制核验 Android APK 是否使用 Google Play 应用签名证书;未通过时
+ 保持 Draft 并停止。此时先针对同一 Draft 执行
+ `bun run publish:stores -- --release vX.Y.Z --platform android --android-track production`,
+ 再重新执行原发布命令续跑。详见
[移动端商店交付](store-delivery.zh-CN.md)。
## 镜像仓库凭据
diff --git a/docs/store-delivery.md b/docs/store-delivery.md
index ecd4806c..a741826a 100644
--- a/docs/store-delivery.md
+++ b/docs/store-delivery.md
@@ -2,10 +2,13 @@
GitHub Releases and mobile store delivery are separate operations:
-- `bun run release` creates and audits the GitHub Release. It never contacts
- Google Play or App Store Connect.
-- `bun run publish:stores` dispatches a manual store-delivery workflow for one
- existing formal Release tag.
+- `bun run release` creates and audits the GitHub Release, but does not itself
+ authorize access to Google Play or App Store Connect. Android assets cannot
+ be published until they pass the Play app-signing gate.
+- `bun run publish:stores` dispatches a manual store-delivery workflow for a
+ matching Draft or an existing formal Release tag. When Android is rebuilt,
+ run it against the Draft so the Play-signed APK replaces the temporary
+ locally signed APK before publication.
- Store delivery is the authorization to submit. By default, Google Play uses
the Production track, while iOS continues from App Store Connect upload into
App Review. Approved builds are released automatically.
@@ -15,7 +18,7 @@ GitHub Releases and mobile store delivery are separate operations:
The workflow checks out the immutable Release tag rather than `main`. Before any
store build starts, it verifies that:
-- the tag belongs to a formal, non-prerelease GitHub Release;
+- the tag belongs to a matching Draft or formal, non-prerelease GitHub Release;
- the Release target and Git tag resolve to the same commit;
- the audited range since the previous formal Release contains mobile runtime
changes;
@@ -25,6 +28,13 @@ store build starts, it verifies that:
A Release that reused the previous mobile binary is intentionally rejected. It
does not represent a new store binary and should not be uploaded again.
+The publication gate accepts only `ANDROID_PLAY_APP_SIGNER_SHA256`. An APK
+signed by the local upload certificate may temporarily exist in a Draft for
+store processing, but cannot become the final Android asset of a formal
+Release. A failed gate leaves the Release as a Draft. If someone bypasses the
+release command and publishes manually, the `published` audit rejects that APK
+and restores Draft state.
+
## Prerequisites
Configure these GitHub repository secrets:
@@ -67,6 +77,15 @@ Submit both platforms to Google Play Production and Apple App Review:
bun run publish:stores -- --release v1.7.0
```
+Prepare the Android Play-signed asset for a Draft before formal publication:
+
+```sh
+bun run publish:stores -- \
+ --release v1.7.0 \
+ --platform android \
+ --android-track production
+```
+
Deliver only Android to a closed testing track:
```sh
@@ -88,7 +107,8 @@ Actions artifacts, and uploads the AAB through EAS Submit.
After Google Play finishes processing the bundle, the workflow downloads the
Play-signed universal APK, verifies the pinned app-signing certificate, and
-replaces the GitHub Release Android asset. This makes installations from
+replaces the Draft or formal GitHub Release Android asset. A Draft replacement
+must also pass the independent pre-publication signature gate. This makes installations from
Google Play and GitHub mutually updateable. The uploaded AAB is intentionally
limited to `arm64-v8a`, so the Play-generated universal APK does not bundle
unused 32-bit ARM or x86 native libraries. Automatic Protection must be
diff --git a/docs/store-delivery.zh-CN.md b/docs/store-delivery.zh-CN.md
index 7d0b503e..f34889fc 100644
--- a/docs/store-delivery.zh-CN.md
+++ b/docs/store-delivery.zh-CN.md
@@ -2,10 +2,11 @@
GitHub Release 与移动端商店交付是两个独立操作:
-- `bun run release` 只创建并审计 GitHub Release,不会访问 Google Play 或
- App Store Connect。
-- `bun run publish:stores` 针对一个已经存在的正式 Release tag,触发手动商店
- 交付工作流。
+- `bun run release` 创建并审计 GitHub Release,但不会自行授权访问 Google Play
+ 或 App Store Connect。Android 资产只有通过 Play 应用签名门禁后才能正式发布。
+- `bun run publish:stores` 针对一个匹配的 Draft 或已经存在的正式 Release tag,
+ 触发手动商店交付工作流。Android 重建时应在 Draft 阶段执行,以便正式发布前
+ 用 Play 签名 APK 替换临时的本地签名 APK。
- 触发商店交付就代表已经授权正式提交。默认情况下,Google Play 使用
Production 轨道;iOS 在上传 App Store Connect 后继续提交 App Review。审核
通过后自动发布。
@@ -14,7 +15,7 @@ GitHub Release 与移动端商店交付是两个独立操作:
工作流检出不可变的 Release tag,而不是 `main`。开始任何商店构建前都会验证:
-- tag 属于正式、非 Prerelease 的 GitHub Release;
+- tag 属于匹配的 Draft 或正式、且非 Prerelease 的 GitHub Release;
- Release 目标提交与 Git tag 指向同一个提交;
- 与上一个正式 Release 相比,审计范围内确实包含移动端运行时代码变化;
- 根版本和移动端 App 版本都与 Release tag 一致;
@@ -23,6 +24,11 @@ GitHub Release 与移动端商店交付是两个独立操作:
如果某个 Release 复用了上一版移动端二进制,工作流会主动拒绝。它不代表新的
商店二进制,不应重复上传。
+正式发布门禁只接受 `ANDROID_PLAY_APP_SIGNER_SHA256`。本地上传证书签名的 APK
+可以暂存在 Draft 中供商店处理,但不能成为正式 Release 的最终 Android 资产;
+门禁失败时发布命令会停止并保留 Draft。即使绕过发布命令手动公开 Release,
+`published` 审计也会拒绝该 APK 并恢复 Draft。
+
## 前置配置
在 GitHub 仓库中配置以下 Secrets:
@@ -62,6 +68,15 @@ EAS Submit 要求应用已经在对应商店中创建;Google Play API 提交
bun run publish:stores -- --release v1.7.0
```
+在正式发布前为 Draft 准备 Android Play 签名资产:
+
+```sh
+bun run publish:stores -- \
+ --release v1.7.0 \
+ --platform android \
+ --android-track production
+```
+
只将 Android 交付到封闭测试轨道:
```sh
@@ -82,7 +97,8 @@ R8 Mapping,将两者保留为 GitHub Actions Artifacts,然后通过 EAS Subm
AAB。
Google Play 处理完 AAB 后,工作流会下载由 Play 应用签名密钥签名的通用 APK,
-核对固定的应用签名证书,并替换 GitHub Release 中的 Android 资产。这样从 Play
+核对固定的应用签名证书,并替换 Draft 或正式 GitHub Release 中的 Android 资产。
+Draft 中的替换结果还必须通过独立的发布前签名门禁。这样从 Play
和 GitHub 安装的版本可以互相覆盖升级。上传的 AAB 会明确限制为
`arm64-v8a`,因此 Play 生成的通用 APK 不会再打包无用的 32 位 ARM 或 x86
原生库。该 Release 必须关闭 Automatic Protection;当 Play 返回带安装来源限制
diff --git a/scripts/desktop-build-workflow.test.mjs b/scripts/desktop-build-workflow.test.mjs
index 561db6c3..2b3a3d67 100644
--- a/scripts/desktop-build-workflow.test.mjs
+++ b/scripts/desktop-build-workflow.test.mjs
@@ -21,6 +21,11 @@ describe("desktop release workflow", () => {
expect(regressionTests).toBeLessThan(releasePlan);
});
+ test("rejects a published APK that is not Play-signed and restores Draft state", () => {
+ expect(mobileWorkflow).toContain("github.event_name == 'release' && secrets.ANDROID_PLAY_APP_SIGNER_SHA256");
+ expect(mobileWorkflow).toContain('gh release edit "$CURRENT_TAG" --repo "$GITHUB_REPOSITORY" --draft=true');
+ });
+
test("assigns shared validation only to the arm64 matrix job", () => {
expect(workflow).toContain([
" - arch: arm64",
diff --git a/scripts/plan-native-release.mjs b/scripts/plan-native-release.mjs
index ec82ba13..53a61ddc 100644
--- a/scripts/plan-native-release.mjs
+++ b/scripts/plan-native-release.mjs
@@ -39,6 +39,7 @@ export const planNativeRelease = (platform, changedFiles) => {
platform === "mobile"
? new Set([
".github/workflows/mobile-build.yml",
+ ".github/workflows/android-play-signature-audit.yml",
".github/workflows/store-delivery.yml",
"bun.lock",
"scripts/build-android-local.sh",
diff --git a/scripts/plan-native-release.test.mjs b/scripts/plan-native-release.test.mjs
index cee8be53..6c215c14 100644
--- a/scripts/plan-native-release.test.mjs
+++ b/scripts/plan-native-release.test.mjs
@@ -22,6 +22,7 @@ describe("native release planning", () => {
"scripts/configure-android-package-permissions.mjs",
"scripts/verify-android-apk-signature.mjs",
".github/workflows/mobile-build.yml",
+ ".github/workflows/android-play-signature-audit.yml",
".github/workflows/store-delivery.yml",
"scripts/download-play-universal-apk.mjs",
];
diff --git a/scripts/release.mjs b/scripts/release.mjs
index 5d1c2cb4..a7d39210 100644
--- a/scripts/release.mjs
+++ b/scripts/release.mjs
@@ -24,6 +24,7 @@ const RUN_DISCOVERY_TIMEOUT_MS = 60_000;
export const RELEASE_WORKFLOWS = {
desktop: "desktop-build.yml",
mobile: "mobile-build.yml",
+ androidPlaySignature: "android-play-signature-audit.yml",
docker: "docker-image.yml",
demo: "deploy-demo.yml",
};
@@ -358,7 +359,7 @@ export const buildIssueBody = ({ changesEn, changesZh, commitCoverageAudit }) =>
"## Acceptance criteria",
"",
"- Required type checks, Web build, and native release planning tests pass.",
- "- The Draft Release contains audited macOS arm64 and x64 DMGs and an Android arm64 APK.",
+ "- The Draft Release contains audited macOS arm64 and x64 DMGs and a Play-signed Android arm64 APK.",
"- Post-publication native asset audits pass.",
].join("\n");
@@ -1073,6 +1074,22 @@ const releaseMain = async (options) => {
mobileRebuild: mobilePlan.rebuild,
});
+ console.log(
+ `[release] requiring the Draft Android APK to use the Google Play app-signing certificate; ` +
+ `if this fails, run "bun run publish:stores -- --release ${tag} --platform android --android-track production" and resume the release.`,
+ );
+ const androidPlaySignatureRunId = await dispatchReleaseWorkflow({
+ repository: options.repository,
+ workflow: RELEASE_WORKFLOWS.androidPlaySignature,
+ tag,
+ headSha: releaseSha,
+ });
+ await waitForRun({
+ repository: options.repository,
+ runId: androidPlaySignatureRunId,
+ label: "Draft Android Play signature gate",
+ });
+
const publishedAt = Date.now();
const releaseUrl = run("gh", [
"release",
diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs
index 1d9906ea..c5685cda 100644
--- a/scripts/release.test.mjs
+++ b/scripts/release.test.mjs
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
import {
auditReleaseCommitCoverage,
buildIssueBody,
@@ -20,6 +21,16 @@ describe("release automation", () => {
expect(RELEASE_WORKFLOWS.docker).toBe("docker-image.yml");
});
+ test("blocks publication until the Draft Android APK passes the Play signature gate", () => {
+ const releaseSource = readFileSync(new URL("./release.mjs", import.meta.url), "utf8");
+ const signatureGate = releaseSource.indexOf('label: "Draft Android Play signature gate"');
+ const publication = releaseSource.indexOf('"--draft=false"');
+
+ expect(RELEASE_WORKFLOWS.androidPlaySignature).toBe("android-play-signature-audit.yml");
+ expect(signatureGate).toBeGreaterThanOrEqual(0);
+ expect(publication).toBeGreaterThan(signatureGate);
+ });
+
test("runs the complete project regression suite before release", () => {
expect(RELEASE_VALIDATIONS).toContainEqual({
label: "Project regression tests",
@@ -260,6 +271,7 @@ describe("release automation", () => {
expect(body).toContain("## 中文说明");
expect(body).toContain("- 并行检查。");
expect(body).toContain("## Commit coverage audit");
+ expect(body).toContain("Play-signed Android arm64 APK");
expect(body).toContain("- Change 1: `aaaaaaaa`");
expect(body).toContain("- Excluded `bbbbbbbb`: test-only coverage");
});
diff --git a/scripts/store-delivery.test.mjs b/scripts/store-delivery.test.mjs
index 075b76e2..70200f1e 100644
--- a/scripts/store-delivery.test.mjs
+++ b/scripts/store-delivery.test.mjs
@@ -54,6 +54,29 @@ describe("store delivery command", () => {
expect(workflow).toContain('gh release upload "$RELEASE_TAG" "$apk_path"');
});
+ test("can prepare a matching Draft before formal publication", () => {
+ const workflow = readFileSync(
+ new URL("../.github/workflows/store-delivery.yml", import.meta.url),
+ "utf8",
+ );
+
+ expect(workflow).toContain('if [[ "$release_is_draft" = "true" ]]');
+ expect(workflow).toContain('previous_tag="${release_tags[0]:-}"');
+ expect(workflow).not.toContain('test "$(jq -r \'.draft\' <<<"$release")" = "false"');
+ });
+
+ test("uses a dedicated Draft audit that accepts only the Play app signer", () => {
+ const workflow = readFileSync(
+ new URL("../.github/workflows/android-play-signature-audit.yml", import.meta.url),
+ "utf8",
+ );
+
+ expect(workflow).toContain("github.repository == 'tianma-if/edgeever'");
+ expect(workflow).toContain('test "$(jq -r \'.draft\' <<<"$release")" = "true"');
+ expect(workflow).toContain("EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}");
+ expect(workflow).not.toContain("22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87");
+ });
+
test("keeps the Play bundle and generated Release APK arm64-only", () => {
const workflow = readFileSync(
new URL("../.github/workflows/store-delivery.yml", import.meta.url),