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): 热更 reload 不再无限循环把 App 卡在启动页 (#1177)

guyong-zapoc3a66b711489
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index c02c148072..c33d0fe413 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -45,7 +45,10 @@ import { startJsStallWatchdog } from '@/debug/jsStallWatchdog';
import { initMobileTapdb } from '@/analytics/mobileTapdb';
import { useBundleUpdatePrompt } from '@/update/useBundleUpdatePrompt';
import { useResumeUpdateCheck } from '@/update/useResumeUpdateCheck';
-import { useStartupOtaGate } from '@/update/useStartupOtaGate';
+import {
+ markStartupOtaLaunchSuccess,
+ useStartupOtaGate,
+} from '@/update/useStartupOtaGate';
import { useCanaryChannelGate } from '@/update/useCanaryChannelGate';
import { useStartupEndpointGate } from '@/config/useStartupEndpointGate';
import { IS_OTA_SELFHOST } from '@/config/env';
@@ -82,6 +85,12 @@ function NavigationGate() {
if (auth.initialized) releaseSplash();
}, [auth.initialized, releaseSplash]);
+ // 启动链走完 = 本次热更 reload(如果有)确实落地:清掉 reload 闸门记录。
+ // 只在目标 update 已成为当前运行版本时才清,判定在 markStartupOtaLaunchSuccess 内。
+ useEffect(() => {
+ if (auth.initialized) markStartupOtaLaunchSuccess();
+ }, [auth.initialized]);
+
useEffect(() => {
if (!auth.initialized) return;
const inAuthGroup = segments[0] === '(auth)';
diff --git a/apps/mobile/src/update/otaReloadGuard.test.ts b/apps/mobile/src/update/otaReloadGuard.test.ts
new file mode 100644
index 0000000000..24ba625039
--- /dev/null
+++ b/apps/mobile/src/update/otaReloadGuard.test.ts
@@ -0,0 +1,179 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const storage = new Map<string, string>();
+let failGetItem = false;
+let failSetItem = false;
+let failRemoveItem = false;
+
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: {
+ getItem: vi.fn(async (key: string) => {
+ if (failGetItem) throw new Error('storage unavailable');
+ return storage.get(key) ?? null;
+ }),
+ setItem: vi.fn(async (key: string, value: string) => {
+ if (failSetItem) throw new Error('storage full');
+ storage.set(key, value);
+ }),
+ removeItem: vi.fn(async (key: string) => {
+ if (failRemoveItem) throw new Error('storage unavailable');
+ storage.delete(key);
+ }),
+ },
+}));
+
+import {
+ MAX_OTA_RELOAD_ATTEMPTS,
+ __testing,
+ clearOtaReloadGuardIfLaunched,
+ readOtaReloadGuard,
+ recordOtaReload,
+ shouldBlockOtaReload,
+} from './otaReloadGuard';
+
+const KEY = __testing.storageKey;
+
+beforeEach(() => {
+ storage.clear();
+ failGetItem = false;
+ failSetItem = false;
+ failRemoveItem = false;
+ vi.clearAllMocks();
+});
+
+describe('readOtaReloadGuard', () => {
+ it('首次安装 → 无记录', async () => {
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: null,
+ reloadCount: 0,
+ });
+ });
+
+ it('坏值(非 JSON / 缺 id)一律按无记录,不阻断正常热更', async () => {
+ storage.set(KEY, 'not-json');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: null,
+ reloadCount: 0,
+ });
+ storage.set(KEY, JSON.stringify({ reloadCount: 9 }));
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: null,
+ reloadCount: 0,
+ });
+ });
+
+ it('次数非法 → 按已试 1 次,不误挡', async () => {
+ storage.set(KEY, JSON.stringify({ targetUpdateId: 'u1', reloadCount: -3 }));
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u1',
+ reloadCount: 1,
+ });
+ });
+
+ it('读存储抛错必须抛出:吞成无记录会把计数重置、闸门永远合不上', async () => {
+ storage.set(KEY, JSON.stringify({ targetUpdateId: 'u1', reloadCount: 2 }));
+ failGetItem = true;
+ await expect(readOtaReloadGuard()).rejects.toThrow(/storage unavailable/);
+ });
+});
+
+describe('recordOtaReload', () => {
+ it('同一个 update 累加次数', async () => {
+ await recordOtaReload('u1');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u1',
+ reloadCount: 1,
+ });
+ await recordOtaReload('u1');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u1',
+ reloadCount: 2,
+ });
+ });
+
+ it('换成另一个 update → 从 1 重新计数', async () => {
+ await recordOtaReload('u1');
+ await recordOtaReload('u1');
+ await recordOtaReload('u2');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u2',
+ reloadCount: 1,
+ });
+ });
+
+ it('写入失败必须抛出(调用方据此放弃本次 reload)', async () => {
+ failSetItem = true;
+ await expect(recordOtaReload('u1')).rejects.toThrow(/storage full/);
+ });
+});
+
+describe('shouldBlockOtaReload', () => {
+ it('未达上限不挡', () => {
+ expect(
+ shouldBlockOtaReload(
+ { targetUpdateId: 'u1', reloadCount: MAX_OTA_RELOAD_ATTEMPTS - 1 },
+ 'u1',
+ ),
+ ).toBe(false);
+ });
+
+ it('达到上限则挡', () => {
+ expect(
+ shouldBlockOtaReload(
+ { targetUpdateId: 'u1', reloadCount: MAX_OTA_RELOAD_ATTEMPTS },
+ 'u1',
+ ),
+ ).toBe(true);
+ });
+
+ it('目标换了就不挡(计数只对同一个 update 有意义)', () => {
+ expect(
+ shouldBlockOtaReload(
+ { targetUpdateId: 'u1', reloadCount: MAX_OTA_RELOAD_ATTEMPTS },
+ 'u2',
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('clearOtaReloadGuardIfLaunched', () => {
+ it('目标 update 已成为当前运行版本 → 清记录', async () => {
+ await recordOtaReload('u1');
+ await clearOtaReloadGuardIfLaunched('u1');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: null,
+ reloadCount: 0,
+ });
+ });
+
+ it('reload 后仍跑着别的版本 → 保留记录,下次冷启动继续计数', async () => {
+ await recordOtaReload('u1');
+ await recordOtaReload('u1');
+ await clearOtaReloadGuardIfLaunched('embedded-or-old');
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u1',
+ reloadCount: 2,
+ });
+ });
+
+ it('当前没有 updateId(跑包内 bundle)→ 不清', async () => {
+ await recordOtaReload('u1');
+ await clearOtaReloadGuardIfLaunched(null);
+ await expect(readOtaReloadGuard()).resolves.toEqual({
+ targetUpdateId: 'u1',
+ reloadCount: 1,
+ });
+ });
+
+ it('清除失败只吞掉,不抛给启动链', async () => {
+ await recordOtaReload('u1');
+ failRemoveItem = true;
+ await expect(clearOtaReloadGuardIfLaunched('u1')).resolves.toBeUndefined();
+ });
+
+ it('读取失败也只吞掉(启动链末端没人能处理这个异常)', async () => {
+ await recordOtaReload('u1');
+ failGetItem = true;
+ await expect(clearOtaReloadGuardIfLaunched('u1')).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/update/otaReloadGuard.ts b/apps/mobile/src/update/otaReloadGuard.ts
new file mode 100644
index 0000000000..eca5581d06
--- /dev/null
+++ b/apps/mobile/src/update/otaReloadGuard.ts
@@ -0,0 +1,119 @@
+/**
+ * 启动热更 reload 的跨重启闸门状态。
+ *
+ * 冷启动热更门(useStartupOtaGate)的 `started` ref 只防同一个 JS 实例内重复检查;
+ * `Updates.reloadAsync()` 之后是全新的 JS 实例,内存状态全部归零。一旦某台机器进入
+ * 「下载下来的 update 装不上、每次 check 又照样报有新版」的状态,那道门就会无休止地
+ * check → fetch → reload,表现为启动页无限转圈并每隔几秒闪一次,用户无法进入 App,
+ * 且不会自愈(实测某台设备累计重启 33 次仍在循环)。
+ *
+ * 因此把「上一次是为了装哪个 update 才 reload、已经试了几次」持久化到本机:
+ * - reload 之前记一次(必须落盘成功才允许 reload,否则闸门等于不存在);
+ * - 同一个 update 连续试满 MAX_OTA_RELOAD_ATTEMPTS 次仍未装上 → 判定为循环,
+ * 本次启动放弃热更、直接进 App(热更不生效 好于 进不去 App);
+ * - 启动链真正走完后,只有当前正在运行的 update 就是当次目标时才清记录
+ * —— reload 后仍跑着旧 bundle 说明目标没装上,这条记录必须留到下次冷启动继续计数。
+ *
+ * 标记不敏感(只有一个 update id 和次数),与 canaryChannelStore 一样用 AsyncStorage。
+ * 本模块无内存缓存:每次冷启动只读一次,读写失败一律 fail-safe(见各函数说明)。
+ */
+import AsyncStorage from '@react-native-async-storage/async-storage';
+
+const STORAGE_KEY = 'cindy.mobile.update.reloadGuard';
+
+/**
+ * 同一个 update 允许的 reload 次数上限。正常路径下一次就够:reload 后新 bundle 生效,
+ * 下一次 check 即 up-to-date,记录随启动成功被清掉。留 2 次是给「reload 恰好被系统
+ * 杀进程/息屏打断」这类偶发一次重试机会;到达上限说明是装不上,不是运气差。
+ */
+export const MAX_OTA_RELOAD_ATTEMPTS = 2;
+
+export interface OtaReloadGuardState {
+ /** 上次 reload 想装上的 update id;无记录为 null。 */
+ targetUpdateId: string | null;
+ /** 针对该 update id 已经 reload 过的次数。 */
+ reloadCount: number;
+}
+
+const EMPTY_STATE: OtaReloadGuardState = { targetUpdateId: null, reloadCount: 0 };
+
+function parseState(raw: string | null): OtaReloadGuardState {
+ if (!raw) return EMPTY_STATE;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== 'object') return EMPTY_STATE;
+ const { targetUpdateId, reloadCount } = parsed as Record<string, unknown>;
+ if (typeof targetUpdateId !== 'string' || !targetUpdateId) return EMPTY_STATE;
+ // 次数非法(缺失/负数/小数/NaN)时不猜:按已试 1 次处理,宁可少挡一次也不误挡。
+ const count =
+ typeof reloadCount === 'number' && Number.isInteger(reloadCount) && reloadCount > 0
+ ? reloadCount
+ : 1;
+ return { targetUpdateId, reloadCount: count };
+ } catch {
+ return EMPTY_STATE;
+ }
+}
+
+/**
+ * 读取闸门状态。
+ *
+ * **读失败会抛出**,不能吞成「无记录」:那样计数会被重置成 1,间歇性失败白放一次
+ * reload,持续失败则永远到不了上限、闸门彻底失效——正是本模块要防的循环。与写失败
+ * 同一口径:存储不可用时本次启动放弃热更(调用方 fail-open 放行进 App)。
+ *
+ * 坏值(非 JSON / 缺 id)不算故障:那是没有可信记录,按「无记录」处理,下一次写入即覆盖。
+ */
+export async function readOtaReloadGuard(): Promise<OtaReloadGuardState> {
+ return parseState(await AsyncStorage.getItem(STORAGE_KEY));
+}
+
+/** 已经为这个 update 试满次数 → 本次启动不再 reload。 */
+export function shouldBlockOtaReload(
+ state: OtaReloadGuardState,
+ targetUpdateId: string,
+): boolean {
+ return (
+ state.targetUpdateId === targetUpdateId && state.reloadCount >= MAX_OTA_RELOAD_ATTEMPTS
+ );
+}
+
+/**
+ * 记一次 reload 尝试(同一 update 累加,换 update 从 1 重新计数)。
+ *
+ * **失败会抛出**:调用方必须在 `await` 成功后才 reload。写不进去就 reload,下一轮启动
+ * 读到的还是旧计数,闸门永远合不上——那正是这个模块要防的死循环。
+ */
+export async function recordOtaReload(targetUpdateId: string): Promise<void> {
+ const previous = await readOtaReloadGuard();
+ const reloadCount =
+ previous.targetUpdateId === targetUpdateId ? previous.reloadCount + 1 : 1;
+ await AsyncStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ targetUpdateId, reloadCount } satisfies OtaReloadGuardState),
+ );
+}
+
+/**
+ * 启动链走完后调用:只有当次目标确实成为当前运行的 update 才清记录。
+ *
+ * 不能改成「进了 App 就清」——被闸门放行也算进了 App,那样每次冷启动都会重新放开一次
+ * reload,循环变成「每次启动闪一轮」而不是被真正掐断。
+ *
+ * 读写失败都只吞掉:这里在启动链末端跑,清不掉的代价只是下一次冷启动少做一次热更,
+ * 不影响进入 App;而向启动链抛异常没有任何人能处理。
+ */
+export async function clearOtaReloadGuardIfLaunched(
+ currentUpdateId: string | null,
+): Promise<void> {
+ if (!currentUpdateId) return;
+ try {
+ const state = await readOtaReloadGuard();
+ if (state.targetUpdateId !== currentUpdateId) return;
+ await AsyncStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // ignore: 记录残留只会让下次冷启动保守一点
+ }
+}
+
+export const __testing = { storageKey: STORAGE_KEY };
diff --git a/apps/mobile/src/update/startupOtaUpdate.test.ts b/apps/mobile/src/update/startupOtaUpdate.test.ts
index 021461da0a..099d9850c0 100644
--- a/apps/mobile/src/update/startupOtaUpdate.test.ts
+++ b/apps/mobile/src/update/startupOtaUpdate.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
-import { runStartupOtaUpdate, withTimeout } from './startupOtaUpdate';
+import {
+ runEmergencyOtaRecovery,
+ runStartupOtaUpdate,
+ withTimeout,
+} from './startupOtaUpdate';
function deps(overrides: Partial<Parameters<typeof runStartupOtaUpdate>[0]> = {}) {
return {
@@ -8,10 +12,24 @@ function deps(overrides: Partial<Parameters<typeof runStartupOtaUpdate>[0]> = {}
checkForUpdateAsync: vi.fn(async () => ({ isAvailable: false })),
fetchUpdateAsync: vi.fn(async () => ({ isNew: false })),
reloadAsync: vi.fn(async () => undefined),
+ isEmergencyLaunch: vi.fn(() => false),
+ currentUpdateId: vi.fn(() => 'running-update'),
+ isReloadBlocked: vi.fn(async () => false),
+ recordReload: vi.fn(async () => undefined),
...overrides,
};
}
+/** fetch 到一个与当前运行版本不同的新 update。 */
+function fetchedNewUpdate(id = 'next-update') {
+ return vi.fn(async () => ({ isNew: true, manifest: { id } }));
+}
+
+/** check 报告有可用更新(带 manifest,与线上真实返回一致)。 */
+function checkAvailable(id?: string) {
+ return vi.fn(async () => ({ isAvailable: true, ...(id ? { manifest: { id } } : {}) }));
+}
+
describe('runStartupOtaUpdate', () => {
it('enabled=false → skipped,且不发起任何调用', async () => {
const d = deps({ enabled: false });
@@ -59,7 +77,123 @@ describe('runStartupOtaUpdate', () => {
it('fetch 到新 bundle → reload,返回 reloading', async () => {
const d = deps({
checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
- fetchUpdateAsync: vi.fn(async () => ({ isNew: true })),
+ fetchUpdateAsync: fetchedNewUpdate(),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('reloading');
+ expect(d.reloadAsync).toHaveBeenCalledOnce();
+ });
+
+ it('emergency launch → 不联网、不 reload,直接放行进 App', async () => {
+ const d = deps({
+ isEmergencyLaunch: vi.fn(() => true),
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate(),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('emergency-launch');
+ expect(d.configureUpdateUrl).not.toHaveBeenCalled();
+ expect(d.checkForUpdateAsync).not.toHaveBeenCalled();
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('fetch 回来的就是当前运行的 update → 不 reload(死循环的直接成因)', async () => {
+ const d = deps({
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate('running-update'),
+ currentUpdateId: vi.fn(() => 'running-update'),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('already-running');
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ expect(d.recordReload).not.toHaveBeenCalled();
+ });
+
+ it('同一个 update 已试满次数 → 被闸门拦下,不再 reload', async () => {
+ const d = deps({
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate('next-update'),
+ isReloadBlocked: vi.fn(async () => true),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('reload-blocked');
+ expect(d.isReloadBlocked).toHaveBeenCalledWith('next-update');
+ expect(d.recordReload).not.toHaveBeenCalled();
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('reload 前必须先把尝试记下来(顺序不能颠倒,否则重启会打断落盘)', async () => {
+ const calls: string[] = [];
+ const d = deps({
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate('next-update'),
+ recordReload: vi.fn(async () => { calls.push('record'); }),
+ reloadAsync: vi.fn(async () => { calls.push('reload'); }),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('reloading');
+ expect(calls).toEqual(['record', 'reload']);
+ expect(d.recordReload).toHaveBeenCalledWith('next-update');
+ });
+
+ it('闸门记录写不进去 → error(fail-open),绝不 reload', async () => {
+ const d = deps({
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate('next-update'),
+ recordReload: vi.fn(async () => { throw new Error('storage full'); }),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('error');
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('已被闸门拦下的 update:在 fetch 之前就返回,不白等一次下载', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('bad-update'),
+ isReloadBlocked: vi.fn(async () => true),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('reload-blocked');
+ expect(d.isReloadBlocked).toHaveBeenCalledWith('bad-update');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('check 就报出当前正在跑的 update:同样不下载', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('running-update'),
+ currentUpdateId: vi.fn(() => 'running-update'),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('already-running');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ });
+
+ it('check 与 fetch 之间指针变了 → 按 fetch 到的 id 再判一次闸门', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('first-update'),
+ fetchUpdateAsync: fetchedNewUpdate('second-update'),
+ isReloadBlocked: vi.fn(async (id: string) => id === 'second-update'),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('reload-blocked');
+ expect(d.fetchUpdateAsync).toHaveBeenCalledOnce();
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('闸门状态读不出来 → error(fail-open),不 reload', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('next-update'),
+ isReloadBlocked: vi.fn(async () => { throw new Error('storage unavailable'); }),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('error');
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('isEmergencyLaunch 依赖本身抛错也不 reject(承诺永不 reject)', async () => {
+ const d = deps({
+ isEmergencyLaunch: vi.fn(() => { throw new Error('native module missing'); }),
+ });
+ await expect(runStartupOtaUpdate(d)).resolves.toBe('error');
+ expect(d.checkForUpdateAsync).not.toHaveBeenCalled();
+ });
+
+ it('当前跑包内 bundle(updateId 为 null)时仍允许装上热更', async () => {
+ const d = deps({
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true })),
+ fetchUpdateAsync: fetchedNewUpdate('next-update'),
+ currentUpdateId: vi.fn(() => null),
});
await expect(runStartupOtaUpdate(d)).resolves.toBe('reloading');
expect(d.reloadAsync).toHaveBeenCalledOnce();
@@ -86,6 +220,99 @@ describe('runStartupOtaUpdate', () => {
});
});
+describe('runEmergencyOtaRecovery', () => {
+ it('线上没有新版 → up-to-date,不下载', async () => {
+ const d = deps();
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('up-to-date');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ });
+
+ it('线上指针还是那个已知装不上的 update → 不重复下载十几 MB', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('bad-update'),
+ isReloadBlocked: vi.fn(async () => true),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('known-bad');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ expect(d.recordReload).not.toHaveBeenCalled();
+ });
+
+ it('check 没带回 id → 无从判断是否已知坏,不下载', async () => {
+ const d = deps({ checkForUpdateAsync: checkAvailable() });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('unknown-id');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ });
+
+ it('有修复版(新 id)→ 下载并计一次尝试,但绝不 reload', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('fixed-update'),
+ fetchUpdateAsync: fetchedNewUpdate('fixed-update'),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('fetched');
+ expect(d.fetchUpdateAsync).toHaveBeenCalledOnce();
+ expect(d.recordReload).toHaveBeenCalledWith('fixed-update');
+ // 后台恢复只把 update 变成 pending,交给下一次冷启动;重启本身绝不在这里发生。
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('指针在 check 与 fetch 之间变了 → 按真正拿到手的 id 记账', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('first-fix'),
+ fetchUpdateAsync: fetchedNewUpdate('second-fix'),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('fetched');
+ expect(d.recordReload).toHaveBeenCalledWith('second-fix');
+ expect(d.recordReload).not.toHaveBeenCalledWith('first-fix');
+ });
+
+ it('拿到手的却是已知坏包(指针变化)→ 不记账,别把它的额度再放一次', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('first-fix'),
+ fetchUpdateAsync: fetchedNewUpdate('bad-update'),
+ isReloadBlocked: vi.fn(async (id: string) => id === 'bad-update'),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('known-bad');
+ expect(d.recordReload).not.toHaveBeenCalled();
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('fetch 什么都没落盘(isNew=false)→ up-to-date,不记一次尝试', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('fixed-update'),
+ fetchUpdateAsync: vi.fn(async () => ({ isNew: false })),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('up-to-date');
+ expect(d.recordReload).not.toHaveBeenCalled();
+ });
+
+ it('计数写不进去也算下载成功(只影响下次是否重下,不影响启动)', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('fixed-update'),
+ fetchUpdateAsync: fetchedNewUpdate('fixed-update'),
+ recordReload: vi.fn(async () => { throw new Error('storage full'); }),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('fetched');
+ });
+
+ it('下载超时 / 离线 → error,永不 reject,也不 reload', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('fixed-update'),
+ fetchUpdateAsync: vi.fn((): Promise<{ isNew: boolean }> => new Promise(() => {})),
+ });
+ await expect(runEmergencyOtaRecovery(d, { fetchTimeoutMs: 20 })).resolves.toBe('error');
+ expect(d.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('闸门状态读不出来 → error,不下载', async () => {
+ const d = deps({
+ checkForUpdateAsync: checkAvailable('fixed-update'),
+ isReloadBlocked: vi.fn(async () => { throw new Error('storage unavailable'); }),
+ });
+ await expect(runEmergencyOtaRecovery(d)).resolves.toBe('error');
+ expect(d.fetchUpdateAsync).not.toHaveBeenCalled();
+ });
+});
+
describe('withTimeout', () => {
it('按时 resolve 透传值', async () => {
await expect(withTimeout(Promise.resolve(42), 100)).resolves.toBe(42);
diff --git a/apps/mobile/src/update/startupOtaUpdate.ts b/apps/mobile/src/update/startupOtaUpdate.ts
index 515a32a359..da2c357e12 100644
--- a/apps/mobile/src/update/startupOtaUpdate.ts
+++ b/apps/mobile/src/update/startupOtaUpdate.ts
@@ -5,18 +5,51 @@
//
// 硬约束:任何异常 / 超时 / 离线一律 fail-open(返回 error,调用方直接放行进 App),绝不卡启动;
// 只有真正 fetch 到新 bundle(isNew)才 reload,避免无意义重启 / 循环。
+//
+// reload 之前还有三道防循环判定(某台设备实测被同一个 update 反复重启 33 次、永久卡在启动页,
+// 且不会自愈,只能清应用数据):
+// 1. emergency launch —— expo-updates 没能启动任何已下载 update、回落到包内 bundle。
+// 这种状态下 check 拿不到「当前 update」做比较,永远报有新版,reload 也回不到正常态,
+// 整道门直接跳过(热更不生效 好于 进不去 App)。
+// 2. fetch 到的 update 就是当前正在跑的那一个 → 没有任何理由重启。
+// 3. 跨 reload 的持久化闸门(otaReloadGuard):同一个 update 试满次数仍没装上就放弃。
-export type StartupOtaOutcome = 'skipped' | 'up-to-date' | 'reloading' | 'error';
+export type StartupOtaOutcome =
+ | 'skipped'
+ | 'up-to-date'
+ | 'reloading'
+ | 'error'
+ /** expo-updates 处于 emergency launch:本次启动完全不走热更。 */
+ | 'emergency-launch'
+ /** fetch 回来的就是当前运行的 update:不重启。 */
+ | 'already-running'
+ /** 同一个 update 反复装不上,被跨 reload 闸门拦下。 */
+ | 'reload-blocked';
export interface StartupOtaDeps {
/** 是否启用(自建变体 + 非 dev + expo-updates 可用);false 直接 skipped、不阻塞。 */
enabled: boolean;
/** 把 endpoint 清单解析出的 /manifest URL 写入 expo-updates;必须先于 check。 */
configureUpdateUrl: () => void;
- checkForUpdateAsync: () => Promise<{ isAvailable: boolean }>;
- fetchUpdateAsync: () => Promise<{ isNew: boolean }>;
+ checkForUpdateAsync: () => Promise<{
+ isAvailable: boolean;
+ /** isAvailable=true 时 expo-updates 必带;用它在下载前就判定要不要走这一轮。 */
+ manifest?: { id?: string };
+ }>;
+ fetchUpdateAsync: () => Promise<{ isNew: boolean; manifest?: { id?: string } }>;
/** 正常不返回(app 重启);测试里用 spy 断言被调用。 */
reloadAsync: () => Promise<void>;
+ /**
+ * `Updates.isEmergencyLaunch`:expo-updates 初始化失败、回落到包内 bundle 启动。
+ * 这是「下载的 update 装不上」这类本机坏状态最直接的信号。
+ */
+ isEmergencyLaunch: () => boolean;
+ /** `Updates.updateId`:当前正在运行的 update id(跑包内 bundle 时可能为 null)。 */
+ currentUpdateId: () => string | null;
+ /** 读跨 reload 闸门状态(实现见 otaReloadGuard)。 */
+ isReloadBlocked: (targetUpdateId: string) => Promise<boolean>;
+ /** reload 前记一次尝试;抛错即视为闸门不可用,本次不 reload。 */
+ recordReload: (targetUpdateId: string) => Promise<void>;
}
export interface StartupOtaOptions {
@@ -46,7 +79,10 @@ export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
/**
* 冷启动的 JS 热更闸门。
* - enabled=false → 'skipped'
+ * - emergency launch → 'emergency-launch'(不联网、不 reload)
* - 无可用更新 / fetch 非新 → 'up-to-date'
+ * - fetch 到的就是当前 update → 'already-running'
+ * - 同一 update 反复装不上 → 'reload-blocked'
* - fetch 到新 bundle → reloadAsync()(正常不返回)→ 'reloading'
* - 任何异常 / 超时 → 'error'(fail-open)
*/
@@ -56,14 +92,113 @@ export async function runStartupOtaUpdate(
): Promise<StartupOtaOutcome> {
if (!deps.enabled) return 'skipped';
try {
+ // emergency launch 下没有 launchedUpdate:check 必然报「有新版」,此时 reload 只会
+ // 回到同一个 emergency launch。这道**阻塞式**门直接放行进 App,不在这里联网——
+ // 后续的修复版下载由 runEmergencyOtaRecovery 在后台做(不 reload),见该函数。
+ // 放在 try 内:本函数对调用方承诺永不 reject,依赖自身抛错也必须落到 'error'。
+ if (deps.isEmergencyLaunch()) return 'emergency-launch';
deps.configureUpdateUrl();
const check = await withTimeout(deps.checkForUpdateAsync(), checkTimeoutMs);
if (!check.isAvailable) return 'up-to-date';
+ // check 就带回了目标 manifest,所以「同 id」「已被闸门拦下」都能在**下载之前**判掉。
+ // 否则正是需要被闸门救的那些设备,每次冷启动都要白等一次 fetch(最多 8s)才放行。
+ const decided = await decideByTargetId(deps, check.manifest?.id);
+ if (decided) return decided;
const fetched = await withTimeout(deps.fetchUpdateAsync(), fetchTimeoutMs);
if (!fetched.isNew) return 'up-to-date';
+ // 再判一次:check 与 fetch 之间服务端指针可能已经变,拿到手的未必是刚才那个 id。
+ // isNew=true 的 fetch 结果按 expo-updates 的类型必定带 manifest;真拿不到 id 时无从
+ // 计数,只能保持原行为(重启一次),不为这条理论上不可达的分支编造一个共享计数键。
+ const targetUpdateId = fetched.manifest?.id;
+ const decidedAfterFetch = await decideByTargetId(deps, targetUpdateId);
+ if (decidedAfterFetch) return decidedAfterFetch;
+ if (targetUpdateId) {
+ // 必须先落盘再 reload:反过来的话 reload 会打断写入,闸门永远合不上。
+ await deps.recordReload(targetUpdateId);
+ }
await deps.reloadAsync(); // 正常不返回:app 重启进新 bundle
return 'reloading';
} catch {
return 'error'; // fail-open:超时/离线/服务异常 → 放行,后台下载留给下次启动
}
}
+
+/** 后台恢复下载的结果(纯观测用;调用方不据此改变启动流程)。 */
+export type EmergencyOtaRecoveryOutcome =
+ | 'up-to-date'
+ /** check 没带回 id:无从判断是不是那个已知坏掉的包,不下载。 */
+ | 'unknown-id'
+ /** 线上指针还是那个已经证明装不上的 update:不重复下载。 */
+ | 'known-bad'
+ /** 已下载,等下次冷启动由原生层启动它(本函数绝不 reload)。 */
+ | 'fetched'
+ | 'error';
+
+/** 后台下载不阻塞启动,所以给足预算:整包 JS bundle 在移动网络下 8s 往往不够。 */
+const DEFAULT_RECOVERY_FETCH_TIMEOUT_MS = 60_000;
+
+/**
+ * emergency launch 后的**后台**恢复下载。
+ *
+ * 自建线 `checkAutomatically: 'NEVER'`,原生层不会自己检查更新;而 emergency launch 的
+ * 设备一直跑包内 bundle。若不做这件事,即使之后发了修复版热更,这些设备也永远拿不到,
+ * 只能靠用户清应用数据——普通用户不会知道要这么做。
+ *
+ * 安全边界(这三条共同保证它不可能变成第二个死循环):
+ * 1. **绝不 reload**——所以 deps 里没有 reloadAsync。下载完只是变成 pending update,
+ * 由下一次冷启动的原生层去选,本次启动的 UI 不受任何影响。
+ * 2. 已被闸门判定装不上的 id 不再下载(拦的是「已知坏掉的那一份」,不是「所有 emergency
+ * launch」);拿不到 id 时同样不下载,避免每次冷启动白下十几 MB。
+ * 3. 下载成功后计一次尝试,与正常路径共用同一个计数器:同一个 id 最多试
+ * MAX_OTA_RELOAD_ATTEMPTS 次就彻底不再碰它。
+ *
+ * 与 runStartupOtaUpdate 一样永不 reject。
+ */
+export async function runEmergencyOtaRecovery(
+ deps: Pick<
+ StartupOtaDeps,
+ 'configureUpdateUrl' | 'checkForUpdateAsync' | 'fetchUpdateAsync' | 'isReloadBlocked' | 'recordReload'
+ >,
+ {
+ checkTimeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
+ fetchTimeoutMs = DEFAULT_RECOVERY_FETCH_TIMEOUT_MS,
+ }: StartupOtaOptions = {},
+): Promise<EmergencyOtaRecoveryOutcome> {
+ try {
+ deps.configureUpdateUrl();
+ const check = await withTimeout(deps.checkForUpdateAsync(), checkTimeoutMs);
+ if (!check.isAvailable) return 'up-to-date';
+ const candidateId = check.manifest?.id;
+ if (!candidateId) return 'unknown-id';
+ if (await deps.isReloadBlocked(candidateId)) return 'known-bad';
+ const fetched = await withTimeout(deps.fetchUpdateAsync(), fetchTimeoutMs);
+ if (!fetched.isNew) return 'up-to-date'; // 什么都没落盘,不该记一次尝试
+ // 记账必须按**真正拿到手的** id:指针可能在 check 与 fetch 之间变过,记在过期的
+ // candidateId 上会让已经试满的那个坏包在下次冷启动又被放行一次(正常路径同样
+ // 在 fetch 之后重判,见 runStartupOtaUpdate)。
+ const fetchedId = fetched.manifest?.id ?? candidateId;
+ if (await deps.isReloadBlocked(fetchedId)) return 'known-bad';
+ // 计数放在下载成功之后:这里没有 reload 会打断落盘,而「下载到了」才算真的试过一次。
+ // 写失败只吞掉——后果仅是下次冷启动可能重下一次,不影响启动也不会循环。
+ await deps.recordReload(fetchedId).catch(() => undefined);
+ return 'fetched';
+ } catch {
+ return 'error';
+ }
+}
+
+/**
+ * 按目标 update id 判定本轮是否该直接结束(不下载、不重启)。返回 null 表示可以继续。
+ * 拿不到 id 时不做判定——无从比较也无从计数。
+ */
+async function decideByTargetId(
+ deps: StartupOtaDeps,
+ targetUpdateId: string | undefined,
+): Promise<StartupOtaOutcome | null> {
+ if (!targetUpdateId) return null;
+ // 服务端说「有新版」只代表相对它的认知是新的。真正决定要不要重启的是 id:与当前
+ // 运行的 update 同 id 却仍在重启,就是那台设备上观察到的死循环。
+ if (targetUpdateId === deps.currentUpdateId()) return 'already-running';
+ if (await deps.isReloadBlocked(targetUpdateId)) return 'reload-blocked';
+ return null;
+}
diff --git a/apps/mobile/src/update/useStartupOtaGate.ts b/apps/mobile/src/update/useStartupOtaGate.ts
index 7ec5d392e0..6943c17e09 100644
--- a/apps/mobile/src/update/useStartupOtaGate.ts
+++ b/apps/mobile/src/update/useStartupOtaGate.ts
@@ -5,8 +5,49 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import * as Updates from 'expo-updates';
import { IS_OTA_SELFHOST, OTA_SERVER_BASE_URL, REVIEW_MODE } from '@/config/env';
-import { runStartupOtaUpdate } from './startupOtaUpdate';
+import {
+ runEmergencyOtaRecovery,
+ runStartupOtaUpdate,
+ type StartupOtaOutcome,
+} from './startupOtaUpdate';
import { updateChannelRequestHeaders } from './canaryChannelStore';
+import {
+ clearOtaReloadGuardIfLaunched,
+ readOtaReloadGuard,
+ recordOtaReload,
+ shouldBlockOtaReload,
+} from './otaReloadGuard';
+
+/**
+ * 启动闸门链全部走完(业务树可用)后调用:只有当次 reload 的目标 update 确实成为当前
+ * 运行版本时才清闸门记录。放在这里而不是热更门放行处——被闸门拦下也会放行进 App,
+ * 那时清记录等于每次冷启动都重新放开一次 reload,循环只会变成「每启动闪一轮」。
+ */
+export function markStartupOtaLaunchSuccess(): void {
+ void clearOtaReloadGuardIfLaunched(Updates.updateId);
+}
+
+/**
+ * 启动时把「本次跑的是哪份 JS」钉进日志流。
+ *
+ * 曾经排查一台无限转圈的设备时,客户端一行相关日志都没有,只能靠原生 dev.expo.updates
+ * 日志反推当前启动的是包内 bundle 还是热更包。这一行让同类问题一眼可判,
+ * 沿用 mobile 既有 `console.*` + `[tag]` 前缀约定。
+ */
+function logStartupOtaLaunch(outcome: StartupOtaOutcome): void {
+ console.info(
+ '[ota] startup gate',
+ JSON.stringify({
+ outcome,
+ updateId: Updates.updateId,
+ isEmbeddedLaunch: Updates.isEmbeddedLaunch,
+ isEmergencyLaunch: Updates.isEmergencyLaunch,
+ emergencyLaunchReason: Updates.emergencyLaunchReason,
+ createdAt: Updates.createdAt?.toISOString() ?? null,
+ runtimeVersion: Updates.runtimeVersion,
+ }),
+ );
+}
export function useStartupOtaGate(isCanary = false): boolean {
// 仅自建变体 + 非 dev + expo-updates 运行时可用才走热更门;其余一律直接放行。
@@ -49,16 +90,32 @@ export function useStartupOtaGate(isCanary = false): boolean {
if (!enabled || started.current) return;
started.current = true; // 只冷启一次(不随 resume 重跑)
let cancelled = false;
- void runStartupOtaUpdate({
+ const otaDeps = {
enabled,
configureUpdateUrl,
checkForUpdateAsync: () => Updates.checkForUpdateAsync(),
fetchUpdateAsync: () => Updates.fetchUpdateAsync(),
reloadAsync: () => Updates.reloadAsync(),
- }).then((outcome) => {
+ isEmergencyLaunch: () => Updates.isEmergencyLaunch,
+ currentUpdateId: () => Updates.updateId,
+ isReloadBlocked: async (targetUpdateId: string) =>
+ shouldBlockOtaReload(await readOtaReloadGuard(), targetUpdateId),
+ recordReload: recordOtaReload,
+ };
+ void runStartupOtaUpdate(otaDeps).then((outcome) => {
+ logStartupOtaLaunch(outcome);
+ // emergency launch:门已放行,修复版热更改在后台找(绝不 reload,见
+ // runEmergencyOtaRecovery)。fire-and-forget——它的结果不影响本次启动,
+ // 只是让下一次冷启动有机会跑上修复版,而不是等用户去清应用数据。
+ if (outcome === 'emergency-launch') {
+ void runEmergencyOtaRecovery(otaDeps).then((recovery) => {
+ console.info('[ota] emergency recovery', JSON.stringify({ recovery }));
+ });
+ }
// 'reloading' 时 app 正在重启,保持 loading 门直到重启;其余情况放行进 App。
if (!cancelled && outcome !== 'reloading') setReady(true);
}).catch(() => {
+ logStartupOtaLaunch('error');
// runStartupOtaUpdate 设计为永不 reject;万一意外 reject,兜底 fail-open 放行,
// 否则 loading 门会永久卡住且不可自恢复(后续 OTA 也进不来),与全模块 fail-open 一致。
if (!cancelled) setReady(true);