Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 热更 reload 被拒时改为引导重开 App,并暴露应急启动原因 (#1149)
guyong-zapo0bd0c577c094
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex b962283533..3bf6730f14 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -277,6 +277,7 @@ export default function SettingsScreen() {checkOtaUpdate: () => Updates.checkForUpdateAsync(),fetchOtaUpdate: () => Updates.fetchUpdateAsync(),reload: () => Updates.reloadAsync(),+ isEmergencyLaunch: () => currentlyRunning.isEmergencyLaunch,onPhase: (phase) => setUpdatePhase(phase),});setUpdateOutcome(outcome);@@ -288,6 +289,9 @@ export default function SettingsScreen() {setUpdatePhase('uptodate');} else if (outcome.kind === 'reloading') {setUpdatePhase('downloading');+ } else if (outcome.kind === 'restart-required') {+ // 更新已经拿到了,只是本进程重启不了 —— 不是失败态,提示文案负责说明要手动重开。+ setUpdatePhase('uptodate');} else if (outcome.kind === 'busy') {setUpdatePhase('idle');} else {@@ -296,7 +300,14 @@ export default function SettingsScreen() {} finally {updateCheckInFlightRef.current = false;}- }, [bundleCheckEnabled, checkBundleUpdate, t, updateCheckEnabled, updatesEnabled]);+ }, [+ bundleCheckEnabled,+ checkBundleUpdate,+ currentlyRunning.isEmergencyLaunch,+ t,+ updateCheckEnabled,+ updatesEnabled,+ ]);const updateSelfDeviceNameDraft = useCallback((value: string) => {selfDeviceNameDraftRef.current = value;diff --git a/apps/mobile/src/__tests__/updateInfo.test.ts b/apps/mobile/src/__tests__/updateInfo.test.tsindex 9662c22fa9..34ef4a78be 100644--- a/apps/mobile/src/__tests__/updateInfo.test.ts+++ b/apps/mobile/src/__tests__/updateInfo.test.ts@@ -36,6 +36,55 @@ describe('buildMobileUpdateInfoRows', () => {});expect(rows.map((r) => r.value)).toEqual(['内置版本(随包)', '—', '—', '—', '1.0.0', OTA_VERIFY_MARKER]);});++ // 应急启动是"点检查更新报 reload 被拒"的唯一现场证据,必须能在设置页直接看到原因。+ it('appends the emergency launch reason when expo-updates fell back to the embedded bundle', () => {+ const rows = buildMobileUpdateInfoRows({+ isEmbeddedLaunch: false,+ updateId: undefined,+ channel: undefined,+ createdAt: undefined,+ runtimeVersion: '1.0.0',+ isEmergencyLaunch: true,+ emergencyLaunchReason: 'No launchable update was found.',+ });+ // 运行来源不能报「OTA 热更新」:应急启动跑的是内置 bundle,否则同一区块自相矛盾。+ expect(rows[0]).toEqual({+ id: 'source',+ label: '运行来源',+ value: '内置版本(应急启动,热更未生效)',+ });+ expect(rows.at(-1)).toEqual({+ id: 'emergencyLaunch',+ label: '应急启动',+ value: 'No launchable update was found.',+ });+ });++ it('falls back to a plain yes when the native layer gives no emergency launch reason', () => {+ const rows = buildMobileUpdateInfoRows({+ isEmbeddedLaunch: false,+ updateId: undefined,+ channel: undefined,+ createdAt: undefined,+ runtimeVersion: '1.0.0',+ isEmergencyLaunch: true,+ emergencyLaunchReason: null,+ });+ expect(rows.at(-1)?.value).toBe('是(本次运行内热更无法生效)');+ });++ it('omits the emergency launch row on a normal launch', () => {+ const rows = buildMobileUpdateInfoRows({+ isEmbeddedLaunch: true,+ updateId: 'embedded-id',+ channel: 'production',+ createdAt: undefined,+ runtimeVersion: '1.0.0',+ isEmergencyLaunch: false,+ });+ expect(rows.map((r) => r.id)).not.toContain('emergencyLaunch');+ });});describe('currentMobileOtaVersion', () => {@@ -50,4 +99,14 @@ describe('currentMobileOtaVersion', () => {expect(currentMobileOtaVersion({ isEmbeddedLaunch: true, updateId: 'embedded-id' })).toBe('随整包');expect(currentMobileOtaVersion({ isEmbeddedLaunch: false, updateId: undefined })).toBe('未知');});++ // 应急启动下 updateId 空、isEmbeddedLaunch 也是 false,但跑的确定是内置 bundle:+ // 显示"未知"会被误读成读不到版本号,这里必须说清是内置 bundle 且热更没生效。+ it('names the embedded fallback instead of unknown on an emergency launch', () => {+ expect(currentMobileOtaVersion({+ isEmbeddedLaunch: false,+ updateId: undefined,+ isEmergencyLaunch: true,+ })).toBe('随整包(热更未生效)');+ });});diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.jsonindex 050f372e39..60623677d3 100644--- a/apps/mobile/src/i18n/locales/en/settings.json+++ b/apps/mobile/src/i18n/locales/en/settings.json@@ -31,6 +31,7 @@"upToDate": "Already up to date","bundleUpToDateNoOta": "App package is up to date; this version does not support OTA updates","downloadedRestarting": "Update downloaded, restarting",+ "downloadedRestartRequired": "Update downloaded. Fully quit the app and reopen it to apply.","bundleCheckFailed": "Could not check for app package updates. Try again later.","checkFailedDetail": "Update check failed: {{detail}}","checkFailed": "Update check failed. Try again later."@@ -76,15 +77,19 @@},"updateInfo": {"embedded": "With app package",+ "embeddedFallback": "With app package (OTA not applied)","unknown": "Unknown","source": "Running Source","sourceEmbedded": "Embedded (with app package)",+ "sourceEmergencyFallback": "Embedded (emergency launch; OTA not applied)","sourceOta": "OTA update","updateId": "Update ID","updatedAt": "Updated At","channel": "Channel","runtime": "Runtime",- "otaMarker": "OTA Marker"+ "otaMarker": "OTA Marker",+ "emergencyLaunch": "Emergency Launch",+ "emergencyLaunchYes": "Yes (OTA cannot apply in this run)"},"legal": {"sectionTitle": "Legal",diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.jsonindex 3e9534d7a9..3b047a0d2f 100644--- a/apps/mobile/src/i18n/locales/ja/settings.json+++ b/apps/mobile/src/i18n/locales/ja/settings.json@@ -31,6 +31,7 @@"upToDate": "すでに最新の状態です","bundleUpToDateNoOta": "アプリ本体は最新です。このバージョンは OTA 更新に対応していません","downloadedRestarting": "更新をダウンロードしました。再起動しています",+ "downloadedRestartRequired": "更新をダウンロードしました。アプリを完全に終了して再度開くと適用されます。","bundleCheckFailed": "アプリ本体の更新を確認できませんでした。しばらくしてからもう一度お試しください。","checkFailedDetail": "更新の確認に失敗しました:{{detail}}","checkFailed": "更新の確認に失敗しました。しばらくしてからもう一度お試しください。"@@ -76,15 +77,19 @@},"updateInfo": {"embedded": "アプリ本体と同梱",+ "embeddedFallback": "アプリ本体と同梱(OTA 未適用)","unknown": "不明","source": "実行ソース","sourceEmbedded": "内蔵バージョン (同梱)",+ "sourceEmergencyFallback": "内蔵バージョン (緊急起動・OTA 未適用)","sourceOta": "OTA 更新","updateId": "更新 ID","updatedAt": "更新日時","channel": "Channel","runtime": "Runtime",- "otaMarker": "OTA マーカー"+ "otaMarker": "OTA マーカー",+ "emergencyLaunch": "緊急起動",+ "emergencyLaunchYes": "はい(この起動では OTA を適用できません)"},"legal": {"sectionTitle": "法的情報",diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.jsonindex 7c920616d1..f9c5b2eb26 100644--- a/apps/mobile/src/i18n/locales/ko/settings.json+++ b/apps/mobile/src/i18n/locales/ko/settings.json@@ -31,6 +31,7 @@"upToDate": "이미 최신 버전입니다","bundleUpToDateNoOta": "앱 패키지는 최신입니다. 현재 버전은 OTA 업데이트를 지원하지 않습니다","downloadedRestarting": "업데이트를 다운로드했습니다. 다시 시작하는 중",+ "downloadedRestartRequired": "업데이트를 다운로드했습니다. 앱을 완전히 종료한 뒤 다시 열면 적용됩니다.","bundleCheckFailed": "앱 패키지 업데이트를 확인할 수 없습니다. 잠시 후 다시 시도해 주세요.","checkFailedDetail": "업데이트 확인에 실패했습니다: {{detail}}","checkFailed": "업데이트 확인에 실패했습니다. 잠시 후 다시 시도해 주세요."@@ -76,15 +77,19 @@},"updateInfo": {"embedded": "앱 패키지 포함",+ "embeddedFallback": "앱 패키지 포함 (OTA 미적용)","unknown": "알 수 없음","source": "실행 소스","sourceEmbedded": "내장 버전 (패키지 포함)",+ "sourceEmergencyFallback": "내장 버전 (긴급 실행, OTA 미적용)","sourceOta": "OTA 업데이트","updateId": "업데이트 ID","updatedAt": "업데이트 시간","channel": "Channel","runtime": "Runtime",- "otaMarker": "OTA 마커"+ "otaMarker": "OTA 마커",+ "emergencyLaunch": "긴급 실행",+ "emergencyLaunchYes": "예 (이번 실행에서는 OTA를 적용할 수 없음)"},"legal": {"sectionTitle": "법적 정보",diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.jsonindex fe9e5de64a..0c3865a524 100644--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json@@ -31,6 +31,7 @@"upToDate": "已是最新版本","bundleUpToDateNoOta": "整包已是最新,当前版本不支持热更新","downloadedRestarting": "更新已下载,正在重启",+ "downloadedRestartRequired": "更新已下载,完全退出 App 后重新打开即可生效","bundleCheckFailed": "无法检查整包更新,请稍后重试","checkFailedDetail": "检查更新失败:{{detail}}","checkFailed": "检查更新失败,请稍后重试"@@ -76,15 +77,19 @@},"updateInfo": {"embedded": "随整包",+ "embeddedFallback": "随整包(热更未生效)","unknown": "未知","source": "运行来源","sourceEmbedded": "内置版本(随包)",+ "sourceEmergencyFallback": "内置版本(应急启动,热更未生效)","sourceOta": "OTA 热更新","updateId": "更新 ID","updatedAt": "更新时间","channel": "Channel","runtime": "Runtime",- "otaMarker": "热更标记"+ "otaMarker": "热更标记",+ "emergencyLaunch": "应急启动",+ "emergencyLaunchYes": "是(本次运行内热更无法生效)"},"legal": {"sectionTitle": "备案信息",diff --git a/apps/mobile/src/settings/updateInfo.ts b/apps/mobile/src/settings/updateInfo.tsindex fde6a64cee..89ac2b532b 100644--- a/apps/mobile/src/settings/updateInfo.ts+++ b/apps/mobile/src/settings/updateInfo.ts@@ -17,14 +17,24 @@ export interface MobileUpdateInfoRow {type MobileUpdateInfoInput = Pick<CurrentlyRunningInfo,'updateId' | 'channel' | 'createdAt' | 'isEmbeddedLaunch' | 'runtimeVersion'->;+> & Partial<Pick<CurrentlyRunningInfo, 'isEmergencyLaunch' | 'emergencyLaunchReason'>>;-/** 当前实际运行的热更版本:OTA 用短 updateId,内置 bundle 明确标成随整包。 */+/**+ * 当前实际运行的热更版本:OTA 用短 updateId,内置 bundle 明确标成随整包。+ *+ * emergency launch(expo-updates 没找到可启动 update、退回内置 bundle)下 updateId 为空且+ * isEmbeddedLaunch 也是 false —— 这不是"未知",而是确定跑着内置 bundle 且本次运行内热更+ * 无法生效(reload 会被原生层拒绝)。单独出文案,免得看到"未知"以为是读不到版本。+ */export function currentMobileOtaVersion(- currentlyRunning: Pick<CurrentlyRunningInfo, 'updateId' | 'isEmbeddedLaunch'>,+ currentlyRunning: Pick<CurrentlyRunningInfo, 'updateId' | 'isEmbeddedLaunch'>+ & Partial<Pick<CurrentlyRunningInfo, 'isEmergencyLaunch'>>,): string {if (currentlyRunning.isEmbeddedLaunch) return i18n.t('settings.updateInfo.embedded');- return currentlyRunning.updateId?.trim().slice(0, 8) || i18n.t('settings.updateInfo.unknown');+ const shortId = currentlyRunning.updateId?.trim().slice(0, 8);+ if (shortId) return shortId;+ if (currentlyRunning.isEmergencyLaunch) return i18n.t('settings.updateInfo.embeddedFallback');+ return i18n.t('settings.updateInfo.unknown');}/**@@ -33,24 +43,37 @@ export function currentMobileOtaVersion(* - 运行来源:isEmbeddedLaunch → 内置(随包),否则 OTA 热更新;* - 更新 ID:有就取前 8 位(canonical UUID 全小写),无(dev / expo-updates 未启用)显示 —;* - 更新时间:createdAt 本地时间 YYYY-MM-DD HH:mm,无则 —;- * - Channel / Runtime:trim 后展示,空则 —。+ * - Channel / Runtime:trim 后展示,空则 —;+ * - 应急启动:仅 isEmergencyLaunch 时追加一行,带上原生给的原因(诊断"热更点了没反应"的第一现场)。*/export function buildMobileUpdateInfoRows(currentlyRunning: MobileUpdateInfoInput): MobileUpdateInfoRow[] {const updateId = currentlyRunning.updateId;const createdAt = currentlyRunning.createdAt;+ const emergencyReason = currentlyRunning.emergencyLaunchReason?.trim();return [{id: 'source',label: i18n.t('settings.updateInfo.source'),+ // 应急启动跑的也是内置 bundle(只是没走 embedded update 记录,isEmbeddedLaunch 为 false),+ // 报「OTA 热更新」会跟同一区块里的应急启动行、以及「热更版本」自相矛盾。value: currentlyRunning.isEmbeddedLaunch? i18n.t('settings.updateInfo.sourceEmbedded')- : i18n.t('settings.updateInfo.sourceOta'),+ : currentlyRunning.isEmergencyLaunch+ ? i18n.t('settings.updateInfo.sourceEmergencyFallback')+ : i18n.t('settings.updateInfo.sourceOta'),},{ id: 'updateId', label: i18n.t('settings.updateInfo.updateId'), value: updateId ? updateId.slice(0, 8) : '—' },{ id: 'updatedAt', label: i18n.t('settings.updateInfo.updatedAt'), value: createdAt ? formatMobileUpdateTime(createdAt) : '—' },{ id: 'channel', label: i18n.t('settings.updateInfo.channel'), value: currentlyRunning.channel?.trim() || '—' },{ id: 'runtimeVersion', label: i18n.t('settings.updateInfo.runtime'), value: currentlyRunning.runtimeVersion?.trim() || '—' },{ id: 'otaMarker', label: i18n.t('settings.updateInfo.otaMarker'), value: OTA_VERIFY_MARKER },+ ...(currentlyRunning.isEmergencyLaunch+ ? [{+ id: 'emergencyLaunch',+ label: i18n.t('settings.updateInfo.emergencyLaunch'),+ value: emergencyReason || i18n.t('settings.updateInfo.emergencyLaunchYes'),+ }]+ : []),];}diff --git a/apps/mobile/src/update/manualUpdateCheck.test.ts b/apps/mobile/src/update/manualUpdateCheck.test.tsindex a01f44733b..77c932788b 100644--- a/apps/mobile/src/update/manualUpdateCheck.test.ts+++ b/apps/mobile/src/update/manualUpdateCheck.test.ts@@ -21,8 +21,9 @@ function deps(overrides: Partial<ManualUpdateCheckDeps> = {}): ManualUpdateCheckreturn {otaEnabled: true,checkOtaUpdate: vi.fn(async () => ({ isAvailable: false })),- fetchOtaUpdate: vi.fn(async () => undefined),+ fetchOtaUpdate: vi.fn(async () => ({ isNew: true })),reload: vi.fn(async () => undefined),+ isEmergencyLaunch: vi.fn(() => false),onPhase: vi.fn(),...overrides,};@@ -87,6 +88,58 @@ describe('runManualUpdateCheck', () => {expect(input.checkOtaUpdate).not.toHaveBeenCalled();});+ // emergency launch(没有 launchedUpdate)时 reloadAsync 会被原生层拒绝,但 bundle 已落盘:+ // 这不是一次失败的检查,必须导向"重开 App 生效",否则用户只看到一条无从下手的红字报错。+ it('asks for a manual restart when an emergency launch blocks reloading the downloaded bundle', async () => {+ const input = deps({+ checkOtaUpdate: vi.fn(async () => ({ isAvailable: true })),+ fetchOtaUpdate: vi.fn(async () => ({ isNew: true })),+ reload: vi.fn(async () => {+ throw new Error("Call to function 'ExpoUpdates.reload' has been rejected.");+ }),+ isEmergencyLaunch: vi.fn(() => true),+ });++ await expect(runManualUpdateCheck(input)).resolves.toEqual({ kind: 'restart-required' });+ expect(input.fetchOtaUpdate).toHaveBeenCalledOnce();+ expect(input.reload).toHaveBeenCalledOnce();+ });++ it('still reports a failure when reload fails without any downloaded bundle', async () => {+ const input = deps({+ checkOtaUpdate: vi.fn(async () => ({ isAvailable: true })),+ fetchOtaUpdate: vi.fn(async () => ({ isNew: false })),+ reload: vi.fn(async () => {+ throw new Error('reload rejected');+ }),+ isEmergencyLaunch: vi.fn(() => true),+ });++ await expect(runManualUpdateCheck(input)).resolves.toEqual({+ kind: 'error',+ reason: 'ota-check',+ detail: 'reload rejected',+ });+ });++ // 非应急启动下的 reload 失败原因未知,原始详情是唯一线索:不能被重启指引盖掉。+ it('keeps the reload failure detail when the app is not in an emergency launch', async () => {+ const input = deps({+ checkOtaUpdate: vi.fn(async () => ({ isAvailable: true })),+ fetchOtaUpdate: vi.fn(async () => ({ isNew: true })),+ reload: vi.fn(async () => {+ throw new Error('Could not reload application; activity is null');+ }),+ isEmergencyLaunch: vi.fn(() => false),+ });++ await expect(runManualUpdateCheck(input)).resolves.toEqual({+ kind: 'error',+ reason: 'ota-check',+ detail: 'Could not reload application; activity is null',+ });+ });+it('keeps OTA failure details unlocalized until the settings page renders them', async () => {const input = deps({checkOtaUpdate: vi.fn(async () => {@@ -103,6 +156,12 @@ describe('runManualUpdateCheck', () => {});describe('manualUpdateCheckMessage', () => {+ 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 }))+ .toBe('更新已下载,完全退出 App 后重新打开即可生效');+ });+it('uses the current language for an already completed TestFlight check', async () => {const outcome = { kind: 'up-to-date' } as const;diff --git a/apps/mobile/src/update/manualUpdateCheck.ts b/apps/mobile/src/update/manualUpdateCheck.tsindex c6cc0ebe11..68927a0d63 100644--- a/apps/mobile/src/update/manualUpdateCheck.ts+++ b/apps/mobile/src/update/manualUpdateCheck.ts@@ -17,6 +17,8 @@ export type ManualUpdateCheckOutcome =| { kind: 'up-to-date' }| { kind: 'ota-unavailable' }| { kind: 'reloading' }+ /** 新 bundle 已下载但重启失败:它会在下次冷启动生效,只能引导用户手动重开。 */+ | { kind: 'restart-required' }| { kind: 'busy' }| { kind: 'error'; reason: 'bundle-check' | 'ota-check'; detail?: string };@@ -26,8 +28,14 @@ export interface ManualUpdateCheckDeps {checkBundleUpdate?: () => Promise<BundleUpdateCheckOutcome>;otaEnabled: boolean;checkOtaUpdate: () => Promise<{ isAvailable: boolean }>;- fetchOtaUpdate: () => Promise<unknown>;+ /** isNew 表示确实落盘了一个新 bundle(reload 失败时用它区分"已下载待重启"与"什么都没拿到")。 */+ fetchOtaUpdate: () => Promise<{ isNew: boolean }>;reload: () => Promise<void>;+ /**+ * expo-updates 是否处于 emergency launch(没有 launchedUpdate,reload 必被原生层拒绝)。+ * 只有这个状态才把 reload 失败判成"已下载待重启";其余 reload 失败仍按失败报,保留详情。+ */+ isEmergencyLaunch: () => boolean;onPhase: (phase: ManualUpdateCheckPhase) => void;}@@ -41,6 +49,7 @@ export async function runManualUpdateCheck({checkOtaUpdate,fetchOtaUpdate,reload,+ isEmergencyLaunch,onPhase,}: ManualUpdateCheckDeps): Promise<ManualUpdateCheckOutcome> {onPhase('checking');@@ -59,14 +68,20 @@ export async function runManualUpdateCheck({if (!otaEnabled) return { kind: 'ota-unavailable' };+ let fetchedNewBundle = false;try {const ota = await checkOtaUpdate();if (!ota.isAvailable) return { kind: 'up-to-date' };onPhase('downloading');- await fetchOtaUpdate();+ const fetched = await fetchOtaUpdate();+ fetchedNewBundle = fetched.isNew;await reload();return { kind: 'reloading' };} catch (error) {+ // emergency launch(没有 launchedUpdate)下 reload 必被原生层拒绝,而 bundle 已经落盘、+ // 下次冷启动就会生效:这不是一次失败的检查,报"检查更新失败"只会让用户无从下手。+ // 反过来,其它原因的 reload 失败不套用这条 —— 那种情况原始详情才是唯一线索,不能吞掉。+ if (fetchedNewBundle && isEmergencyLaunch()) return { kind: 'restart-required' };const detail = error instanceof Error ? error.message.trim() : String(error).trim();return {kind: 'error',@@ -97,6 +112,8 @@ export function manualUpdateCheckMessage(: 'settings.version.bundleUpToDateNoOta');case 'reloading':return t('settings.version.downloadedRestarting');+ case 'restart-required':+ return t('settings.version.downloadedRestartRequired');case 'error':if (outcome.reason === 'bundle-check') return t('settings.version.bundleCheckFailed');return outcome.detail