Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): route Google Play installs away from website APK updates (#5181)

bobofd73bc91fd3d
diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js
index e5e0f20bdf..92612eefc4 100644
--- a/apps/mobile/app.config.js
+++ b/apps/mobile/app.config.js
@@ -384,7 +384,7 @@ module.exports = (context = {}) => {
...next,
android: {
...next.android,
- // Only APK self-distribution requests permission to install updates.
+ // Self-hosted APK and AAB share native config; Play installs skip APK updates at runtime.
permissions: [...new Set([
...(next.android.permissions || []),
'android.permission.REQUEST_INSTALL_PACKAGES',
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 1c5f3cc4e2..c6260d390b 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -98,6 +98,7 @@ import { DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL } from '@cindy/maker-shared/de
import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';
import { buildMobileUpdateInfoRows, currentMobileOtaVersion } from '@/settings/updateInfo';
import { shouldCheckBundleUpdate } from '@/update/bundleUpdate';
+import { isGooglePlayInstallation } from '@/update/androidInstallSource';
import {
manualUpdateCheckMessage,
runManualUpdateCheck,
@@ -271,19 +272,22 @@ export default function SettingsScreen() {
auto: false,
channel: updateChannel.channel,
});
+ const playManagedUpdates = Platform.OS === 'android' && isGooglePlayInstallation();
const bundleCheckEnabled = shouldCheckBundleUpdate({
isSelfHosted: IS_OTA_SELFHOST,
isReviewMode: REVIEW_MODE,
isTestFlightBuild: IS_TESTFLIGHT_BUILD,
+ isGooglePlayInstallation: playManagedUpdates,
});
const updateCheckEnabled = bundleCheckEnabled || updatesEnabled;
// 保存未翻译的结果,语言切换触发重渲染时用当前 t() 重新生成提示。
const updateMessage = useMemo(
() => updateOutcome && manualUpdateCheckMessage(updateOutcome, {
isTestFlightBuild: IS_TESTFLIGHT_BUILD,
+ isGooglePlayInstallation: playManagedUpdates,
t,
}),
- [t, updateOutcome],
+ [playManagedUpdates, t, updateOutcome],
);
const aboutSection = overview.sections.find((section) => section.id === 'about');
@@ -970,7 +974,7 @@ export default function SettingsScreen() {
const updateButtonLabel = updatePhase === 'checking' ? t('settings.version.checking')
: updatePhase === 'downloading' ? t('settings.version.updating')
: t(
- IS_TESTFLIGHT_BUILD
+ IS_TESTFLIGHT_BUILD || playManagedUpdates
? 'settings.version.testFlightCheckAction'
: 'settings.version.checkAction',
);
@@ -1056,6 +1060,11 @@ export default function SettingsScreen() {
{t('settings.version.testFlightUpdateManaged')}
</Text>
) : null}
+ {playManagedUpdates ? (
+ <Text style={styles.rowDetail} numberOfLines={2} testID="settings.googlePlayUpdateHint">
+ {t('settings.version.googlePlayUpdateManaged')}
+ </Text>
+ ) : null}
{updateMessage ? (
<Text style={styles.rowDetail} numberOfLines={2} testID="settings.updateMessage">{updateMessage}</Text>
) : !REVIEW_MODE && !updatesEnabled ? (
@@ -1063,7 +1072,9 @@ export default function SettingsScreen() {
{t(
IS_TESTFLIGHT_BUILD
? 'settings.version.testFlightContentUpdateUnavailable'
- : 'settings.version.devNoOta',
+ : playManagedUpdates
+ ? 'settings.version.googlePlayContentUpdateUnavailable'
+ : 'settings.version.devNoOta',
)}
</Text>
) : null}
@@ -1074,12 +1085,12 @@ export default function SettingsScreen() {
action={{
accessibilityLabel: updateBusy
? t(
- IS_TESTFLIGHT_BUILD
+ IS_TESTFLIGHT_BUILD || playManagedUpdates
? 'settings.version.testFlightCheckingAccessibility'
: 'settings.version.checkingAccessibility',
)
: t(
- IS_TESTFLIGHT_BUILD
+ IS_TESTFLIGHT_BUILD || playManagedUpdates
? 'settings.version.testFlightCheckAction'
: 'settings.version.checkAction',
),
diff --git a/apps/mobile/modules/cindy-app-installer/android/src/main/java/expo/modules/cindyappinstaller/CindyAppInstallerModule.kt b/apps/mobile/modules/cindy-app-installer/android/src/main/java/expo/modules/cindyappinstaller/CindyAppInstallerModule.kt
index dfe99e6c84..304f1b9702 100644
--- a/apps/mobile/modules/cindy-app-installer/android/src/main/java/expo/modules/cindyappinstaller/CindyAppInstallerModule.kt
+++ b/apps/mobile/modules/cindy-app-installer/android/src/main/java/expo/modules/cindyappinstaller/CindyAppInstallerModule.kt
@@ -27,6 +27,19 @@ class CindyAppInstallerModule : Module() {
Function("isSupported") {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && declaresInstallPermission()
}
+ Function("installerPackageName") {
+ val context = appContext.reactContext ?: return@Function null
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ context.packageManager.getInstallSourceInfo(context.packageName).installingPackageName
+ } else {
+ @Suppress("DEPRECATION")
+ context.packageManager.getInstallerPackageName(context.packageName)
+ }
+ } catch (_: Exception) {
+ null
+ }
+ }
AsyncFunction("hasPermission") { declaresInstallPermission() && canInstall() }
AsyncFunction("requestPermission") { promise: Promise ->
when {
diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.json
index 24d5185ea9..f3993b66a5 100644
--- a/apps/mobile/src/i18n/locales/en/settings.json
+++ b/apps/mobile/src/i18n/locales/en/settings.json
@@ -61,6 +61,9 @@
"testFlightUpdateManaged": "TestFlight manages test build updates",
"testFlightNoContentUpdate": "No content updates are available. Check TestFlight for new test builds.",
"testFlightContentUpdateUnavailable": "This build cannot check for content updates. Check TestFlight for new test builds.",
+ "googlePlayUpdateManaged": "Google Play manages app version updates",
+ "googlePlayNoContentUpdate": "No content updates are available. Check Google Play for new app versions.",
+ "googlePlayContentUpdateUnavailable": "This build cannot check for content updates. Check Google Play for new app versions.",
"bundleUpdateFound": "App package update available",
"upToDate": "Already up to date",
"bundleUpToDateNoOta": "App package is up to date; this version does not support OTA updates",
diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.json
index f8202402af..c80bda7f8e 100644
--- a/apps/mobile/src/i18n/locales/ja/settings.json
+++ b/apps/mobile/src/i18n/locales/ja/settings.json
@@ -61,6 +61,9 @@
"testFlightUpdateManaged": "テスト版アプリの更新は TestFlight で管理されます",
"testFlightNoContentUpdate": "利用可能なコンテンツ更新はありません。新しいテスト版は TestFlight で確認してください。",
"testFlightContentUpdateUnavailable": "このビルドではコンテンツ更新を確認できません。新しいテスト版は TestFlight で確認してください。",
+ "googlePlayUpdateManaged": "アプリ本体の更新は Google Play で管理されます",
+ "googlePlayNoContentUpdate": "利用可能なコンテンツ更新はありません。新しいアプリ版は Google Play で確認してください。",
+ "googlePlayContentUpdateUnavailable": "このビルドではコンテンツ更新を確認できません。新しいアプリ版は Google Play で確認してください。",
"bundleUpdateFound": "アプリ本体の更新があります",
"upToDate": "すでに最新の状態です",
"bundleUpToDateNoOta": "アプリ本体は最新です。このバージョンは OTA 更新に対応していません",
diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.json
index a0131f0022..93280a1e36 100644
--- a/apps/mobile/src/i18n/locales/ko/settings.json
+++ b/apps/mobile/src/i18n/locales/ko/settings.json
@@ -61,6 +61,9 @@
"testFlightUpdateManaged": "테스트 빌드 업데이트는 TestFlight에서 관리합니다",
"testFlightNoContentUpdate": "사용 가능한 콘텐츠 업데이트가 없습니다. 새 테스트 빌드는 TestFlight에서 확인해 주세요.",
"testFlightContentUpdateUnavailable": "이 빌드에서는 콘텐츠 업데이트를 확인할 수 없습니다. 새 테스트 빌드는 TestFlight에서 확인해 주세요.",
+ "googlePlayUpdateManaged": "앱 버전 업데이트는 Google Play에서 관리합니다",
+ "googlePlayNoContentUpdate": "사용 가능한 콘텐츠 업데이트가 없습니다. 새 앱 버전은 Google Play에서 확인해 주세요.",
+ "googlePlayContentUpdateUnavailable": "이 빌드에서는 콘텐츠 업데이트를 확인할 수 없습니다. 새 앱 버전은 Google Play에서 확인해 주세요.",
"bundleUpdateFound": "앱 패키지 업데이트가 있습니다",
"upToDate": "이미 최신 버전입니다",
"bundleUpToDateNoOta": "앱 패키지는 최신입니다. 현재 버전은 OTA 업데이트를 지원하지 않습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.json
index 1ee7a24b1b..5c65bff9d8 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json
@@ -61,6 +61,9 @@
"testFlightUpdateManaged": "测试版安装更新由 TestFlight 管理",
"testFlightNoContentUpdate": "当前没有可用的内容更新。新测试版本请在 TestFlight 中查看。",
"testFlightContentUpdateUnavailable": "当前构建无法检查内容更新。新测试版本请在 TestFlight 中查看。",
+ "googlePlayUpdateManaged": "应用版本更新由 Google Play 管理",
+ "googlePlayNoContentUpdate": "当前没有可用的内容更新。新应用版本请在 Google Play 中查看。",
+ "googlePlayContentUpdateUnavailable": "当前构建无法检查内容更新。新应用版本请在 Google Play 中查看。",
"bundleUpdateFound": "发现整包更新",
"upToDate": "已是最新版本",
"bundleUpToDateNoOta": "整包已是最新,当前版本不支持热更新",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.json
index 58f9b4dfb8..ebdddcd6df 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json
@@ -61,6 +61,9 @@
"testFlightUpdateManaged": "測試版安裝更新由 TestFlight 管理",
"testFlightNoContentUpdate": "當前沒有可用的內容更新。新測試版本請在 TestFlight 中檢視。",
"testFlightContentUpdateUnavailable": "當前構建無法檢查內容更新。新測試版本請在 TestFlight 中檢視。",
+ "googlePlayUpdateManaged": "應用程式版本更新由 Google Play 管理",
+ "googlePlayNoContentUpdate": "目前沒有可用的內容更新。新應用程式版本請在 Google Play 中查看。",
+ "googlePlayContentUpdateUnavailable": "目前無法檢查內容更新。新應用程式版本請在 Google Play 中查看。",
"bundleUpdateFound": "發現整包更新",
"upToDate": "已是最新版本",
"bundleUpToDateNoOta": "整包已是最新,當前版本不支援熱更新",
diff --git a/apps/mobile/src/update/androidInstallSource.test.ts b/apps/mobile/src/update/androidInstallSource.test.ts
new file mode 100644
index 0000000000..10c08a54a6
--- /dev/null
+++ b/apps/mobile/src/update/androidInstallSource.test.ts
@@ -0,0 +1,35 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ platform: { OS: 'android' },
+ installerPackageName: vi.fn<() => string | null>(),
+}));
+
+vi.mock('react-native', () => ({ Platform: mocks.platform }));
+vi.mock('expo-modules-core', () => ({
+ requireOptionalNativeModule: () => ({ installerPackageName: mocks.installerPackageName }),
+}));
+
+import { isGooglePlayInstallation } from './androidInstallSource';
+
+beforeEach(() => {
+ mocks.installerPackageName.mockReset();
+});
+
+describe('Android install source', () => {
+ it('recognizes Google Play as the installer', () => {
+ mocks.installerPackageName.mockReturnValue('com.android.vending');
+ expect(isGooglePlayInstallation()).toBe(true);
+ });
+
+ it.each([null, 'com.google.android.packageinstaller', 'com.android.packageinstaller'])
+ ('keeps APK distribution for installer %s', (installer) => {
+ mocks.installerPackageName.mockReturnValue(installer);
+ expect(isGooglePlayInstallation()).toBe(false);
+ });
+
+ it('keeps old binaries without the new native query usable', () => {
+ mocks.installerPackageName.mockImplementation(() => { throw new Error('Unavailable'); });
+ expect(isGooglePlayInstallation()).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/update/androidInstallSource.ts b/apps/mobile/src/update/androidInstallSource.ts
new file mode 100644
index 0000000000..3500544a4e
--- /dev/null
+++ b/apps/mobile/src/update/androidInstallSource.ts
@@ -0,0 +1,19 @@
+import { Platform } from 'react-native';
+import { requireOptionalNativeModule } from 'expo-modules-core';
+
+interface NativeInstallSource {
+ /** Absent on binaries released before the Play routing fix. */
+ installerPackageName?: () => string | null;
+}
+
+const native = Platform.OS === 'android'
+ ? requireOptionalNativeModule<NativeInstallSource>('CindyAppInstaller') : null;
+
+/** Read the installed package's source, rather than a value mutable by JS OTA. */
+export function isGooglePlayInstallation(): boolean {
+ try {
+ return native?.installerPackageName?.() === 'com.android.vending';
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/mobile/src/update/bundleInstallRouting.test.ts b/apps/mobile/src/update/bundleInstallRouting.test.ts
index 6fc7667904..658250f2cc 100644
--- a/apps/mobile/src/update/bundleInstallRouting.test.ts
+++ b/apps/mobile/src/update/bundleInstallRouting.test.ts
@@ -5,17 +5,20 @@ const mocks = vi.hoisted(() => ({
openURL: vi.fn(async () => undefined),
start: vi.fn(() => true),
forced: vi.fn(),
+ playInstall: vi.fn(() => false),
}));
vi.mock('react-native', () => ({ Alert: { alert: mocks.alert }, Linking: { openURL: mocks.openURL }, Platform: mocks.platform }));
+vi.mock('expo-application', () => ({ applicationId: 'com.xd.cindy' }));
vi.mock('expo-updates', () => ({}));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('@/config/env', () => ({ APP_BINARY_VERSION: '1.0.0', IS_OTA_SELFHOST: true, IS_TESTFLIGHT_BUILD: false, REVIEW_MODE: false }));
vi.mock('./androidInstaller', () => ({ androidInstaller: { start: mocks.start } }));
+vi.mock('./androidInstallSource', () => ({ isGooglePlayInstallation: mocks.playInstall }));
vi.mock('./forcedUpdateStore', () => ({ enterForcedUpdate: mocks.forced }));
vi.mock('./canaryChannelStore', () => ({ resolveUpdateChannelForDevice: () => 'release' }));
import { openBundleInstall, promptBundleUpdate } from './useBundleUpdatePrompt';
const target = { version: '1.2.3', runtimeVersion: 'new', installUrl: 'https://updates.example.invalid/app.apk', itmsUrl: '' };
-beforeEach(() => { vi.clearAllMocks(); mocks.platform.OS = 'android'; mocks.start.mockReturnValue(true); });
+beforeEach(() => { vi.clearAllMocks(); mocks.platform.OS = 'android'; mocks.start.mockReturnValue(true); mocks.playInstall.mockReturnValue(false); });
describe('shared bundle install routing', () => {
it('ordinary update confirmation starts the same native path as the forced gate', () => {
@@ -39,6 +42,19 @@ describe('shared bundle install routing', () => {
openBundleInstall(target);
expect(mocks.openURL).toHaveBeenCalledWith(target.installUrl);
});
+ it('Google Play installs open their store listing without downloading the website APK', async () => {
+ mocks.playInstall.mockReturnValue(true);
+ openBundleInstall(target);
+ expect(mocks.start).not.toHaveBeenCalled();
+ expect(mocks.openURL).toHaveBeenCalledWith('market://details?id=com.xd.cindy');
+ });
+ it('Google Play listing falls back to its HTTPS page when the market scheme fails', async () => {
+ mocks.playInstall.mockReturnValue(true);
+ mocks.openURL.mockRejectedValueOnce(new Error('No market handler'));
+ openBundleInstall(target);
+ await vi.waitFor(() => expect(mocks.openURL).toHaveBeenCalledWith('https://play.google.com/store/apps/details?id=com.xd.cindy'));
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
it('iOS continues to use its original installation scheme', () => {
mocks.platform.OS = 'ios';
openBundleInstall({ ...target, itmsUrl: 'itms-services://?action=download-manifest' });
diff --git a/apps/mobile/src/update/bundleUpdate.test.ts b/apps/mobile/src/update/bundleUpdate.test.ts
index 26eab0fe9d..3b8fc75025 100644
--- a/apps/mobile/src/update/bundleUpdate.test.ts
+++ b/apps/mobile/src/update/bundleUpdate.test.ts
@@ -39,9 +39,19 @@ describe('shouldCheckBundleUpdate', () => {
isSelfHosted,
isReviewMode,
isTestFlightBuild,
+ isGooglePlayInstallation: false,
})).toBe(expected);
},
);
+
+ it('Google Play 安装跳过官网 APK 整包记录', () => {
+ expect(shouldCheckBundleUpdate({
+ isSelfHosted: true,
+ isReviewMode: false,
+ isTestFlightBuild: false,
+ isGooglePlayInstallation: true,
+ })).toBe(false);
+ });
});
describe('parseLatestRelease', () => {
diff --git a/apps/mobile/src/update/bundleUpdate.ts b/apps/mobile/src/update/bundleUpdate.ts
index c8f1dbfe6a..89522dc9b9 100644
--- a/apps/mobile/src/update/bundleUpdate.ts
+++ b/apps/mobile/src/update/bundleUpdate.ts
@@ -48,7 +48,8 @@ export interface EvaluateBundleUpdateInput {
const NO_UPDATE: BundleUpdateEvaluation = { needsUpdate: false, forced: false, target: null };
/**
- * 整包更新只属于自建分发渠道。
+ * 官网整包记录只属于自建安装渠道。Google Play 安装由 Play 管理原生包更新;
+ * 两种 Android 产物共用自建 OTA 配置,不能只用 isSelfHosted 区分。
* Review 构建与 TestFlight 构建都不能展示外部安装入口;
* TestFlight 的 JS OTA 由独立通道继续处理。
*/
@@ -56,12 +57,14 @@ export function shouldCheckBundleUpdate({
isSelfHosted,
isReviewMode,
isTestFlightBuild,
+ isGooglePlayInstallation,
}: {
isSelfHosted: boolean;
isReviewMode: boolean;
isTestFlightBuild: boolean;
+ isGooglePlayInstallation: boolean;
}): boolean {
- return isSelfHosted && !isReviewMode && !isTestFlightBuild;
+ return isSelfHosted && !isReviewMode && !isTestFlightBuild && !isGooglePlayInstallation;
}
export function isSupportedBundleVersion(version: string): boolean {
diff --git a/apps/mobile/src/update/manualUpdateCheck.test.ts b/apps/mobile/src/update/manualUpdateCheck.test.ts
index 266293426d..1babb94e26 100644
--- a/apps/mobile/src/update/manualUpdateCheck.test.ts
+++ b/apps/mobile/src/update/manualUpdateCheck.test.ts
@@ -198,6 +198,15 @@ describe('runManualUpdateCheck', () => {
});
describe('manualUpdateCheckMessage', () => {
+ it('does not claim the Google Play app package is current after checking only content updates', async () => {
+ await i18n.changeLanguage('zh-CN');
+ const options = { isTestFlightBuild: false, isGooglePlayInstallation: true, t: i18n.t };
+ expect(manualUpdateCheckMessage({ kind: 'up-to-date' }, options))
+ .toBe('当前没有可用的内容更新。新应用版本请在 Google Play 中查看。');
+ expect(manualUpdateCheckMessage({ kind: 'ota-unavailable' }, options))
+ .toBe('当前构建无法检查内容更新。新应用版本请在 Google Play 中查看。');
+ });
+
it('tells the user to fully reopen the app when reload was rejected', async () => {
await i18n.changeLanguage('zh-CN');
expect(manualUpdateCheckMessage({ kind: 'restart-required' }, { isTestFlightBuild: false, t: i18n.t }))
diff --git a/apps/mobile/src/update/manualUpdateCheck.ts b/apps/mobile/src/update/manualUpdateCheck.ts
index 1049a50ab9..99e807fe62 100644
--- a/apps/mobile/src/update/manualUpdateCheck.ts
+++ b/apps/mobile/src/update/manualUpdateCheck.ts
@@ -127,20 +127,24 @@ export async function runManualUpdateCheck({
*/
export function manualUpdateCheckMessage(
outcome: ManualUpdateCheckOutcome,
- options: { isTestFlightBuild: boolean; t: TFunction },
+ options: { isTestFlightBuild: boolean; isGooglePlayInstallation?: boolean; t: TFunction },
): string | null {
- const { isTestFlightBuild, t } = options;
+ const { isTestFlightBuild, isGooglePlayInstallation, t } = options;
switch (outcome.kind) {
case 'bundle-update-available':
return t('settings.version.bundleUpdateFound');
case 'up-to-date':
return t(isTestFlightBuild
? 'settings.version.testFlightNoContentUpdate'
- : 'settings.version.upToDate');
+ : isGooglePlayInstallation
+ ? 'settings.version.googlePlayNoContentUpdate'
+ : 'settings.version.upToDate');
case 'ota-unavailable':
return t(isTestFlightBuild
? 'settings.version.testFlightContentUpdateUnavailable'
- : 'settings.version.bundleUpToDateNoOta');
+ : isGooglePlayInstallation
+ ? 'settings.version.googlePlayContentUpdateUnavailable'
+ : 'settings.version.bundleUpToDateNoOta');
case 'reloading':
return t('settings.version.downloadedRestarting');
case 'restart-required':
diff --git a/apps/mobile/src/update/playUpdateEntries.test.ts b/apps/mobile/src/update/playUpdateEntries.test.ts
new file mode 100644
index 0000000000..6859236879
--- /dev/null
+++ b/apps/mobile/src/update/playUpdateEntries.test.ts
@@ -0,0 +1,118 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ playInstall: vi.fn(() => true),
+ fetchLatest: vi.fn(async () => null),
+ checkOta: vi.fn(async () => ({ isAvailable: false })),
+ fetchOta: vi.fn(async () => ({ isNew: false })),
+ appStateListener: null as ((state: string) => void) | null,
+ cleanup: null as (() => void) | null,
+}));
+
+// Exercise the update hooks' real effects and callbacks without rendering the full app.
+vi.mock('react', () => ({
+ useCallback: (callback: unknown) => callback,
+ useRef: (value: unknown) => ({ current: value }),
+ useState: (value: unknown) => [value, vi.fn()],
+ useEffect: (effect: () => void | (() => void)) => {
+ const cleanup = effect();
+ mocks.cleanup = typeof cleanup === 'function' ? cleanup : null;
+ },
+}));
+vi.mock('react-native', () => ({
+ Platform: { OS: 'android' },
+ Alert: { alert: vi.fn() },
+ Linking: { openURL: vi.fn() },
+ AppState: {
+ addEventListener: vi.fn((_event: string, listener: (state: string) => void) => {
+ mocks.appStateListener = listener;
+ return { remove: vi.fn() };
+ }),
+ },
+}));
+vi.mock('expo-updates', () => ({
+ isEnabled: true,
+ runtimeVersion: 'runtime-1',
+ checkForUpdateAsync: mocks.checkOta,
+ fetchUpdateAsync: mocks.fetchOta,
+}));
+vi.mock('@/config/env', () => ({
+ APP_BINARY_VERSION: '1.0.0',
+ IS_OTA_SELFHOST: true,
+ IS_TESTFLIGHT_BUILD: false,
+ REVIEW_MODE: false,
+}));
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+vi.mock('./androidInstallSource', () => ({ isGooglePlayInstallation: mocks.playInstall }));
+vi.mock('./androidInstaller', () => ({ androidInstaller: { start: vi.fn() } }));
+vi.mock('./fetchLatestRelease', () => ({ fetchLatestRelease: mocks.fetchLatest }));
+vi.mock('./forcedUpdateStore', () => ({ enterForcedUpdate: vi.fn() }));
+vi.mock('./canaryChannelStore', () => ({ resolveUpdateChannelForDevice: () => 'release' }));
+vi.mock('./otaRequestCoordinator', () => ({
+ runSelfHostedOtaRequest: (_channel: string, operation: (client: {
+ checkForUpdateAsync: typeof mocks.checkOta;
+ fetchUpdateAsync: typeof mocks.fetchOta;
+ }) => Promise<unknown>) => operation({
+ checkForUpdateAsync: mocks.checkOta,
+ fetchUpdateAsync: mocks.fetchOta,
+ }),
+}));
+
+import { useBundleUpdatePrompt } from './useBundleUpdatePrompt';
+import { useResumeUpdateCheck } from './useResumeUpdateCheck';
+import { runManualUpdateCheck } from './manualUpdateCheck';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.playInstall.mockReturnValue(true);
+ mocks.appStateListener = null;
+ mocks.cleanup = null;
+});
+
+afterEach(() => {
+ mocks.cleanup?.();
+ vi.restoreAllMocks();
+});
+
+describe('Google Play update entry points', () => {
+ it('startup hook skips the website release check', async () => {
+ const { checkNow } = useBundleUpdatePrompt({ auto: true, channel: 'release' });
+ await expect(checkNow()).resolves.toBe('skipped');
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ // The root layout still mounts its independent startup content OTA gate.
+ const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');
+ expect(layout).toContain('const otaReady = useStartupOtaGate(channel);');
+ });
+
+ it('resume checks content OTA but never asks for the website APK', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValue(300_001);
+ useResumeUpdateCheck('release');
+ expect(mocks.appStateListener).not.toBeNull();
+ mocks.appStateListener!('background');
+ mocks.appStateListener!('active');
+ await vi.waitFor(() => expect(mocks.checkOta).toHaveBeenCalledOnce());
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ now.mockRestore();
+ });
+
+ it('settings passes no website check and can still check content OTA', async () => {
+ const settings = readFileSync(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');
+ expect(settings).toContain('isGooglePlayInstallation: playManagedUpdates,');
+ expect(settings).toContain('checkBundleUpdate: bundleCheckEnabled ? checkBundleUpdate : undefined,');
+ expect(settings).toContain('const updateCheckEnabled = bundleCheckEnabled || updatesEnabled;');
+ expect(settings).toContain("? 'settings.version.googlePlayContentUpdateUnavailable'");
+ await expect(runManualUpdateCheck({
+ checkBundleUpdate: undefined,
+ otaEnabled: true,
+ checkOtaUpdate: mocks.checkOta,
+ fetchOtaUpdate: mocks.fetchOta,
+ reload: vi.fn(async () => undefined),
+ isEmergencyLaunch: () => false,
+ onPhase: vi.fn(),
+ })).resolves.toEqual({ kind: 'up-to-date' });
+ expect(mocks.checkOta).toHaveBeenCalledOnce();
+ expect(mocks.fetchLatest).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/update/useBundleUpdatePrompt.ts b/apps/mobile/src/update/useBundleUpdatePrompt.ts
index 6b38898d73..1627ecbdf6 100644
--- a/apps/mobile/src/update/useBundleUpdatePrompt.ts
+++ b/apps/mobile/src/update/useBundleUpdatePrompt.ts
@@ -7,6 +7,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert, Linking, Platform } from 'react-native';
+import * as Application from 'expo-application';
import * as Updates from 'expo-updates';
import { i18n } from '@/i18n';
import {
@@ -17,6 +18,7 @@ import {
} from '@/config/env';
import { fetchLatestRelease } from './fetchLatestRelease';
import { androidInstaller } from './androidInstaller';
+import { isGooglePlayInstallation } from './androidInstallSource';
import {
evaluateBundleUpdate,
preferredInstallUrl,
@@ -56,8 +58,23 @@ async function openInstall(url: string): Promise<void> {
}
}
+async function openGooglePlay(packageName: string): Promise<void> {
+ const id = encodeURIComponent(packageName);
+ try {
+ await Linking.openURL(`market://details?id=${id}`);
+ } catch {
+ await openInstall(`https://play.google.com/store/apps/details?id=${id}`);
+ }
+}
+
/** 普通更新与强更共用的安装出口;旧 Android 包及网页地址保留浏览器回退。 */
export function openBundleInstall(target: { version?: string; itmsUrl?: string; installUrl?: string }): void {
+ if (Platform.OS === 'android' && isGooglePlayInstallation()) {
+ // A stale forced-update target must never hand a Play install to the APK installer.
+ const packageName = Application.applicationId;
+ if (packageName) void openGooglePlay(packageName);
+ return;
+ }
if (Platform.OS === 'android' && target.version && target.installUrl
&& androidInstaller.start({ version: target.version, installUrl: target.installUrl })) return;
const url = preferredInstallUrl(target);
@@ -104,6 +121,7 @@ export function useBundleUpdatePrompt({
isSelfHosted: IS_OTA_SELFHOST,
isReviewMode: REVIEW_MODE,
isTestFlightBuild: IS_TESTFLIGHT_BUILD,
+ isGooglePlayInstallation: isGooglePlayInstallation(),
});
const inFlightChannels = useRef(new Set<UpdateChannel>());
const channelEpochRef = useRef(0);
diff --git a/apps/mobile/src/update/useResumeUpdateCheck.ts b/apps/mobile/src/update/useResumeUpdateCheck.ts
index 9da2467b46..07f2f041c4 100644
--- a/apps/mobile/src/update/useResumeUpdateCheck.ts
+++ b/apps/mobile/src/update/useResumeUpdateCheck.ts
@@ -15,6 +15,7 @@ import {
REVIEW_MODE,
} from '@/config/env';
import { shouldCheckBundleUpdate } from './bundleUpdate';
+import { isGooglePlayInstallation } from './androidInstallSource';
import { fetchLatestRelease } from './fetchLatestRelease';
import { createResumeUpdateChecker } from './resumeUpdateCheck';
import { promptBundleUpdate } from './useBundleUpdatePrompt';
@@ -29,6 +30,7 @@ export function useResumeUpdateCheck(
isSelfHosted: IS_OTA_SELFHOST,
isReviewMode: REVIEW_MODE,
isTestFlightBuild: IS_TESTFLIGHT_BUILD,
+ isGooglePlayInstallation: isGooglePlayInstallation(),
});
useEffect(() => {
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index da5861f184..dbe9c43159 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -216,7 +216,17 @@ Mobile 用 `runtimeVersion.policy: "fingerprint"`:OTA 热更只在**指纹一致
启动检查、设置页与强制更新屏共用 `src/update/useBundleUpdatePrompt.ts` 的安装出口。
Android 8 及以上的新原生包优先应用内下载 HTTPS APK;Android 7、旧包缺少
-`CindyAppInstaller`,或安装地址是网页时,继续使用浏览器。权限只由自建构建的 `app.config.js` 声明,商店构建不声明。
+`CindyAppInstaller`,或安装地址是网页时,继续使用浏览器。权限由自建构建的
+`app.config.js` 声明;同流程生成的官网 APK 和 Google Play AAB 当前共享这一原生配置,
+EAS 商店构建不声明。
+
+Global 自建 APK 与 Google Play AAB 共用自建 OTA 配置和原生构建流程,不能仅凭
+`IS_OTA_SELFHOST` 判断整包更新渠道。Android 原生安装桥读取系统记录的 installer:
+Google Play 安装跳过官网 `/latest` APK 整包提示,由 Google Play 管理原生包更新;
+JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。遗留强更目标的安装按钮也
+只能打开该应用在 Google Play 的页面。官网 APK 安装继续使用下述应用内更新流程。
+这项原生查询改变 Android runtime fingerprint,旧 Play 包必须经一次 Play 冷更后才具备
+可靠的安装来源识别能力;不能把 JS OTA 当作旧包已经修复。
- 已授权直接下载;未授权先显示说明与「去授权 / 浏览器下载 / 稍后」,用户点「去授权」
才打开系统设置。返回后读取实际权限;拒绝不会循环申请,可选择浏览器下载。