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。

feat(mobile): 强更从"不可取消弹窗"改为阻断式闸门

guyong34aa79c3b563
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 43d53c9e0e..e8f4382902 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -8,6 +8,7 @@ import {
} from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { useCallback, useEffect, useMemo, useRef, type ReactElement } from 'react';
+import { useTranslation } from 'react-i18next';
import { Alert, AppState, Platform, Pressable, StyleSheet, View } from 'react-native';
import { Text } from '@/components/AppText';
import {
@@ -46,7 +47,14 @@ import {
import { registerDevCacheMenu } from '@/debug/devCacheMenu';
import { startJsStallWatchdog } from '@/debug/jsStallWatchdog';
import { initMobileTapdb } from '@/analytics/mobileTapdb';
-import { useBundleUpdatePrompt } from '@/update/useBundleUpdatePrompt';
+import {
+ openBundleInstall,
+ useBundleUpdatePrompt,
+} from '@/update/useBundleUpdatePrompt';
+import {
+ useForcedUpdate,
+ type ForcedUpdateTarget,
+} from '@/update/forcedUpdateStore';
import { useResumeUpdateCheck } from '@/update/useResumeUpdateCheck';
import {
markStartupOtaLaunchSuccess,
@@ -356,6 +364,9 @@ function RootLayout() {
// 回写 env live binding。拉不到 / 清单非法 → 错误屏等用户重试,无缓存与超时兜底;
// __DEV__ 直接放行。ready 前 RootAfterEndpoints(含 OTA 门与业务树)不挂载。
const endpointGate = useStartupEndpointGate();
+ // 强更阻断态(自建线整包更新命中 minVersion 门槛):模块级 store,启动检查 / 设置页手动
+ // 检查 / resume 静默检查三条路径中任一命中即置位。置位后整棵业务树不挂载。
+ const forcedUpdate = useForcedUpdate();
// 所有 hook 已在上方调用,下面条件返回不违反 hooks 规则。
// GestureHandlerRootView 必须在根部常驻(RNGH 官方要求;缺失时 Android 手势整体不响应)。
// 各分支都包同一层,避免闸门状态切换时 root 重挂。
@@ -371,11 +382,21 @@ function RootLayout() {
'{reason}',
endpointGate.reason ?? 'unknown',
)}
- retryLabel={loginText('retry')}
- onRetry={endpointGate.retry}
+ actionLabel={loginText('retry')}
+ onAction={endpointGate.retry}
/>
</MobileLoginHandoffStage>
);
+ } else if (forcedUpdate) {
+ // 强更闸门:与端点错误屏同一套阻断体系(白底品牌宿主 + 唯一出口),没有"稍后 / 跳过"
+ // ——点「去更新」跳出去安装,回到 App 仍是这一屏,直到装上不低于门槛的版本。
+ // 业务树整体不挂载,含 AuthProvider / DeviceLinkProvider / 预创建 worktree 恢复桥:
+ // 强更期间不该发起任何 Device Link 调用;恢复账本是持久化的,阻断解除后下次启动照常补偿。
+ body = (
+ <MobileLoginHandoffStage>
+ <ForcedUpdateGateContent target={forcedUpdate} />
+ </MobileLoginHandoffStage>
+ );
} else if (endpointGate.status === 'pending') {
// pending 期间由 StartupSplashOverlay 顶着,不渲染业务内容。
body = null;
@@ -391,8 +412,11 @@ function RootLayout() {
{/* handoff Provider 常驻 root(PR4b):闸门屏切换不重置衔接状态机 */}
<MobileLoginHandoffProvider>
<EndpointHandoffBridge status={endpointGate.status} />
- {/* 启动闸门全程共用这一个 splash 实例;端点错误屏需要交互时才隐藏它 */}
- <StartupSplashOverlay hidden={endpointGate.status === 'error'}>
+ {/* 启动闸门全程共用这一个 splash 实例;需要用户交互的闸门屏
+ (端点错误 / 强更阻断)才隐藏它 */}
+ <StartupSplashOverlay
+ hidden={endpointGate.status === 'error' || forcedUpdate !== null}
+ >
{body}
</StartupSplashOverlay>
</MobileLoginHandoffProvider>
@@ -404,21 +428,22 @@ function RootLayout() {
}
/**
- * 端点闸门阻断内容层(StartupBlockedScreen 的白底体系消费变体,PR4a):
+ * 启动闸门阻断内容层(StartupBlockedScreen 的白底体系消费变体,PR4a):
* 品牌视觉由 MobileLoginHandoffStage 宿主拥有,本层背景透明、内容沉到下半屏
- * (避开品牌三要素),仅承载标题/原因/重试。文案 key 化契约不变
- * (endpointGateTitle / endpointGateSubtitle{reason} / retry)。
+ * (避开品牌三要素),仅承载标题/说明/唯一动作。端点闸门与强更闸门共用本层
+ * ——阻断语义一致:没有"跳过 / 稍后再说",只有一个出口。端点错误屏的文案 key 化
+ * 契约不变(endpointGateTitle / endpointGateSubtitle{reason} / retry)。
*/
function StartupGateBlockedContent({
title,
subtitle,
- retryLabel,
- onRetry,
+ actionLabel,
+ onAction,
}: {
title: string;
subtitle?: string;
- retryLabel: string;
- onRetry: () => void;
+ actionLabel: string;
+ onAction: () => void;
}) {
const gateStyles = useThemedStyles(makeGateStyles);
return (
@@ -427,18 +452,41 @@ function StartupGateBlockedContent({
{subtitle ? <Text style={gateStyles.subtitle}>{subtitle}</Text> : null}
<Pressable
accessibilityRole="button"
- onPress={onRetry}
+ onPress={onAction}
style={({ pressed }) => [
gateStyles.retryButton,
pressed && gateStyles.retryButtonPressed,
]}
>
- <Text style={gateStyles.retryLabel}>{retryLabel}</Text>
+ <Text style={gateStyles.retryLabel}>{actionLabel}</Text>
</Pressable>
</View>
);
}
+/**
+ * 强更闸门内容层:命中 minVersion 门槛时的阻断屏,唯一出口是「去更新」
+ * (iOS 跳 itms-services / App Store,Android 跳应用商店或 APK 直下)。
+ * 复用既有 update.* 文案(forcedTitle / bundleAvailableBody / releaseNotes / goUpdate),
+ * 不新增术语;t() 在此消费,保证语言切换即时生效。
+ */
+function ForcedUpdateGateContent({ target }: { target: ForcedUpdateTarget }) {
+ const { t } = useTranslation();
+ const notes = target.releaseNotes?.trim();
+ const subtitle = [
+ t('update.bundleAvailableBody'),
+ notes ? t('update.releaseNotes', { notes }) : '',
+ ].join('');
+ return (
+ <StartupGateBlockedContent
+ title={t('update.forcedTitle')}
+ subtitle={subtitle}
+ actionLabel={t('update.goUpdate')}
+ onAction={() => openBundleInstall(target)}
+ />
+ );
+}
+
const makeGateStyles = (colors: ThemeColors) =>
StyleSheet.create({
root: {
diff --git a/apps/mobile/src/__tests__/forcedUpdateGate.test.ts b/apps/mobile/src/__tests__/forcedUpdateGate.test.ts
new file mode 100644
index 0000000000..8320b05c29
--- /dev/null
+++ b/apps/mobile/src/__tests__/forcedUpdateGate.test.ts
@@ -0,0 +1,53 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * 强更阻断契约(读源码断言)。
+ *
+ * 回归背景:强更曾经是一个 `cancelable: false` 的单按钮 Alert —— 但 RN Alert 的按钮
+ * 点一下就关(cancelable 只挡点外部 / 返回键),弹窗消失后底下的 App 照旧可用,且模块级
+ * 去重让本进程内不再弹。那是"强提醒"而非"强制"。现在强更必须是 root 层的阻断屏:
+ * 命中门槛就不挂业务树。
+ */
+describe('强更阻断闸门', () => {
+ const read = (rel: string) =>
+ readFileSync(resolve(process.cwd(), rel), 'utf8').replace(/\r\n/g, '\n');
+
+ it('root layout 用 forcedUpdate 状态阻断业务树,唯一出口是「去更新」', () => {
+ const layout = read('app/_layout.tsx');
+
+ expect(layout).toContain("from '@/update/forcedUpdateStore'");
+ expect(layout).toContain('const forcedUpdate = useForcedUpdate();');
+ // 阻断分支必须先于 ready 分支(ready 才会挂 RootAfterEndpoints 业务树)。
+ expect(layout.indexOf('} else if (forcedUpdate) {')).toBeGreaterThan(0);
+ expect(layout.indexOf('} else if (forcedUpdate) {')).toBeLessThan(
+ layout.indexOf('body = <RootAfterEndpoints />;'),
+ );
+ expect(layout).toContain('<ForcedUpdateGateContent target={forcedUpdate} />');
+ expect(layout).toContain("actionLabel={t('update.goUpdate')}");
+ // 阻断屏不得有"稍后 / 跳过"出口。
+ expect(layout).not.toContain('update.later');
+ });
+
+ it('强更路径不再走 Alert:promptBundleUpdate 直接进入阻断态', () => {
+ const prompt = read('src/update/useBundleUpdatePrompt.ts');
+
+ expect(prompt).toContain('enterForcedUpdate(evaluation.target)');
+ // 不可取消弹窗是被替换掉的旧实现,不允许回归(匹配 Alert 的 options 对象写法,
+ // 不误伤注释里解释这段历史的文字)。
+ expect(prompt).not.toContain('{ cancelable:');
+ expect(prompt).not.toContain("i18n.t('update.forcedTitle')");
+ // 拿不到安装地址时不得进入阻断态(否则把用户关进没有出口的屏)。
+ expect(prompt).toContain('if (!url) return;');
+ });
+
+ it('阻断态只存内存,不持久化(服务端撤回门槛后用户不能被本地缓存锁死)', () => {
+ const store = read('src/update/forcedUpdateStore.ts');
+
+ // 与 otaReloadGuard 的关键区别:那是防故障循环、必须落盘计数并自带放弃条件;
+ // 这是产品意图的阻断,不落盘本身就是自愈路径。
+ expect(store).not.toContain('AsyncStorage');
+ expect(store).toContain('export function enterForcedUpdate');
+ });
+});
diff --git a/apps/mobile/src/__tests__/startupSplashOverlay.test.ts b/apps/mobile/src/__tests__/startupSplashOverlay.test.ts
index f4af260c19..1eb8235aec 100644
--- a/apps/mobile/src/__tests__/startupSplashOverlay.test.ts
+++ b/apps/mobile/src/__tests__/startupSplashOverlay.test.ts
@@ -21,9 +21,11 @@ describe("startup splash overlay", () => {
const layout = read("app/_layout.tsx");
expect(layout).toContain("from '@/components/StartupSplashOverlay'");
- expect(layout).toContain(
- "<StartupSplashOverlay hidden={endpointGate.status === 'error'}>",
- );
+ // 常驻实例只能有一个;需要用户交互的闸门屏才隐藏它(端点错误 / 强更阻断)。
+ // 这里不锁死整个表达式字面量,避免后续增删闸门时连带改断言。
+ expect(layout.match(/<StartupSplashOverlay/g)).toHaveLength(1);
+ expect(layout).toMatch(/hidden=\{endpointGate\.status === 'error'/);
+ expect(layout).toMatch(/hidden=\{[^}]*forcedUpdate !== null\}/);
// 闸门链各关不许再各自渲染 splash 实例(splash-preview 路由是唯一例外)。
expect(layout).not.toContain('variant="splash"');
});
diff --git a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts b/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts
index 11f7934895..58a8825489 100644
--- a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts
@@ -214,7 +214,9 @@ describe('loginHandoff 接线(Provider/reporter 拓扑 + 清理,读源码断言)
it('gate 屏内容层退化:endpoint error 层可交互 retry(错误层文案 key 化不变)', () => {
expect(layoutSource).toContain('<MobileLoginHandoffStage>');
- expect(layoutSource).toContain('onRetry={endpointGate.retry}');
+ // 内容层的动作 prop 已从 retry 专用改为通用 action(端点重试 / 强更去更新共用同一层),
+ // 端点错误屏的接线与文案 key 化契约不变。
+ expect(layoutSource).toContain('onAction={endpointGate.retry}');
expect(layoutSource).toContain("loginText('endpointGateTitle')");
});
diff --git a/apps/mobile/src/update/bundleUpdate.test.ts b/apps/mobile/src/update/bundleUpdate.test.ts
index 10c2f22aad..c78c88b0b4 100644
--- a/apps/mobile/src/update/bundleUpdate.test.ts
+++ b/apps/mobile/src/update/bundleUpdate.test.ts
@@ -88,6 +88,40 @@ describe('evaluateBundleUpdate', () => {
expect(r.forced).toBe(false);
});
+ it('runtimeVersion 相同但低于 minVersion → 仍然强更(门槛不经指纹门闸)', () => {
+ // 服务端可以对某个已发布版本事后下发门槛;此时装机指纹与 /latest 一致,但 version
+ // 低于门槛 —— 必须命中强更,否则发布链写了 minVersion 也拦不住同指纹的旧构建。
+ const r = evaluateBundleUpdate({
+ currentRuntimeVersion: 'rtv-new',
+ currentVersion: '1.0.0',
+ latest: { ...VALID, minVersion: '1.2.0' },
+ });
+ expect(r.needsUpdate).toBe(true);
+ expect(r.forced).toBe(true);
+ // 同指纹强更时 target.runtimeVersion 就等于当前值,消费方不得据此判断"换了指纹"。
+ expect(r.target?.runtimeVersion).toBe('rtv-new');
+ });
+
+ it('runtimeVersion 相同且不低于 minVersion → 无更新', () => {
+ const r = evaluateBundleUpdate({
+ currentRuntimeVersion: 'rtv-new',
+ currentVersion: '1.2.0',
+ latest: { ...VALID, minVersion: '1.2.0' },
+ });
+ expect(r.needsUpdate).toBe(false);
+ expect(r.target).toBeNull();
+ });
+
+ it('缺 currentVersion → 不强更(无法比较,fail-open)', () => {
+ const r = evaluateBundleUpdate({
+ currentRuntimeVersion: 'rtv-new',
+ currentVersion: null,
+ latest: { ...VALID, minVersion: '1.2.0' },
+ });
+ expect(r.needsUpdate).toBe(false);
+ expect(r.forced).toBe(false);
+ });
+
it('拿不到当前 runtimeVersion(dev / 未启用)→ 无更新', () => {
expect(evaluateBundleUpdate({ currentRuntimeVersion: null, currentVersion: '1.0.0', latest: VALID }).needsUpdate).toBe(false);
expect(evaluateBundleUpdate({ currentRuntimeVersion: '', currentVersion: '1.0.0', latest: VALID }).needsUpdate).toBe(false);
diff --git a/apps/mobile/src/update/bundleUpdate.ts b/apps/mobile/src/update/bundleUpdate.ts
index faf50dcb49..3bd688bf7c 100644
--- a/apps/mobile/src/update/bundleUpdate.ts
+++ b/apps/mobile/src/update/bundleUpdate.ts
@@ -6,6 +6,8 @@
// · latest.runtimeVersion === 当前 runtimeVersion → 无需整包(JS OTA 通道会处理);
// · 不同 → 原生层变了,JS OTA 覆盖不到 → 引导用户打开 release record 的正常安装入口。
// - minVersion(可选)用于强制更新:当前 version 低于它则阻断使用、只留"去更新"。
+// 强更判定**不经过 runtimeVersion 门闸**:门槛由服务端按 version 下发,同 runtimeVersion
+// 的旧构建也必须能被强更(否则"发布链写了 minVersion 却对同指纹装机无效")。
/** mobile-update-server `/latest` 返回的整包版本记录(release.json 透传)。 */
export interface LatestReleaseRecord {
@@ -98,8 +100,14 @@ export function compareVersions(a: string, b: string): number {
}
/**
- * 判定是否需要引导整包更新。核心信号是 runtimeVersion 不一致。
- * 拿不到当前 runtimeVersion(dev / expo-updates 未启用)或 `/latest` 无效 → 一律视为无更新。
+ * 判定是否需要引导整包更新。两条独立信号:
+ * - runtimeVersion 不一致 → 有整包更新(可跳过的普通提示);
+ * - 当前 version < minVersion → 强更,**与 runtimeVersion 是否一致无关**。
+ * 服务端可以对某个已发布版本事后下发门槛,把同指纹的问题构建也挡住;
+ * 反过来说,同 runtimeVersion 命中强更时 target.runtimeVersion 就等于当前值,
+ * 消费方不得把它当作"换了指纹"的证据。
+ * 拿不到当前 runtimeVersion(dev / expo-updates 未启用)、拿不到当前 version 或
+ * `/latest` 无效 → 一律视为无更新(比不出来就不挡人,fail-open)。
*/
export function evaluateBundleUpdate({
currentRuntimeVersion,
@@ -112,14 +120,14 @@ export function evaluateBundleUpdate({
const current = String(currentRuntimeVersion ?? '').trim();
if (!current) return NO_UPDATE;
- if (record.runtimeVersion === current) return NO_UPDATE;
-
const forced = Boolean(
record.minVersion &&
currentVersion &&
compareVersions(String(currentVersion), record.minVersion) < 0,
);
+ if (!forced && record.runtimeVersion === current) return NO_UPDATE;
+
return {
needsUpdate: true,
forced,
diff --git a/apps/mobile/src/update/forcedUpdateStore.test.ts b/apps/mobile/src/update/forcedUpdateStore.test.ts
new file mode 100644
index 0000000000..76256f8b95
--- /dev/null
+++ b/apps/mobile/src/update/forcedUpdateStore.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ __testing,
+ enterForcedUpdate,
+ getForcedUpdateTarget,
+ subscribeForcedUpdate,
+ type ForcedUpdateTarget,
+} from './forcedUpdateStore';
+
+function target(overrides: Partial<ForcedUpdateTarget> = {}): ForcedUpdateTarget {
+ return {
+ version: '2.0.0',
+ runtimeVersion: 'rtv-new',
+ installUrl: 'https://cdn.example/install',
+ itmsUrl: 'itms-services://?action=download-manifest&url=https://cdn.example/m.plist',
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ __testing.reset();
+});
+
+describe('forcedUpdateStore', () => {
+ it('初始无阻断目标', () => {
+ expect(getForcedUpdateTarget()).toBeNull();
+ });
+
+ it('进入阻断态后可读取目标并通知订阅者', () => {
+ const listener = vi.fn();
+ subscribeForcedUpdate(listener);
+ enterForcedUpdate(target());
+ expect(getForcedUpdateTarget()).toEqual(target());
+ expect(listener).toHaveBeenCalledOnce();
+ });
+
+ it('同一目标重复进入 → 幂等,不重复通知(resume 每 5 分钟命中一次也不会重渲染)', () => {
+ const listener = vi.fn();
+ subscribeForcedUpdate(listener);
+ enterForcedUpdate(target());
+ enterForcedUpdate(target());
+ enterForcedUpdate({ ...target() });
+ expect(listener).toHaveBeenCalledOnce();
+ });
+
+ it('目标变化(更高版本)→ 更新并通知', () => {
+ const listener = vi.fn();
+ subscribeForcedUpdate(listener);
+ enterForcedUpdate(target());
+ enterForcedUpdate(target({ version: '2.1.0' }));
+ expect(getForcedUpdateTarget()?.version).toBe('2.1.0');
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
+ it('取消订阅后不再收到通知', () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeForcedUpdate(listener);
+ unsubscribe();
+ enterForcedUpdate(target());
+ expect(listener).not.toHaveBeenCalled();
+ expect(getForcedUpdateTarget()).not.toBeNull();
+ });
+
+ it('单个订阅者抛错不影响其它订阅者', () => {
+ const bad = vi.fn(() => { throw new Error('boom'); });
+ const good = vi.fn();
+ subscribeForcedUpdate(bad);
+ subscribeForcedUpdate(good);
+ expect(() => enterForcedUpdate(target())).not.toThrow();
+ expect(good).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/mobile/src/update/forcedUpdateStore.ts b/apps/mobile/src/update/forcedUpdateStore.ts
new file mode 100644
index 0000000000..9cfa2a3265
--- /dev/null
+++ b/apps/mobile/src/update/forcedUpdateStore.ts
@@ -0,0 +1,90 @@
+/**
+ * 强更阻断态 —— 模块级单例 + 订阅。
+ *
+ * 强更不是"弹一次提示",而是**阻断使用**:命中门槛后 root 层不再挂载业务树,只渲染
+ * 一个唯一出口是「去更新」的闸门屏(见 app/_layout.tsx)。因此状态不能挂在某个 hook 里
+ * (启动检查、设置页手动检查、resume 静默检查三条路径都能命中),必须放模块级共享。
+ *
+ * **不持久化,只存内存**——这是与 otaReloadGuard 的关键区别,别把两者混为一谈:
+ * - otaReloadGuard 挡的是**故障循环**(bundle 装不上却反复 reload),它必须落盘计数,
+ * 并且必须自带放弃条件(满 2 次就放弃热更直接进 App);
+ * - 本模块是**产品意图**的阻断,不是故障。不落盘本身就是自愈路径:服务端撤回门槛
+ * (发布链 set-mobile-min-version --clear)后,用户下次冷启动即恢复;若落盘,撤回
+ * 就再也救不回被误挡的装机。
+ * 而"杀进程绕过"并不成立:下次启动会重新拉 /latest 并立刻命中同一个门槛。
+ *
+ * 三层保证"不会把人永久挡在门外":
+ * 1. 拉不到 /latest(离线 / 超时 / 5xx)→ 调用方 fail-open,不进入阻断态;
+ * 2. 拿不到可跳转的安装地址 → 不进入阻断态(见 promptBundleUpdate),不造无出口的屏;
+ * 3. 门槛必须 ≤ 该 record 宣告的 version(发布链 assertMinVersionUsable fail closed),
+ * 所以装上被广播的那个版本必然解除阻断。
+ */
+import { useSyncExternalStore } from 'react';
+
+/** 阻断屏需要的目标信息(evaluateBundleUpdate 的 target 子集)。 */
+export interface ForcedUpdateTarget {
+ version: string;
+ runtimeVersion: string;
+ installUrl: string;
+ itmsUrl: string;
+ releaseNotes?: string;
+}
+
+let forcedTarget: ForcedUpdateTarget | null = null;
+const listeners = new Set<() => void>();
+
+function notifyListeners(): void {
+ // 单个订阅者异常不能影响其它订阅者(与 canaryChannelStore 同口径)。
+ for (const listener of [...listeners]) {
+ try {
+ listener();
+ } catch {
+ // ignore listener failures
+ }
+ }
+}
+
+function isSameTarget(a: ForcedUpdateTarget | null, b: ForcedUpdateTarget | null): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return a.version === b.version
+ && a.runtimeVersion === b.runtimeVersion
+ && a.installUrl === b.installUrl
+ && a.itmsUrl === b.itmsUrl
+ && a.releaseNotes === b.releaseNotes;
+}
+
+/**
+ * 进入强更阻断态。幂等:同一目标重复调用不通知订阅者(三条检查路径都可能反复命中,
+ * 尤其 resume 每 5 分钟一次;不做等值判断会引发无意义重渲染)。
+ */
+export function enterForcedUpdate(target: ForcedUpdateTarget): void {
+ if (isSameTarget(forcedTarget, target)) return;
+ forcedTarget = target;
+ notifyListeners();
+}
+
+/** 当前阻断目标;null = 未命中强更。 */
+export function getForcedUpdateTarget(): ForcedUpdateTarget | null {
+ return forcedTarget;
+}
+
+/** 订阅阻断态变化;返回取消订阅函数。 */
+export function subscribeForcedUpdate(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** root 层消费:命中强更时返回目标,用于渲染阻断屏。 */
+export function useForcedUpdate(): ForcedUpdateTarget | null {
+ return useSyncExternalStore(subscribeForcedUpdate, getForcedUpdateTarget, getForcedUpdateTarget);
+}
+
+export const __testing = {
+ reset(): void {
+ forcedTarget = null;
+ listeners.clear();
+ },
+};
diff --git a/apps/mobile/src/update/resumeUpdateCheck.test.ts b/apps/mobile/src/update/resumeUpdateCheck.test.ts
index 58da41304b..5516aaf563 100644
--- a/apps/mobile/src/update/resumeUpdateCheck.test.ts
+++ b/apps/mobile/src/update/resumeUpdateCheck.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createResumeUpdateChecker, markForcedPrompted, resetForcedPromptedForTest, type ResumeUpdateCheckDeps } from './resumeUpdateCheck';
+import { describe, expect, it, vi } from 'vitest';
+import { createResumeUpdateChecker, type ResumeUpdateCheckDeps } from './resumeUpdateCheck';
/** 有效的 /latest 记录(runtimeVersion 与当前 '1' 不同 → 有整包更新)。 */
function latestRecord(overrides: Record<string, unknown> = {}) {
@@ -23,10 +23,8 @@ function makeDeps(overrides: Partial<ResumeUpdateCheckDeps> = {}) {
fetchLatest: vi.fn(async () => null),
getCurrentRuntimeVersion: () => '1',
getCurrentVersion: () => '1.0.0',
- // 模拟真实 callback(promptBundleUpdate)的契约:实际展示后标记去重。
- onForcedUpdate: vi.fn((e: Parameters<ResumeUpdateCheckDeps['onForcedUpdate']>[0]) => {
- if (e.target) markForcedPrompted(e.target.runtimeVersion);
- }),
+ // 真实 callback 是 promptBundleUpdate → enterForcedUpdate(幂等,不需要去重)。
+ onForcedUpdate: vi.fn(),
now: () => nowMs,
advance: (ms: number) => { nowMs += ms; },
...overrides,
@@ -40,10 +38,6 @@ function resume(checker: ReturnType<typeof createResumeUpdateChecker>) {
return checker.handleAppStateChange('active');
}
-afterEach(() => {
- resetForcedPromptedForTest();
-});
-
describe('createResumeUpdateChecker 触发条件', () => {
it('创建后立刻 resume:间隔不足 → 不检查(冷启动刚查过)', () => {
const deps = makeDeps();
@@ -184,30 +178,27 @@ describe('createResumeUpdateChecker 整包路径', () => {
expect(deps.onForcedUpdate).toHaveBeenCalledOnce();
});
- it('同一强更目标多次 resume → 只提示一次(去重)', async () => {
+ it('同一强更目标多次 resume → 每次都上报(阻断态幂等,本层不去重)', async () => {
+ // 去重曾是必需的(强更是一次性 Alert);改成阻断态后 enterForcedUpdate 幂等,
+ // 本层不再持有"已提示过"状态 —— 也就不会因为一次未展示而让强更永久失声。
const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord({ minVersion: '2.0.0' })) });
const checker = createResumeUpdateChecker(deps, { minIntervalMs: 0 });
deps.advance(1);
await resume(checker);
deps.advance(1);
await resume(checker);
- expect(deps.onForcedUpdate).toHaveBeenCalledOnce();
+ expect(deps.onForcedUpdate).toHaveBeenCalledTimes(2);
});
- it('onForcedUpdate 未标记(模拟无 URL 静默失败)→ 下次 resume 重试,不永久失声', async () => {
- // callback 不调 markForcedPrompted,模拟 promptBundleUpdate 因无安装 URL 提前 return。
- const onForcedUpdate = vi.fn();
+ it('同 runtimeVersion 但低于 minVersion → 依旧上报强更', async () => {
+ // 服务端事后给某个已发布版本下发门槛时,装机 runtimeVersion 与 /latest 相同,
+ // 但 version 低于门槛 —— 不能因为"指纹没变"就放过。
const deps = makeDeps({
- fetchLatest: vi.fn(async () => latestRecord({ minVersion: '2.0.0' })),
- onForcedUpdate,
+ fetchLatest: vi.fn(async () => latestRecord({ runtimeVersion: '1', minVersion: '2.0.0' })),
});
- const checker = createResumeUpdateChecker(deps, { minIntervalMs: 0 });
- deps.advance(1);
- await resume(checker);
- deps.advance(1);
- await resume(checker);
- // 未标记 → guard 每次都放行,强更不会因一次未展示而永久失声。
- expect(onForcedUpdate).toHaveBeenCalledTimes(2);
+ const { bundle } = await runOnce(deps);
+ expect(bundle).toBe('forced');
+ expect(deps.onForcedUpdate).toHaveBeenCalledOnce();
});
it('/latest 拉取失败 → error(fail-open),不影响 OTA 结果', async () => {
@@ -217,15 +208,6 @@ describe('createResumeUpdateChecker 整包路径', () => {
expect(ota).toBe('up-to-date');
});
- it('启动路径已标记强更 → resume 不再弹(跨路径去重)', async () => {
- // 模拟启动路径弹过强更:直接调用模块级 markForcedPrompted
- markForcedPrompted('2');
- const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord({ minVersion: '2.0.0' })) });
- const { bundle } = await runOnce(deps);
- expect(bundle).toBe('forced');
- expect(deps.onForcedUpdate).not.toHaveBeenCalled(); // 已标记过,不再回调
- });
-
it('/latest 挂起 → withTimeout backstop 触发 error(fail-open),不影响 OTA', async () => {
// 注入一个永不 resolve 的 fetchLatest:模拟注入实现无内部超时时纯逻辑层的兜底。
const deps = makeDeps({ fetchLatest: vi.fn((): Promise<unknown> => new Promise(() => {})) });
diff --git a/apps/mobile/src/update/resumeUpdateCheck.ts b/apps/mobile/src/update/resumeUpdateCheck.ts
index ff574e4d4d..2ef6c1f71e 100644
--- a/apps/mobile/src/update/resumeUpdateCheck.ts
+++ b/apps/mobile/src/update/resumeUpdateCheck.ts
@@ -5,7 +5,7 @@
// - JS OTA:静默 check → fetch,**绝不 reload**(reload 会闪屏断状态);下载好的 bundle
// 由 expo-updates 在下次冷启动自动生效。
// - 整包(runtimeVersion 变化):静默拉 /latest 比对;唯一允许出 UI 的情况是命中
-// minVersion 强更(强更本身无法无感),且同一目标 runtimeVersion 进程内只回调一次;
+// minVersion 强更(强更本身无法无感),此时上报给 onForcedUpdate 进入阻断态;
// 非强更完全静默(启动路径已有一次性提示,不在每次切回时骚扰)。
// - 节流:只认真正的 background → active(iOS 通知中心/来电导致的 inactive 抖动不算),
// 两次检查最小间隔 minIntervalMs;创建时间视为"刚检查过"(冷启动路径刚跑完,首次
@@ -15,25 +15,9 @@
import { evaluateBundleUpdate, type BundleUpdateEvaluation } from './bundleUpdate';
import { withTimeout } from './startupOtaUpdate';
-// 模块级强更提示去重:同一 runtimeVersion 进程内只弹一次,跨启动路径和 resume 路径共享。
-// 启动路径(useBundleUpdatePrompt)弹强更时调 markForcedPrompted 写入,resume 路径检查前
-// 先查 hasForcedPrompted,避免冷启动已弹过的强更在 5 分钟后 resume 时再弹一次。
-const promptedForcedRuntimes = new Set<string>();
-
-/** 标记某 runtimeVersion 的强更已提示过(启动路径弹窗后调用)。 */
-export function markForcedPrompted(runtimeVersion: string): void {
- promptedForcedRuntimes.add(runtimeVersion);
-}
-
-/** 查询某 runtimeVersion 是否已提示过强更。 */
-export function hasForcedPrompted(runtimeVersion: string): boolean {
- return promptedForcedRuntimes.has(runtimeVersion);
-}
-
-/** 仅供单测重置模块级状态。 */
-export function resetForcedPromptedForTest(): void {
- promptedForcedRuntimes.clear();
-}
+// 强更不再需要"是否已提示过"的去重:它现在是阻断态而不是一次性弹窗,onForcedUpdate
+// (promptBundleUpdate → enterForcedUpdate)对同一目标幂等,重复上报不会产生重复 UI。
+// 反过来说,去重曾经引入过风险:标记了却没展示,强更就对本进程永久失声。
export type ResumeOtaOutcome = 'skipped' | 'up-to-date' | 'fetched' | 'error';
export type ResumeBundleOutcome = 'skipped' | 'up-to-date' | 'update-available' | 'forced' | 'error';
@@ -55,9 +39,9 @@ export interface ResumeUpdateCheckDeps {
getCurrentRuntimeVersion: () => string | null | undefined;
getCurrentVersion: () => string | null | undefined;
/**
- * 强更时的唯一 UI 出口。契约:实现必须在**实际展示**强更提示后调用 markForcedPrompted
- * 标记该 runtimeVersion(见 promptBundleUpdate),本层据此跨路径去重、且只在确认展示后才标记
- * ——若实现因故未展示(如无安装 URL)则不应标记,以便下次 resume 重试。
+ * 强更时的唯一 UI 出口(实参是 promptBundleUpdate → 进入模块级阻断态)。
+ * 契约:实现必须幂等 —— 本层每次命中强更都会上报,不做去重;
+ * 实现因故无法给出出口(如拿不到安装地址)时应自行 no-op,不要留下无出口的阻断屏。
*/
onForcedUpdate: (evaluation: BundleUpdateEvaluation) => void;
now: () => number;
@@ -93,7 +77,7 @@ export interface ResumeUpdateChecker {
handleAppStateChange: (next: string) => Promise<ResumeUpdateOutcome> | null;
}
-/** 创建 resume 检查器(持有节流/在途/已提示状态;一个 App 进程一个实例)。 */
+/** 创建 resume 检查器(持有节流/在途状态;一个 App 进程一个实例)。 */
export function createResumeUpdateChecker(
deps: ResumeUpdateCheckDeps,
{
@@ -136,10 +120,8 @@ export function createResumeUpdateChecker(
});
if (!evaluation.needsUpdate || !evaluation.target) return 'up-to-date';
if (!evaluation.forced) return 'update-available'; // 非强更静默:启动路径已负责提示
- // 去重标记由 onForcedUpdate(promptBundleUpdate)在确认展示弹窗后统一负责,
- // 这里只做 guard、不预先标记,避免"caller 已标记但 callee 未展示"竞态。
if (deps.isCurrent && !deps.isCurrent()) return 'skipped';
- if (!hasForcedPrompted(evaluation.target.runtimeVersion)) deps.onForcedUpdate(evaluation);
+ deps.onForcedUpdate(evaluation); // 幂等,不去重:阻断态重复上报无副作用
return 'forced';
} catch {
return 'error'; // fail-open:连不上更新服务静默放过
diff --git a/apps/mobile/src/update/useBundleUpdatePrompt.ts b/apps/mobile/src/update/useBundleUpdatePrompt.ts
index 95b67db3e5..d041c751a6 100644
--- a/apps/mobile/src/update/useBundleUpdatePrompt.ts
+++ b/apps/mobile/src/update/useBundleUpdatePrompt.ts
@@ -22,7 +22,7 @@ import {
shouldCheckBundleUpdate,
} from './bundleUpdate';
import type { BundleUpdateCheckOutcome } from './manualUpdateCheck';
-import { markForcedPrompted } from './resumeUpdateCheck';
+import { enterForcedUpdate } from './forcedUpdateStore';
import { isCanaryChannel } from './canaryChannelStore';
type CheckState = 'idle' | 'checking' | 'up-to-date' | 'update-available' | 'error';
@@ -52,26 +52,36 @@ async function openInstall(url: string): Promise<void> {
}
}
-/** 弹出整包更新引导(强更不可取消)。启动/设置页检查与 resume 静默检查的强更路径共用。 */
+/** 阻断屏的「去更新」出口:解析安装地址并交给系统。无可用地址则 no-op。 */
+export function openBundleInstall(target: { itmsUrl?: string; installUrl?: string }): void {
+ const url = preferredInstallUrl(target);
+ if (url) void openInstall(url);
+}
+
+/**
+ * 整包更新的统一出口。启动/设置页检查与 resume 静默检查共用。
+ * - 强更:不弹窗,进入模块级阻断态,由 root 层渲染只有「去更新」的闸门屏。
+ * 弹窗做不到阻断——RN Alert 的按钮点一下就关(cancelable: false 只挡点外部/返回键),
+ * 弹窗消失后底下的 App 照旧可用,那是"强提醒"不是"强制"。
+ * - 非强更:可跳过的普通提示,行为不变。
+ * 两种情况都要求先解析出可跳转的安装地址:拿不到地址就什么都不做,
+ * 尤其不能把用户关进一个没有出口的阻断屏(见 forcedUpdateStore 的三层保证)。
+ */
export function promptBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUpdate>): void {
if (!evaluation.target) return;
const url = preferredInstallUrl(evaluation.target);
if (!url) return;
+
+ if (evaluation.forced) {
+ enterForcedUpdate(evaluation.target);
+ return;
+ }
+
const notes = evaluation.target.releaseNotes?.trim();
const message = [
i18n.t('update.bundleAvailableBody'),
notes ? i18n.t('update.releaseNotes', { notes }) : '',
].join('');
-
- if (evaluation.forced) {
- // 确认有可跳转 URL、即将展示强更弹窗时才标记去重(模块级 Set,跨启动/resume 路径共享)。
- // 必须在 url 校验之后标记:若无 URL 提前 return 则不标记,下次 resume 仍会重试,
- // 避免"已标记但未展示"导致强更对本进程永久失声。
- markForcedPrompted(evaluation.target.runtimeVersion);
- // 强制更新:不可取消,只留"去更新"。
- Alert.alert(i18n.t('update.forcedTitle'), message, [{ text: i18n.t('update.goUpdate'), onPress: () => void openInstall(url) }], { cancelable: false });
- return;
- }
Alert.alert(i18n.t('update.newVersionTitle'), message, [
{ text: i18n.t('update.later'), style: 'cancel' },
{ text: i18n.t('update.goUpdate'), onPress: () => void openInstall(url) },