Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): resume interrupted Android update downloads (#6600)
Chris Zhangbdcd37d4c6a5
diff --git a/apps/mobile/src/update/androidInstallController.ts b/apps/mobile/src/update/androidInstallController.tsindex 785869de71..80d29450a7 100644--- a/apps/mobile/src/update/androidInstallController.ts+++ b/apps/mobile/src/update/androidInstallController.ts@@ -15,7 +15,7 @@ export interface AndroidInstallIO {supported(): boolean;hasPermission(): Promise<boolean>;requestPermission(): Promise<boolean>;- download(url: string, signal: AbortSignal, progress: (value: number | null) => void): Promise<string>;+ download(url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string): Promise<string>;install(uri: string, version: string, signal: AbortSignal): Promise<void>;remove(uri: string): Promise<void>;openBrowser(url: string): Promise<void>;@@ -97,7 +97,7 @@ export class AndroidInstallController {this.update({ phase: 'downloading', target, progress: null });const file = await this.io.download(target.installUrl, operation.signal, (progress) => {if (current()) this.update({ phase: 'downloading', target, progress });- });+ }, target.version);if (!current()) { await this.io.remove(file).catch(() => undefined); return; }this.file = file;this.handedToInstaller = false;diff --git a/apps/mobile/src/update/androidInstaller.test.ts b/apps/mobile/src/update/androidInstaller.test.tsindex 03f1c3d3c6..74d63f08f5 100644--- a/apps/mobile/src/update/androidInstaller.test.ts+++ b/apps/mobile/src/update/androidInstaller.test.ts@@ -1,136 +1,188 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const mocks = vi.hoisted(() => {- const native = {- isSupported: vi.fn(() => true),- hasPermission: vi.fn(async () => true),- requestPermission: vi.fn(async () => true),- install: vi.fn(async () => undefined),- };- return {- native,- state: { currentState: 'active' },- appStateListener: undefined as ((state: string) => void) | undefined,- onProgress: undefined as ((data: { totalBytesWritten: number; totalBytesExpectedToWrite: number }) => void) | undefined,- file: '',- download: vi.fn<() => Promise<{ status: number } | undefined>>(),- cancel: vi.fn(async () => undefined),- remove: vi.fn(async () => undefined),- unsubscribe: vi.fn(),- browser: vi.fn(async () => undefined),- };-});+const mocks = vi.hoisted(() => ({+ native: { isSupported: vi.fn(() => true), hasPermission: vi.fn(async () => true),+ requestPermission: vi.fn(async () => true), install: vi.fn(async (_file: string, _version: string) => undefined) },+ state: { currentState: 'active' },+ appStateListener: undefined as ((state: string) => void) | undefined,+ onProgress: undefined as ((data: { bytesWritten: number; totalBytes: number }) => void) | undefined,+ file: '', resumeData: undefined as string | undefined,+ files: new Map<string, number>(),+ download: vi.fn<() => Promise<object | null>>(),+ resolveDownload: undefined as ((value: object | null) => void) | undefined,+ rejectDownload: undefined as ((error: Error) => void) | undefined,+ cancel: vi.fn(), release: vi.fn(), unsubscribe: vi.fn(), browser: vi.fn(async () => undefined),+ remove: vi.fn(async (file: string) => { mocks.files.delete(file); }),+}));vi.mock('react-native', () => ({Platform: { OS: 'android' },- AppState: {- get currentState() { return mocks.state.currentState; },+ AppState: { get currentState() { return mocks.state.currentState; },addEventListener: (_name: string, callback: (state: string) => void) => {- mocks.appStateListener = callback;- return { remove: mocks.unsubscribe };- },- },+ mocks.appStateListener = callback; return { remove: mocks.unsubscribe };+ } },Linking: { openURL: mocks.browser },}));vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => mocks.native }));vi.mock('expo-file-system/legacy', () => ({- cacheDirectory: 'file:///cache/',- makeDirectoryAsync: vi.fn(async () => undefined),+ cacheDirectory: 'file:///cache/', makeDirectoryAsync: vi.fn(async () => undefined),readDirectoryAsync: vi.fn(async () => []),- getInfoAsync: vi.fn(),+ getInfoAsync: vi.fn(async (file: string) => mocks.files.has(file)+ ? { exists: true, isDirectory: false, size: mocks.files.get(file), modificationTime: Date.now() / 1000 }+ : { exists: false }),deleteAsync: mocks.remove,- createDownloadResumable: (_url: string, file: string, _options: object, onProgress: typeof mocks.onProgress) => {- mocks.file = file;- mocks.onProgress = onProgress;- return { downloadAsync: mocks.download, cancelAsync: mocks.cancel };+ moveAsync: vi.fn(async ({ from, to }: { from: string; to: string }) => {+ mocks.files.set(to, mocks.files.get(from) ?? 0); mocks.files.delete(from);+ }),+}));+vi.mock('expo-file-system', () => ({+ File: class { constructor(public uri: string) {} },+ DownloadTask: class {+ constructor(_url: string, file: { uri: string }, options: { onProgress: typeof mocks.onProgress }) {+ mocks.file = file.uri; mocks.onProgress = options.onProgress; mocks.resumeData = undefined;+ }+ static fromSavable(saved: { url: string; fileUri: string; resumeData: string }, options: { onProgress: typeof mocks.onProgress }) {+ const task = new this(saved.url, { uri: saved.fileUri }, options);+ mocks.resumeData = saved.resumeData; return task;+ }+ downloadAsync = mocks.download;+ resumeAsync = mocks.download;+ state = 'active';+ pauseAsync = mocks.cancel;+ release = mocks.release;},}));import { androidInstaller } from './androidInstaller';const target = { installUrl: 'https://updates.example.invalid/app.apk', version: '1.2.3' };-const settle = async () => { for (let i = 0; i < 40; i++) await Promise.resolve(); };-+const settle = async () => { for (let i = 0; i < 80; i++) await Promise.resolve(); };+const pending = () => mocks.download.mockImplementation(() => new Promise((resolve, reject) => { mocks.resolveDownload = resolve; mocks.rejectDownload = reject; }));beforeEach(() => {- vi.useFakeTimers();- vi.clearAllMocks();- mocks.state.currentState = 'active';- mocks.download.mockResolvedValue({ status: 200 });-});-afterEach(async () => {- androidInstaller.close();- await settle();- vi.useRealTimers();+ vi.useFakeTimers(); vi.clearAllMocks(); mocks.files.clear();+ mocks.state.currentState = 'active'; mocks.rejectDownload = undefined; mocks.resolveDownload = undefined;+ mocks.download.mockResolvedValue({});+ mocks.cancel.mockImplementation(async () => mocks.resolveDownload?.(null));});+afterEach(async () => { androidInstaller.close(); await settle(); vi.useRealTimers(); });+// Unit regression: the public installer previously deleted partial APKs on failure.+// Seed on-disk bytes (including a previous process's file) and observe the resume+// offset and installation through start/retry, not just storage helper calls.describe('Android installer IO', () => {- it('downloads to the private update cache and retains the APK for the system installer', async () => {- androidInstaller.start(target);- await settle();- expect(mocks.file).toMatch(/^file:\/\/\/cache\/cindy-updates\/update-.*\.apk$/);- expect(mocks.native.install).toHaveBeenCalledWith(mocks.file, target.version);+ it('retains the downloaded APK for the system installer', async () => {+ androidInstaller.start(target); await settle();+ expect(mocks.file).toMatch(/^file:\/\/\/cache\/cindy-updates\/update-resume-[a-f0-9]{64}\.apk$/);+ expect(mocks.native.install).toHaveBeenCalledWith(expect.stringMatching(/\/update-[0-9]+-[a-z0-9]+\.apk$/), target.version);+ expect(androidInstaller.getSnapshot().phase).toBe('ready');expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.release).toHaveBeenCalledOnce();+ mocks.onProgress!({ bytesWritten: 100, totalBytes: 100 });expect(androidInstaller.getSnapshot().phase).toBe('ready');- mocks.onProgress!({ totalBytesWritten: 100, totalBytesExpectedToWrite: 100 });expect(vi.getTimerCount()).toBe(0);- androidInstaller.close();- expect(mocks.remove).not.toHaveBeenCalled();});- it('HTTP failures never launch installation and remove partial bytes', async () => {- mocks.download.mockResolvedValue({ status: 503 });- androidInstaller.start(target);- await settle();- expect(mocks.native.install).not.toHaveBeenCalled();- expect(mocks.remove).toHaveBeenCalledWith(mocks.file, { idempotent: true });+ it('never overwrites a completed file held by the system installer', async () => {+ androidInstaller.start(target); await settle();+ const handedOff = mocks.native.install.mock.calls[0][0];+ expect(mocks.files.has(handedOff)).toBe(true);+ androidInstaller.close(); await settle();+ androidInstaller.start(target); await settle();+ expect(mocks.resumeData).toBeUndefined();+ expect(mocks.files.has(handedOff)).toBe(true);+ expect(mocks.native.install.mock.calls[1][0]).not.toBe(handedOff);+ });++ it('retains interrupted bytes and resumes from disk on retry', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.files.set(mocks.file, 256);+ mocks.rejectDownload!(new Error('connection lost')); await settle();expect(androidInstaller.getSnapshot().phase).toBe('error');+ expect(mocks.native.install).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+ mocks.download.mockResolvedValue({}); androidInstaller.retry(); await settle();+ expect(mocks.resumeData).toBe('256');+ expect(androidInstaller.getSnapshot().phase).toBe('ready');});- it('stalled downloads time out, cancel the native transfer and expose browser fallback', async () => {- mocks.download.mockImplementation(() => new Promise(() => undefined));- androidInstaller.start(target);- await settle();- expect(androidInstaller.getSnapshot().phase).toBe('downloading');- await vi.advanceTimersByTimeAsync(90_000);- expect(mocks.cancel).toHaveBeenCalled();- expect(mocks.remove).toHaveBeenCalledWith(mocks.file, { idempotent: true });+ it('cancels stalled transfers but keeps their bytes available for retry', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.files.set(mocks.file, 128);+ await vi.advanceTimersByTimeAsync(90_000); await settle();+ expect(mocks.cancel).toHaveBeenCalledOnce();+ expect(mocks.remove).not.toHaveBeenCalled();expect(androidInstaller.getSnapshot().phase).toBe('error');await androidInstaller.browser();expect(mocks.browser).toHaveBeenCalledWith(target.installUrl);});- it('reports unknown length without fake percentages; progress keeps a live download running', async () => {- mocks.download.mockImplementation(() => new Promise(() => undefined));- androidInstaller.start(target);- await settle();- mocks.onProgress!({ totalBytesWritten: 20, totalBytesExpectedToWrite: -1 });+ it('reopens with persisted bytes and never shares them with another release', async () => {+ pending(); androidInstaller.start(target); await settle();+ const original = mocks.file; mocks.files.set(original, 512);+ androidInstaller.close(); await settle();+ mocks.download.mockResolvedValue({}); androidInstaller.start(target); await settle();+ expect(mocks.file).toBe(original); expect(mocks.resumeData).toBe('512');+ androidInstaller.close(); await settle();+ androidInstaller.start({ ...target, version: '1.2.4' }); await settle();+ expect(mocks.file).not.toBe(original); expect(mocks.resumeData).toBeUndefined();+ });++ it('waits for a cancelled native writer before immediately reopening', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.cancel.mockImplementation(async () => undefined);+ androidInstaller.close(); androidInstaller.start(target); await settle();+ expect(mocks.download).toHaveBeenCalledTimes(1);+ mocks.files.set(mocks.file, 333);+ mocks.download.mockResolvedValue({}); mocks.rejectDownload!(new Error('cancelled')); await settle();+ expect(mocks.download).toHaveBeenCalledTimes(2);+ expect(mocks.resumeData).toBe('333');+ expect(androidInstaller.getSnapshot().phase).toBe('ready');+ });++ it('retries an unsatisfiable range from zero once', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.files.set(mocks.file, 99); androidInstaller.close(); await settle();+ mocks.download.mockRejectedValueOnce(new Error('HTTP 416')).mockResolvedValueOnce({});+ androidInstaller.start(target); await settle();+ expect(mocks.remove).toHaveBeenCalledWith(mocks.file, { idempotent: true });+ expect(mocks.resumeData).toBeUndefined();+ expect(androidInstaller.getSnapshot().phase).toBe('ready');+ });++ it('HTTP failures never launch installation or discard the previous partial', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.files.set(mocks.file, 256);+ mocks.rejectDownload!(new Error('connection lost')); await settle();+ mocks.download.mockRejectedValue(new Error('HTTP 503'));+ androidInstaller.retry(); await settle();+ expect(mocks.files.get(mocks.file)).toBe(256);+ expect(mocks.native.install).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(androidInstaller.getSnapshot().phase).toBe('error');+ });++ it('reports unknown length without fake percentages and refreshes the stall timer', async () => {+ pending(); androidInstaller.start(target); await settle();+ mocks.onProgress!({ bytesWritten: 20, totalBytes: -1 });expect(androidInstaller.getSnapshot().progress).toBeNull();await vi.advanceTimersByTimeAsync(60_000);- mocks.onProgress!({ totalBytesWritten: 50, totalBytesExpectedToWrite: 100 });+ mocks.onProgress!({ bytesWritten: 50, totalBytes: 100 });expect(androidInstaller.getSnapshot().progress).toBe(0.5);await vi.advanceTimersByTimeAsync(60_000);expect(androidInstaller.getSnapshot().phase).toBe('downloading');- androidInstaller.close();- await settle();+ androidInstaller.close(); await settle();expect(mocks.native.install).not.toHaveBeenCalled();- expect(mocks.remove).toHaveBeenCalledWith(mocks.file, { idempotent: true });+ expect(mocks.remove).not.toHaveBeenCalled();});- it('does not open installation over another app; resuming launches the downloaded update', async () => {- mocks.state.currentState = 'background';- androidInstaller.start(target);- await settle();+ it('waits for the foreground before opening installation', async () => {+ mocks.state.currentState = 'background'; androidInstaller.start(target); await settle();expect(mocks.native.install).not.toHaveBeenCalled();- mocks.state.currentState = 'active';- mocks.appStateListener!('active');- await settle();+ mocks.state.currentState = 'active'; mocks.appStateListener!('active'); await settle();expect(mocks.native.install).toHaveBeenCalledOnce();expect(mocks.unsubscribe).toHaveBeenCalledOnce();});- it('cancelling a background handoff removes the listener and prevents later installation', async () => {- mocks.state.currentState = 'background';- androidInstaller.start(target);- await settle();- androidInstaller.close();- await settle();+ it('cancelling a background handoff prevents later installation', async () => {+ mocks.state.currentState = 'background'; androidInstaller.start(target); await settle();+ androidInstaller.close(); await settle();expect(mocks.unsubscribe).toHaveBeenCalledOnce();expect(mocks.native.install).not.toHaveBeenCalled();expect(androidInstaller.getSnapshot().phase).toBe('idle');diff --git a/apps/mobile/src/update/androidInstaller.ts b/apps/mobile/src/update/androidInstaller.tsindex 37c4dac6f6..d65e0c6dfb 100644--- a/apps/mobile/src/update/androidInstaller.ts+++ b/apps/mobile/src/update/androidInstaller.ts@@ -1,6 +1,9 @@import { AppState, Linking, Platform } from 'react-native';import { requireOptionalNativeModule } from 'expo-modules-core';import * as FileSystem from 'expo-file-system/legacy';+import { DownloadTask, File } from 'expo-file-system';+import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex } from '@noble/hashes/utils';import { AndroidInstallController } from './androidInstallController';interface NativeInstaller {@@ -29,58 +32,96 @@ async function waitForForeground(signal: AbortSignal): Promise<void> {});}-async function downloadApk(- url: string, signal: AbortSignal, progress: (value: number | null) => void,+// A dismissed sheet may immediately be opened again. Wait for the previous native+// writer to stop before inspecting its on-disk offset or reusing the same file.+let downloadTail: Promise<unknown> = Promise.resolve();+function downloadApk(+ url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string,): Promise<string> {+ const result = downloadTail.then(() => runDownload(url, signal, progress, version));+ downloadTail = result.catch(() => undefined);+ return result;+}++async function runDownload(+ url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string,+): Promise<string> {+ if (signal.aborted) throw abortError();if (!FileSystem.cacheDirectory) throw new Error('Cache unavailable');const directory = `${FileSystem.cacheDirectory}cindy-updates/`;await FileSystem.makeDirectoryAsync(directory, { intermediates: true });- // Android may still read the most recent handoff. Reap only our own old cache files.+ // The identity survives process death without storing URLs or progress snapshots.+ // Different releases (even at the same URL) never share partial bytes.+ const key = bytesToHex(sha256(JSON.stringify([url, version])));+ const file = `${directory}update-resume-${key}.apk`;for (const name of await FileSystem.readDirectoryAsync(directory)) {- if (!/^update-[0-9]+-[a-z0-9]+\.apk$/.test(name)) continue;- const file = `${directory}${name}`;- const info = await FileSystem.getInfoAsync(file);+ if (!/^update-(?:[0-9]+-[a-z0-9]+|resume-[a-f0-9]{64})\.apk$/.test(name)) continue;+ const cached = `${directory}${name}`;+ const info = await FileSystem.getInfoAsync(cached);if (info.exists && !info.isDirectory && Date.now() / 1000 - info.modificationTime > 86400) {- await FileSystem.deleteAsync(file, { idempotent: true }).catch(() => undefined);+ await FileSystem.deleteAsync(cached, { idempotent: true }).catch(() => undefined);}}if (signal.aborted) throw abortError();- const file = `${directory}update-${Date.now()}-${Math.random().toString(36).slice(2)}.apk`;- let finished = false;- let timer: ReturnType<typeof setTimeout> | undefined;- let rejectStopped: (reason: Error) => void = () => undefined;- const stopped = new Promise<never>((_, reject) => { rejectStopped = reject; });- const task = FileSystem.createDownloadResumable(url, file, {}, (event) => {- if (finished) return;- armTimeout();- progress(event.totalBytesExpectedToWrite > 0- ? Math.min(1, Math.max(0, event.totalBytesWritten / event.totalBytesExpectedToWrite)) : null);- });- const stop = () => {- rejectStopped(abortError());- void task.cancelAsync().catch(() => undefined);- };- const armTimeout = () => {- clearTimeout(timer);- timer = setTimeout(stop, 90_000);- };- signal.addEventListener('abort', stop, { once: true });- armTimeout();- try {+ const info = await FileSystem.getInfoAsync(file);+ let offset = info.exists && !info.isDirectory ? info.size : 0;+ for (;;) {if (signal.aborted) throw abortError();- const result = await Promise.race([task.downloadAsync(), stopped]);- if (signal.aborted || !result || result.status !== 200) throw new Error('APK download failed');- return file;- } catch (error) {- await task.cancelAsync().catch(() => undefined);- await FileSystem.deleteAsync(file, { idempotent: true }).catch(() => undefined);- throw error;- } finally {- finished = true;- clearTimeout(timer);- signal.removeEventListener('abort', stop);- // Release expo-file-system's progress subscription after completion as well.- void task.cancelAsync().catch(() => undefined);+ let timer: ReturnType<typeof setTimeout> | undefined;+ let finished = false;+ const armTimeout = () => {+ clearTimeout(timer);+ timer = setTimeout(stop, 90_000);+ };+ const options = {+ onProgress: (event: { bytesWritten: number; totalBytes: number }) => {+ if (finished || signal.aborted) return;+ armTimeout();+ progress(event.totalBytes > 0+ ? Math.min(1, Math.max(0, event.bytesWritten / event.totalBytes)) : null);+ },+ };+ // Android's native resume token is the persisted file length. The current Expo+ // downloader checks HTTP status before writing and truncates when Range is+ // ignored (200), unlike the legacy downloader which blindly appends responses.+ const task = offset > 0+ ? DownloadTask.fromSavable({ url, fileUri: file, isDirectory: false, resumeData: String(offset) }, options)+ : new DownloadTask(url, new File(file), options);+ const stop = () => {+ // Pause waits for native output to close; retain the bytes even when the+ // user dismisses the sheet. Repeated abort/timeout events share one pause.+ if (task.state === 'active' && !stopping) {+ stopping = true;+ void task.pauseAsync().catch(() => undefined);+ }+ };+ let stopping = false;+ signal.addEventListener('abort', stop, { once: true });+ armTimeout();+ try {+ if (signal.aborted) throw abortError();+ const result = await (offset > 0 ? task.resumeAsync() : task.downloadAsync());+ if (signal.aborted || !result) throw abortError();+ // Keep files already handed to Android immutable, even if the user opens+ // the same update again while the system installer still holds its URI.+ const ready = `${directory}update-${Date.now()}-${Math.random().toString(36).slice(2)}.apk`;+ await FileSystem.moveAsync({ from: file, to: ready });+ return ready;+ } catch (error) {+ // A completed/stale partial may be outside the server's range. Retry once+ // from zero; network failures and user cancellation retain usable bytes.+ if (!signal.aborted && offset > 0 && /HTTP 416\b/.test(String(error))) {+ await FileSystem.deleteAsync(file, { idempotent: true });+ offset = 0;+ continue;+ }+ throw error;+ } finally {+ finished = true;+ clearTimeout(timer);+ signal.removeEventListener('abort', stop);+ task.release();+ }}}diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 57c591deb2..4b564ec5d9 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -401,7 +401,10 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。- 已授权时确认后直接下载;未授权时卡内先说明权限,用户点「允许并更新」才打开系统设置,返回后读取实际权限,授权成功即继续下载。拒绝不会循环申请,卡上保留「改用浏览器下载」。- 下载显示进度条并支持取消,服务器未给大小时显示不定进度(系统减弱动态效果时静止);- 网络停滞会结束并提供重试。下载在后台完成时,等回到前台再打开安装器。关闭更新卡不会+ 网络停滞会结束并提供重试。中断、取消或进程重启后,按下载地址与目标版本复用私有缓存中+ 已落盘的 APK 字节,重试时续传;不同目标版本不共用文件。服务器忽略 Range 时安全从头+ 写入,返回 416 时仅回退重下一次;HTTP 错误响应不写入已有文件。关闭后立即重开会等待+ 原生写入停止再续传。下载在后台完成时,等回到前台再打开安装器。关闭更新卡不会解除原有强制更新闸门。- APK 只写入 app 私有 `cache/cindy-updates/`。原生桥只接受该目录内的 APK,校验包名、目标版本与递增的 versionCode;最终签名校验、安装确认和覆盖安装由 Android 负责。