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): 强更阻断屏自带回前台重新核对,不再只能杀进程恢复

guyong6938718c984b
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index e8f4382902..33ce47c9d2 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -55,6 +55,7 @@ import {
useForcedUpdate,
type ForcedUpdateTarget,
} from '@/update/forcedUpdateStore';
+import { useForcedUpdateRecheck } from '@/update/useForcedUpdateRecheck';
import { useResumeUpdateCheck } from '@/update/useResumeUpdateCheck';
import {
markStartupOtaLaunchSuccess,
@@ -472,6 +473,10 @@ function StartupGateBlockedContent({
*/
function ForcedUpdateGateContent({ target }: { target: ForcedUpdateTarget }) {
const { t } = useTranslation();
+ // 阻断期间业务树不挂载 → useResumeUpdateCheck 也停了,本进程不会再拉 /latest。
+ // 所以阻断屏自带一次"回前台重新核对":服务端撤回误下发的门槛后,用户切出去再回来
+ // 即自动解除,不必杀进程冷启动。拉取失败一律维持阻断(不能靠断网绕过)。
+ useForcedUpdateRecheck();
const notes = target.releaseNotes?.trim();
const subtitle = [
t('update.bundleAvailableBody'),
diff --git a/apps/mobile/src/__tests__/forcedUpdateGate.test.ts b/apps/mobile/src/__tests__/forcedUpdateGate.test.ts
index 8320b05c29..0841d7efa2 100644
--- a/apps/mobile/src/__tests__/forcedUpdateGate.test.ts
+++ b/apps/mobile/src/__tests__/forcedUpdateGate.test.ts
@@ -14,6 +14,18 @@ describe('强更阻断闸门', () => {
const read = (rel: string) =>
readFileSync(resolve(process.cwd(), rel), 'utf8').replace(/\r\n/g, '\n');
+ /**
+ * 去掉行注释与块注释后再断言"某段代码不存在"。
+ * 直接搜关键字会误伤解释这段历史的注释;搜 `{ cancelable:` 又依赖空格写法
+ * (`{cancelable:` 就漏检)。剥注释后按关键字断言,两个问题一起消掉。
+ */
+ const readCode = (rel: string) =>
+ read(rel)
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .split('\n')
+ .map((line) => line.replace(/(^|\s)\/\/.*$/, '$1'))
+ .join('\n');
+
it('root layout 用 forcedUpdate 状态阻断业务树,唯一出口是「去更新」', () => {
const layout = read('app/_layout.tsx');
@@ -32,16 +44,29 @@ describe('强更阻断闸门', () => {
it('强更路径不再走 Alert:promptBundleUpdate 直接进入阻断态', () => {
const prompt = read('src/update/useBundleUpdatePrompt.ts');
+ const promptCode = readCode('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(promptCode).not.toMatch(/cancelable/);
+ expect(promptCode).not.toContain("i18n.t('update.forcedTitle')");
// 拿不到安装地址时不得进入阻断态(否则把用户关进没有出口的屏)。
expect(prompt).toContain('if (!url) return;');
});
+ it('阻断屏自带回前台重新核对:服务端撤回门槛后不必杀进程', () => {
+ const layout = read('app/_layout.tsx');
+ const recheck = read('src/update/forcedUpdateRecheck.ts');
+
+ // 阻断期间业务树不挂载 → resume 通道停摆,恢复入口必须挂在阻断屏自己身上。
+ expect(layout).toContain("from '@/update/useForcedUpdateRecheck'");
+ expect(layout).toContain('useForcedUpdateRecheck();');
+ // 解除方向 fail-closed:只有成功拉到 /latest 且判定不再强更才解除,
+ // 拉取失败维持阻断,不能靠断网 / 飞行模式绕过。
+ expect(recheck).toContain('if (evaluation.forced) return \'still-forced\';');
+ expect(recheck).toContain("return 'error'");
+ });
+
it('阻断态只存内存,不持久化(服务端撤回门槛后用户不能被本地缓存锁死)', () => {
const store = read('src/update/forcedUpdateStore.ts');
diff --git a/apps/mobile/src/update/forcedUpdateRecheck.test.ts b/apps/mobile/src/update/forcedUpdateRecheck.test.ts
new file mode 100644
index 0000000000..fcffbf0ae1
--- /dev/null
+++ b/apps/mobile/src/update/forcedUpdateRecheck.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createForcedUpdateRechecker,
+ type ForcedUpdateRecheckDeps,
+} from './forcedUpdateRecheck';
+
+/** 有效的 /latest 记录;默认带门槛(当前 version 1.0.0 < 2.0.0 → 仍强更)。 */
+function latestRecord(overrides: Record<string, unknown> = {}) {
+ return {
+ version: '2.0.0',
+ buildNumber: 20,
+ runtimeVersion: '2',
+ installUrl: 'https://cdn.example/install',
+ itmsUrl: 'itms-services://?action=download-manifest&url=https://cdn.example/m.plist',
+ minVersion: '2.0.0',
+ ...overrides,
+ };
+}
+
+function makeDeps(overrides: Partial<ForcedUpdateRecheckDeps> = {}) {
+ let nowMs = 1_000_000;
+ const deps: ForcedUpdateRecheckDeps & { advance: (ms: number) => void } = {
+ fetchLatest: vi.fn(async () => latestRecord()),
+ getCurrentRuntimeVersion: () => '1',
+ getCurrentVersion: () => '1.0.0',
+ onCleared: vi.fn(),
+ now: () => nowMs,
+ advance: (ms: number) => { nowMs += ms; },
+ ...overrides,
+ };
+ return deps;
+}
+
+/** 模拟一次「切后台再回前台」。 */
+function resume(rechecker: ReturnType<typeof createForcedUpdateRechecker>) {
+ rechecker.handleAppStateChange('background');
+ return rechecker.handleAppStateChange('active');
+}
+
+describe('createForcedUpdateRechecker 触发条件', () => {
+ it('创建后立刻回前台:间隔不足 → 不检查(阻断屏刚挂载时那次检查刚跑完)', () => {
+ const deps = makeDeps();
+ const rechecker = createForcedUpdateRechecker(deps);
+ expect(resume(rechecker)).toBeNull();
+ expect(deps.fetchLatest).not.toHaveBeenCalled();
+ });
+
+ it('没进过后台的 active 抖动 → 不检查', () => {
+ const deps = makeDeps();
+ const rechecker = createForcedUpdateRechecker(deps, { minIntervalMs: 0 });
+ deps.advance(1);
+ expect(rechecker.handleAppStateChange('inactive')).toBeNull();
+ expect(rechecker.handleAppStateChange('active')).toBeNull();
+ expect(deps.fetchLatest).not.toHaveBeenCalled();
+ });
+
+ it('间隔不足的连续回前台 → 只检查一次(节流)', async () => {
+ const deps = makeDeps();
+ const rechecker = createForcedUpdateRechecker(deps, { minIntervalMs: 1000 });
+ deps.advance(1001);
+ await resume(rechecker);
+ deps.advance(1); // 远小于间隔
+ expect(resume(rechecker)).toBeNull();
+ expect(deps.fetchLatest).toHaveBeenCalledOnce();
+ });
+});
+
+describe('createForcedUpdateRechecker 解除判定', () => {
+ const runOnce = (deps: ReturnType<typeof makeDeps>) => {
+ const rechecker = createForcedUpdateRechecker(deps, { minIntervalMs: 0 });
+ deps.advance(1);
+ const result = resume(rechecker);
+ expect(result).not.toBeNull();
+ return result!;
+ };
+
+ it('门槛已撤回 → 解除阻断', async () => {
+ const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord({ minVersion: undefined })) });
+ await expect(runOnce(deps)).resolves.toBe('cleared');
+ expect(deps.onCleared).toHaveBeenCalledOnce();
+ });
+
+ it('门槛降到当前 version 之下 → 解除阻断', async () => {
+ const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord({ minVersion: '1.0.0' })) });
+ await expect(runOnce(deps)).resolves.toBe('cleared');
+ expect(deps.onCleared).toHaveBeenCalledOnce();
+ });
+
+ it('门槛仍在 → 维持阻断', async () => {
+ const deps = makeDeps();
+ await expect(runOnce(deps)).resolves.toBe('still-forced');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('/latest 拉取失败 → 维持阻断(不能靠断网绕过强更)', async () => {
+ const deps = makeDeps({ fetchLatest: vi.fn(async () => { throw new Error('offline'); }) });
+ await expect(runOnce(deps)).resolves.toBe('error');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('/latest 记录解析不出 → 维持阻断(一条坏记录不得放行所有被强更装机)', async () => {
+ const deps = makeDeps({ fetchLatest: vi.fn(async () => ({})) });
+ await expect(runOnce(deps)).resolves.toBe('error');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('记录有效但缺 runtimeVersion / 安装地址 → 维持阻断', async () => {
+ const deps = makeDeps({
+ fetchLatest: vi.fn(async () => latestRecord({ installUrl: '', itmsUrl: '', minVersion: undefined })),
+ });
+ await expect(runOnce(deps)).resolves.toBe('error');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('拿不到本机 version → 维持阻断(比不出来不放行)', async () => {
+ const deps = makeDeps({
+ fetchLatest: vi.fn(async () => latestRecord({ minVersion: undefined })),
+ getCurrentVersion: () => null,
+ });
+ await expect(runOnce(deps)).resolves.toBe('error');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('/latest 挂起 → withTimeout 兜底为 error,维持阻断', async () => {
+ const deps = makeDeps({ fetchLatest: vi.fn((): Promise<unknown> => new Promise(() => {})) });
+ const rechecker = createForcedUpdateRechecker(deps, { minIntervalMs: 0, latestTimeoutMs: 20 });
+ deps.advance(1);
+ const result = resume(rechecker);
+ expect(result).not.toBeNull();
+ await expect(result!).resolves.toBe('error');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+
+ it('阻断屏已卸载(isCurrent=false)→ 迟到结果不解除', async () => {
+ let current = true;
+ let release!: (value: unknown) => void;
+ const deps = makeDeps({
+ fetchLatest: vi.fn(() => new Promise((resolve) => { release = resolve; })),
+ isCurrent: () => current,
+ });
+ const rechecker = createForcedUpdateRechecker(deps, { minIntervalMs: 0 });
+ deps.advance(1);
+ const pending = resume(rechecker);
+ expect(pending).not.toBeNull();
+ current = false;
+ release(latestRecord({ minVersion: undefined })); // 已不再强更,但屏已卸载
+ await expect(pending!).resolves.toBe('still-forced');
+ expect(deps.onCleared).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/update/forcedUpdateRecheck.ts b/apps/mobile/src/update/forcedUpdateRecheck.ts
new file mode 100644
index 0000000000..ffdade73f4
--- /dev/null
+++ b/apps/mobile/src/update/forcedUpdateRecheck.ts
@@ -0,0 +1,106 @@
+// 阻断屏的"回前台重新核对" —— 纯逻辑(依赖可注入,便于单测)。
+//
+// 为什么需要:进入强更阻断态后业务树整体不挂载,useResumeUpdateCheck 随之卸载,
+// 于是本进程再也不会拉 /latest。服务端撤回误下发的 minVersion 后,用户只能杀进程
+// 冷启动才能恢复 —— 普通用户不会想到这一步。所以阻断屏自己补一次检查。
+//
+// 方向不对称,这是刻意的:
+// - **进入**阻断态要求成功拉到 /latest 且判定强更(拉不到就 fail-open 放行,更新服务
+// 故障不该锁死用户);
+// - **解除**阻断态同样要求成功拉到 /latest 且判定不再强更 —— 拉取失败一律维持阻断,
+// 否则断网(飞行模式)就能绕过强更。
+//
+// 节流比 resume 通道(5 分钟)短得多:用户此刻正被挡在门外,恢复延迟直接可感;
+// 但仍要节流,避免在阻断屏上反复切前后台把 /latest 打成高频请求。
+
+import { evaluateBundleUpdate, parseLatestRelease } from './bundleUpdate';
+import { withTimeout } from './startupOtaUpdate';
+
+export type ForcedUpdateRecheckOutcome = 'still-forced' | 'cleared' | 'error';
+
+export interface ForcedUpdateRecheckDeps {
+ /** 拉 /latest(平台与 channel 已由调用方绑定);返回原始 JSON。 */
+ fetchLatest: () => Promise<unknown>;
+ getCurrentRuntimeVersion: () => string | null | undefined;
+ getCurrentVersion: () => string | null | undefined;
+ /** 判定不再强更时调用(实参为 clearForcedUpdate),之后业务树重新挂载。 */
+ onCleared: () => void;
+ now: () => number;
+ /** 阻断屏卸载后使迟到结果失效。 */
+ isCurrent?: () => boolean;
+}
+
+export interface ForcedUpdateRecheckOptions {
+ /** 两次核对的最小间隔(默认 30s)。 */
+ minIntervalMs?: number;
+ /** /latest 拉取超时(默认 10s,与 resume 通道同口径)。 */
+ latestTimeoutMs?: number;
+}
+
+const DEFAULT_MIN_INTERVAL_MS = 30_000;
+const DEFAULT_LATEST_TIMEOUT_MS = 10_000;
+
+export interface ForcedUpdateRechecker {
+ /**
+ * AppState 'change' 入口。命中「从后台回到前台 + 间隔满足 + 无在途」才发起;
+ * 未触发时返回 null(便于测试断言),触发时返回本次核对的 Promise(永不 reject)。
+ */
+ handleAppStateChange: (next: string) => Promise<ForcedUpdateRecheckOutcome> | null;
+}
+
+/** 创建阻断屏核对器(持有节流/在途状态;阻断屏挂载期间一个实例)。 */
+export function createForcedUpdateRechecker(
+ deps: ForcedUpdateRecheckDeps,
+ {
+ minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
+ latestTimeoutMs = DEFAULT_LATEST_TIMEOUT_MS,
+ }: ForcedUpdateRecheckOptions = {},
+): ForcedUpdateRechecker {
+ // 与 resume 通道不同:阻断屏刚挂载时那次检查刚跑完,所以创建时刻同样视为"刚查过"。
+ let lastRunAt = deps.now();
+ let wasBackground = false;
+ let inFlight = false;
+
+ async function run(): Promise<ForcedUpdateRecheckOutcome> {
+ inFlight = true;
+ try {
+ const latest = await withTimeout(deps.fetchLatest(), latestTimeoutMs);
+ if (deps.isCurrent && !deps.isCurrent()) return 'still-forced';
+ // 解除必须建立在"真的比出来了不再低于门槛"之上。record 解析不出(指针损坏 /
+ // 被中间层改坏)或拿不到本机 version 时,evaluateBundleUpdate 会 fail-open 报
+ // 无更新 —— 那是**进入**方向的正确取向,拿到解除方向就成了漏洞:一条坏记录
+ // 就能放行所有被强更的装机。这里显式挡掉,按拉取失败处理。
+ const record = parseLatestRelease(latest);
+ const currentVersion = String(deps.getCurrentVersion() ?? '').trim();
+ if (!record || !currentVersion) return 'error';
+ const evaluation = evaluateBundleUpdate({
+ currentRuntimeVersion: deps.getCurrentRuntimeVersion(),
+ currentVersion,
+ latest,
+ });
+ // 仍然强更(门槛还在,或换了更高的目标)→ 维持阻断,不动 store:
+ // 目标信息的刷新交给下次冷启动,阻断屏本身不需要热更文案。
+ if (evaluation.forced) return 'still-forced';
+ deps.onCleared();
+ return 'cleared';
+ } catch {
+ return 'error'; // 拉不到就维持阻断(见文件头:解除方向 fail-closed)
+ } finally {
+ inFlight = false;
+ }
+ }
+
+ return {
+ handleAppStateChange(next: string): Promise<ForcedUpdateRecheckOutcome> | null {
+ if (next === 'background') {
+ wasBackground = true;
+ return null;
+ }
+ if (next !== 'active' || !wasBackground) return null;
+ wasBackground = false;
+ if (inFlight || deps.now() - lastRunAt < minIntervalMs) return null;
+ lastRunAt = deps.now();
+ return run();
+ },
+ };
+}
diff --git a/apps/mobile/src/update/forcedUpdateStore.test.ts b/apps/mobile/src/update/forcedUpdateStore.test.ts
index 76256f8b95..72f297a983 100644
--- a/apps/mobile/src/update/forcedUpdateStore.test.ts
+++ b/apps/mobile/src/update/forcedUpdateStore.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
__testing,
+ clearForcedUpdate,
enterForcedUpdate,
getForcedUpdateTarget,
subscribeForcedUpdate,
@@ -61,6 +62,29 @@ describe('forcedUpdateStore', () => {
expect(getForcedUpdateTarget()).not.toBeNull();
});
+ it('解除阻断态 → 目标清空并通知(服务端撤回门槛后的恢复入口)', () => {
+ enterForcedUpdate(target());
+ const listener = vi.fn();
+ subscribeForcedUpdate(listener);
+ clearForcedUpdate();
+ expect(getForcedUpdateTarget()).toBeNull();
+ expect(listener).toHaveBeenCalledOnce();
+ });
+
+ it('本来就没阻断时解除 → 幂等,不通知', () => {
+ const listener = vi.fn();
+ subscribeForcedUpdate(listener);
+ clearForcedUpdate();
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it('解除后可再次进入(下一轮门槛)', () => {
+ enterForcedUpdate(target());
+ clearForcedUpdate();
+ enterForcedUpdate(target());
+ expect(getForcedUpdateTarget()).toEqual(target());
+ });
+
it('单个订阅者抛错不影响其它订阅者', () => {
const bad = vi.fn(() => { throw new Error('boom'); });
const good = vi.fn();
diff --git a/apps/mobile/src/update/forcedUpdateStore.ts b/apps/mobile/src/update/forcedUpdateStore.ts
index 9cfa2a3265..25c6fa96d9 100644
--- a/apps/mobile/src/update/forcedUpdateStore.ts
+++ b/apps/mobile/src/update/forcedUpdateStore.ts
@@ -13,11 +13,14 @@
* 就再也救不回被误挡的装机。
* 而"杀进程绕过"并不成立:下次启动会重新拉 /latest 并立刻命中同一个门槛。
*
- * 三层保证"不会把人永久挡在门外":
+ * 四层保证"不会把人永久挡在门外":
* 1. 拉不到 /latest(离线 / 超时 / 5xx)→ 调用方 fail-open,不进入阻断态;
* 2. 拿不到可跳转的安装地址 → 不进入阻断态(见 promptBundleUpdate),不造无出口的屏;
* 3. 门槛必须 ≤ 该 record 宣告的 version(发布链 assertMinVersionUsable fail closed),
- * 所以装上被广播的那个版本必然解除阻断。
+ * 所以装上被广播的那个版本必然解除阻断;
+ * 4. 阻断期间业务树整体不挂载 —— resume 检查也随之停摆,所以阻断屏自带一次
+ * "回前台重新核对"(见 forcedUpdateRecheck):服务端撤回门槛后不必杀进程冷启动,
+ * 切出去再回来即自动解除。
*/
import { useSyncExternalStore } from 'react';
@@ -64,6 +67,17 @@ export function enterForcedUpdate(target: ForcedUpdateTarget): void {
notifyListeners();
}
+/**
+ * 解除阻断态(生产入口,不是测试专用)。
+ * 唯一调用方是阻断屏的重新核对:**成功**拉到 /latest 且判定不再强更时才解除
+ * —— 不能在拉取失败时解除,否则断网就能绕过强更。
+ */
+export function clearForcedUpdate(): void {
+ if (forcedTarget === null) return;
+ forcedTarget = null;
+ notifyListeners();
+}
+
/** 当前阻断目标;null = 未命中强更。 */
export function getForcedUpdateTarget(): ForcedUpdateTarget | null {
return forcedTarget;
diff --git a/apps/mobile/src/update/useForcedUpdateRecheck.ts b/apps/mobile/src/update/useForcedUpdateRecheck.ts
new file mode 100644
index 0000000000..63d4825f94
--- /dev/null
+++ b/apps/mobile/src/update/useForcedUpdateRecheck.ts
@@ -0,0 +1,41 @@
+// 阻断屏的"回前台重新核对" hook:订阅 AppState,把真实 IO 绑进
+// createForcedUpdateRechecker(判定/节流逻辑在 forcedUpdateRecheck.ts,纯函数已单测)。
+//
+// 只在强更阻断屏挂载期间存在(见 app/_layout.tsx 的 ForcedUpdateGateContent):
+// 阻断态解除后业务树重新挂载,后续检查回到 useResumeUpdateCheck 那条常规通道。
+
+import { useEffect } from 'react';
+import { AppState, Platform } from 'react-native';
+import Constants from 'expo-constants';
+import * as Updates from 'expo-updates';
+import { fetchLatestRelease } from './fetchLatestRelease';
+import { createForcedUpdateRechecker } from './forcedUpdateRecheck';
+import { clearForcedUpdate } from './forcedUpdateStore';
+import { isCanaryChannel } from './canaryChannelStore';
+
+export function useForcedUpdateRecheck(isCanary = isCanaryChannel()): void {
+ useEffect(() => {
+ let current = true;
+ const rechecker = createForcedUpdateRechecker({
+ fetchLatest: () => fetchLatestRelease(
+ Platform.OS === 'android' ? 'android' : 'ios',
+ undefined,
+ undefined,
+ isCanary,
+ ),
+ getCurrentRuntimeVersion: () => Updates.runtimeVersion,
+ getCurrentVersion: () => Constants.expoConfig?.version ?? null,
+ onCleared: clearForcedUpdate,
+ now: () => Date.now(),
+ isCurrent: () => current,
+ });
+
+ const subscription = AppState.addEventListener('change', (next) => {
+ void rechecker.handleAppStateChange(next);
+ });
+ return () => {
+ current = false;
+ subscription.remove();
+ };
+ }, [isCanary]);
+}