Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 安卓在 Wi-Fi 自动下载更新并清理旧安装包
Dash101b404a2ade
diff --git a/apps/mobile/src/update/AndroidUpdateSheet.tsx b/apps/mobile/src/update/AndroidUpdateSheet.tsxindex f4d14fec50..6db1bfd83d 100644--- a/apps/mobile/src/update/AndroidUpdateSheet.tsx+++ b/apps/mobile/src/update/AndroidUpdateSheet.tsx@@ -47,7 +47,8 @@ export function AndroidUpdateSheet() {const state = useSyncExternalStore(androidInstaller.subscribe, androidInstaller.getSnapshot);// close() resets to idle at once; keep the last card on screen while the sheet animates away.const lastShown = useRef<AndroidInstallState | null>(null);- if (state.phase !== 'idle') lastShown.current = state;+ const visible = state.phase !== 'idle' && !state.silent;+ if (visible) lastShown.current = state;const shown = lastShown.current;return (<SheetModal@@ -55,7 +56,7 @@ export function AndroidUpdateSheet() {backdropTestID="update.android.backdrop"onBackdropPress={androidInstaller.close}onRequestClose={androidInstaller.close}- visible={state.phase !== 'idle'}+ visible={visible}>{shown ? <AndroidUpdateCard state={shown} /> : null}</SheetModal>diff --git a/apps/mobile/src/update/androidInstallController.test.ts b/apps/mobile/src/update/androidInstallController.test.tsindex fd93801328..b1189d4c74 100644--- a/apps/mobile/src/update/androidInstallController.test.ts+++ b/apps/mobile/src/update/androidInstallController.test.ts@@ -16,6 +16,7 @@ function setup(overrides: Partial<AndroidInstallIO> = {}) {hasPermission: vi.fn(async () => false),requestPermission: vi.fn(async () => true),download: vi.fn(async () => file),+ waitForForeground: vi.fn(async () => undefined),install: vi.fn(async () => undefined),remove: vi.fn(async () => undefined),openBrowser: vi.fn(async () => undefined),@@ -25,6 +26,49 @@ function setup(overrides: Partial<AndroidInstallIO> = {}) {}describe('Android in-app installation', () => {+ // Unit: automatic discovery must download before prompting, without asking for+ // install permission. Existing manual-entry tests do not exercise this ordering.+ it('offers a completed automatic download only in the foreground, then asks for permission on tap', async () => {+ const foreground = deferred<void>();+ const { controller, io } = setup({ waitForForeground: () => foreground.promise });+ controller.start(target, { automatic: true });+ await settle();+ expect(controller.getSnapshot()).toMatchObject({ silent: true, phase: 'downloading' });+ expect(io.hasPermission).not.toHaveBeenCalled();+ expect(io.install).not.toHaveBeenCalled();+ foreground.resolve(); await settle();+ expect(controller.getSnapshot()).toMatchObject({ phase: 'ready', progress: 1 });+ expect(controller.getSnapshot().silent).not.toBe(true);+ controller.retry(); await settle();+ expect(controller.getSnapshot().phase).toBe('permission-required');+ controller.retry(); await settle();+ expect(io.install).toHaveBeenCalledOnce();+ expect(io.download).toHaveBeenCalledOnce();+ });++ it('keeps automatic failures quiet and allows a later discovery to retry', async () => {+ const { controller } = setup({ download: vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(file) });+ controller.start(target, { automatic: true }); await settle();+ expect(controller.getSnapshot().phase).toBe('idle');+ controller.start(target, { automatic: true }); await settle();+ expect(controller.getSnapshot().phase).toBe('ready');+ controller.close();+ controller.start(target, { automatic: true }); await settle();+ expect(controller.getSnapshot().phase).toBe('idle');+ controller.start({ ...target, version: '1.2.4' }, { automatic: true }); await settle();+ expect(controller.getSnapshot().target?.version).toBe('1.2.4');+ });++ it('replaces a silent obsolete target and ignores its late completion', async () => {+ const old = deferred<string>();+ const { controller, io } = setup({ download: vi.fn().mockImplementationOnce(() => old.promise).mockResolvedValue(file) });+ controller.start(target, { automatic: true }); await settle();+ controller.start({ ...target, version: '1.2.4' }, { automatic: true }); await settle();+ old.resolve('old.apk'); await settle();+ expect(controller.getSnapshot()).toMatchObject({ phase: 'ready', target: { version: '1.2.4' } });+ expect(io.install).not.toHaveBeenCalled();+ });+it('explains the permission before opening settings; only the explicit action requests it', async () => {const { controller, io } = setup();expect(controller.start(target)).toBe(true);@@ -152,7 +196,7 @@ describe('Android in-app installation', () => {await settle();expect(controller.getSnapshot().phase).toBe('idle');expect(io.install).not.toHaveBeenCalled();- expect(io.remove).toHaveBeenCalledWith(file);+ expect(io.remove).not.toHaveBeenCalled(); // The completed target cache remains reusable.});it('an immediate restart after cancellation is not swallowed or overwritten by the old download', async () => {@@ -169,7 +213,7 @@ describe('Android in-app installation', () => {await settle();expect(controller.getSnapshot().phase).toBe('ready');expect(io.install).toHaveBeenCalledOnce();- expect(io.remove).toHaveBeenCalledWith('file:///cache/cindy-updates/old.apk');+ expect(io.remove).not.toHaveBeenCalled(); // The downloader cleans obsolete targets.});it('a download failure offers retry and browser fallback without unhandled rejections', async () => {diff --git a/apps/mobile/src/update/androidInstallController.ts b/apps/mobile/src/update/androidInstallController.tsindex 80d29450a7..e318438777 100644--- a/apps/mobile/src/update/androidInstallController.ts+++ b/apps/mobile/src/update/androidInstallController.ts@@ -5,17 +5,21 @@ export type AndroidInstallPhase = 'idle' | 'offer' | 'permission-required' | 'peexport interface AndroidInstallStartOptions {/** Discovery prompts wait for an explicit tap; the forced gate's button already is that tap. */confirm?: boolean;+ /** Download silently on Wi-Fi, then offer installation. */+ automatic?: boolean;}export interface AndroidInstallState {phase: AndroidInstallPhase;target: AndroidInstallTarget | null;progress: number | null;+ silent?: boolean;}export interface AndroidInstallIO {supported(): boolean;hasPermission(): Promise<boolean>;requestPermission(): Promise<boolean>;- download(url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string): Promise<string>;+ download(url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string, wifiOnly?: boolean): Promise<string>;+ waitForForeground(signal: AbortSignal): Promise<void>;install(uri: string, version: string, signal: AbortSignal): Promise<void>;remove(uri: string): Promise<void>;openBrowser(url: string): Promise<void>;@@ -34,9 +38,8 @@ export class AndroidInstallController {private listeners = new Set<() => void>();private operation: AbortController | null = null;private file: string | null = null;- // Files passed to Android must survive dialog dismissal and installation cancellation.- private handedToInstaller = false;private awaitingConfirm = false;+ private dismissedAutomaticTarget: string | null = null;constructor(private io: AndroidInstallIO) {}getSnapshot = (): AndroidInstallState => this.state;subscribe = (listener: () => void): (() => void) => {@@ -53,10 +56,19 @@ export class AndroidInstallController {try {if (!this.io.supported() || !isDirectApkUrl(target.installUrl)) return false;} catch { return false; }- if (this.state.phase !== 'idle' || this.operation) return true;+ const key = JSON.stringify([target.installUrl, target.version]);+ if (options.automatic && this.dismissedAutomaticTarget === key) return true;+ if (this.state.phase !== 'idle' || this.operation) {+ const same = this.state.target?.version === target.version && this.state.target?.installUrl === target.installUrl;+ // Explicit actions can take over a silent transfer; discovery can replace an+ // obsolete silent target, but must not interrupt a user's installation.+ if (same && options.automatic) return true;+ if (!this.state.silent && !(this.state.phase === 'ready' && !same && !this.operation)) return true;+ this.close();+ }this.awaitingConfirm = options.confirm === true;- this.update({ phase: 'permission', target, progress: null });- void this.run();+ this.update({ phase: 'permission', target, progress: null, silent: options.automatic === true });+ void this.run(false, options.automatic === true);return true;}/** The sheet's primary action: confirm the offer, grant permission, install, or retry. */@@ -69,13 +81,22 @@ export class AndroidInstallController {}};- private async run(grant = false): Promise<void> {+ private async run(grant = false, automatic = false): Promise<void> {const target = this.state.target;if (!target || this.operation) return;const operation = new AbortController();this.operation = operation;const current = () => !operation.signal.aborted;try {+ if (automatic) {+ this.update({ phase: 'downloading', target, progress: null, silent: true });+ const file = await this.io.download(target.installUrl, operation.signal, () => {}, target.version, true);+ if (!current()) return; // Completed files remain reusable in the target cache.+ this.file = file;+ await this.io.waitForForeground(operation.signal);+ if (current()) this.update({ phase: 'ready', target, progress: 1 });+ return;+ }this.update({ phase: 'permission', target, progress: null });let allowed = await this.io.hasPermission();if (!current()) return;@@ -98,21 +119,23 @@ export class AndroidInstallController {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; }+ if (!current()) return;this.file = file;- this.handedToInstaller = false;}this.update({ phase: 'installing', target, progress: 1 });- this.handedToInstaller = true;await this.io.install(this.file, target.version, operation.signal);if (current()) this.update({ phase: 'ready', target, progress: 1 });// Launching Android's installer is not proof that the update was installed.} catch {if (current()) {+ if (automatic) {+ this.file = null;+ this.update(IDLE); // Automatic failures stay quiet; a later check can retry.+ return;+ }// A rejected handoff (invalid APK, missing installer, revoked permission) owns no file.const failedFile = this.file;this.file = null;- this.handedToInstaller = false;if (failedFile) await this.io.remove(failedFile).catch(() => undefined);if (current()) this.update({ phase: 'error', target, progress: null });}@@ -122,12 +145,14 @@ export class AndroidInstallController {}close = (): void => {+ if (this.state.phase === 'ready' && this.state.target) {+ this.dismissedAutomaticTarget = JSON.stringify([this.state.target.installUrl, this.state.target.version]);+ }this.operation?.abort();this.operation = null;- const file = this.file;this.file = null;- if (file && !this.handedToInstaller) void this.io.remove(file).catch(() => undefined);- this.handedToInstaller = false;+ // Keep completed APKs for later installation; discovering a different target+ // removes obsolete files through the same serialized download queue.this.awaitingConfirm = false;this.update(IDLE);};diff --git a/apps/mobile/src/update/androidInstaller.test.ts b/apps/mobile/src/update/androidInstaller.test.tsindex 74d63f08f5..b180d5b064 100644--- a/apps/mobile/src/update/androidInstaller.test.ts+++ b/apps/mobile/src/update/androidInstaller.test.ts@@ -8,6 +8,9 @@ const mocks = vi.hoisted(() => ({onProgress: undefined as ((data: { bytesWritten: number; totalBytes: number }) => void) | undefined,file: '', resumeData: undefined as string | undefined,files: new Map<string, number>(),+ network: { type: 'WIFI', isConnected: true, isInternetReachable: true },+ networkListener: undefined as ((state: { type: string; isConnected: boolean; isInternetReachable: boolean }) => void) | undefined,+ networkUnsubscribe: vi.fn(),download: vi.fn<() => Promise<object | null>>(),resolveDownload: undefined as ((value: object | null) => void) | undefined,rejectDownload: undefined as ((error: Error) => void) | undefined,@@ -23,9 +26,17 @@ vi.mock('react-native', () => ({Linking: { openURL: mocks.browser },}));vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => mocks.native }));+vi.mock('expo-network', () => ({+ NetworkStateType: { WIFI: 'WIFI' },+ getNetworkStateAsync: vi.fn(async () => mocks.network),+ addNetworkStateListener: (listener: typeof mocks.networkListener) => {+ mocks.networkListener = listener;+ return { remove: mocks.networkUnsubscribe };+ },+}));vi.mock('expo-file-system/legacy', () => ({cacheDirectory: 'file:///cache/', makeDirectoryAsync: vi.fn(async () => undefined),- readDirectoryAsync: vi.fn(async () => []),+ readDirectoryAsync: vi.fn(async () => [...mocks.files.keys()].map((file) => file.split('/').at(-1))),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 }),@@ -58,6 +69,8 @@ const pending = () => mocks.download.mockImplementation(() => new Promise((resolbeforeEach(() => {vi.useFakeTimers(); vi.clearAllMocks(); mocks.files.clear();mocks.state.currentState = 'active'; mocks.rejectDownload = undefined; mocks.resolveDownload = undefined;+ mocks.network = { type: 'WIFI', isConnected: true, isInternetReachable: true };+ mocks.networkListener = undefined;mocks.download.mockResolvedValue({});mocks.cancel.mockImplementation(async () => mocks.resolveDownload?.(null));});@@ -67,10 +80,68 @@ afterEach(async () => { androidInstaller.close(); await settle(); vi.useRealTime// 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', () => {+ // Unit: automatic start previously prompted before download and retained obsolete+ // APKs for 24h. Seed a fresh old package on cellular and drive real network events.+ it('cleans obsolete packages immediately on cellular, downloads on Wi-Fi, and only then offers installation', async () => {+ const old = 'file:///cache/cindy-updates/update-123-abc.apk';+ const unrelated = 'file:///cache/cindy-updates/user.apk';+ mocks.files.set(old, 500); mocks.files.set(unrelated, 200);+ mocks.network.type = 'CELLULAR';+ androidInstaller.start({ ...target, version: '2.0.1' }, { automatic: true }); await settle();+ expect(mocks.files.has(old)).toBe(false);+ expect(mocks.files.has(unrelated)).toBe(true);+ expect(mocks.download).not.toHaveBeenCalled();+ expect(androidInstaller.getSnapshot().silent).toBe(true);+ mocks.networkListener!({ ...mocks.network, type: 'WIFI' }); await settle();+ expect(androidInstaller.getSnapshot().phase).toBe('ready');+ expect(androidInstaller.getSnapshot().silent).not.toBe(true);+ expect(mocks.native.install).not.toHaveBeenCalled();+ expect(mocks.native.hasPermission).not.toHaveBeenCalled();+ androidInstaller.retry(); await settle();+ expect(mocks.native.install).toHaveBeenCalledOnce();+ expect(mocks.networkUnsubscribe).toHaveBeenCalledOnce();+ });++ it('pauses when Wi-Fi disappears and resumes the partial only when Wi-Fi returns', async () => {+ pending();+ androidInstaller.start({ ...target, version: '2.0.2' }, { automatic: true }); await settle();+ mocks.files.set(mocks.file, 256);+ mocks.networkListener!({ ...mocks.network, type: 'CELLULAR' }); await settle();+ expect(mocks.cancel).toHaveBeenCalledOnce();+ expect(mocks.download).toHaveBeenCalledOnce();+ expect(androidInstaller.getSnapshot().silent).toBe(true);+ mocks.download.mockResolvedValue({});+ mocks.networkListener!({ ...mocks.network, type: 'WIFI' }); await settle();+ expect(mocks.resumeData).toBe('256');+ expect(androidInstaller.getSnapshot().phase).toBe('ready');+ expect(mocks.native.install).not.toHaveBeenCalled();+ });++ it('lets a manual update take over while automatic download waits for Wi-Fi', async () => {+ mocks.network.type = 'CELLULAR';+ const next = { ...target, version: '2.0.3' };+ androidInstaller.start(next, { automatic: true }); await settle();+ androidInstaller.start(next); await settle();+ expect(mocks.download).toHaveBeenCalledOnce();+ expect(mocks.native.install).toHaveBeenCalledOnce();+ expect(mocks.networkUnsubscribe).toHaveBeenCalledOnce();+ });++ it('reuses a completed automatic APK after dismissal even without Wi-Fi', async () => {+ const next = { ...target, version: '2.0.4' };+ androidInstaller.start(next, { automatic: true }); await settle();+ const cached = [...mocks.files.keys()][0];+ androidInstaller.close(); await settle();+ mocks.network.type = 'CELLULAR';+ androidInstaller.start(next); await settle();+ expect(mocks.download).toHaveBeenCalledOnce();+ expect(mocks.native.install).toHaveBeenCalledWith(cached, next.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(mocks.native.install).toHaveBeenCalledWith(expect.stringMatching(/\/update-ready-[a-f0-9]{64}\.apk$/), target.version);expect(androidInstaller.getSnapshot().phase).toBe('ready');expect(mocks.remove).not.toHaveBeenCalled();expect(mocks.release).toHaveBeenCalledOnce();@@ -87,7 +158,8 @@ describe('Android installer IO', () => {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);+ expect(mocks.native.install.mock.calls[1][0]).toBe(handedOff);+ expect(mocks.download).toHaveBeenCalledOnce();});it('retains interrupted bytes and resumes from disk on retry', async () => {@@ -172,6 +244,23 @@ describe('Android installer IO', () => {expect(mocks.remove).not.toHaveBeenCalled();});+ it('waits for rejected APK deletion before a reopened update can reuse the cache', async () => {+ let finishRemoval!: () => void;+ mocks.remove.mockImplementationOnce(async (file) => {+ await new Promise<void>((resolve) => { finishRemoval = resolve; });+ mocks.files.delete(file);+ });+ mocks.native.install.mockRejectedValueOnce(new Error('invalid APK'));+ androidInstaller.start(target); await settle();+ androidInstaller.close(); androidInstaller.start(target); await settle();+ expect(mocks.download).toHaveBeenCalledOnce();+ finishRemoval(); await settle();+ expect(mocks.download).toHaveBeenCalledTimes(2);+ expect(androidInstaller.getSnapshot().phase).toBe('ready');+ const installed = mocks.native.install.mock.calls[1][0];+ expect(mocks.files.has(installed)).toBe(true);+ });+it('waits for the foreground before opening installation', async () => {mocks.state.currentState = 'background'; androidInstaller.start(target); await settle();expect(mocks.native.install).not.toHaveBeenCalled();diff --git a/apps/mobile/src/update/androidInstaller.ts b/apps/mobile/src/update/androidInstaller.tsindex d65e0c6dfb..27b50b3fce 100644--- a/apps/mobile/src/update/androidInstaller.ts+++ b/apps/mobile/src/update/androidInstaller.ts@@ -2,6 +2,7 @@ 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 * as Network from 'expo-network';import { sha256 } from '@noble/hashes/sha256';import { bytesToHex } from '@noble/hashes/utils';import { AndroidInstallController } from './androidInstallController';@@ -35,16 +36,20 @@ async function waitForForeground(signal: AbortSignal): Promise<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));+function withDownloadCache<T>(operation: () => Promise<T>): Promise<T> {+ const result = downloadTail.then(operation);downloadTail = result.catch(() => undefined);return result;}+function downloadApk(+ url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string, wifiOnly = false,+): Promise<string> {+ return withDownloadCache(() => runDownload(url, signal, progress, version, wifiOnly));+}+async function runDownload(- url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string,+ url: string, signal: AbortSignal, progress: (value: number | null) => void, version: string, wifiOnly: boolean,): Promise<string> {if (signal.aborted) throw abortError();if (!FileSystem.cacheDirectory) throw new Error('Cache unavailable');@@ -54,14 +59,70 @@ async function runDownload(// 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`;+ const ready = `${directory}update-ready-${key}.apk`;for (const name of await FileSystem.readDirectoryAsync(directory)) {- if (!/^update-(?:[0-9]+-[a-z0-9]+|resume-[a-f0-9]{64})\.apk$/.test(name)) continue;+ if (signal.aborted) throw abortError();+ if (!/^update-(?:[0-9]+-[a-z0-9]+|(?:resume|ready)-[a-f0-9]{64})\.apk$/.test(name)) continue;const cached = `${directory}${name}`;+ if (cached === file || cached === ready) continue;const info = await FileSystem.getInfoAsync(cached);- if (info.exists && !info.isDirectory && Date.now() / 1000 - info.modificationTime > 86400) {+ if (info.exists && !info.isDirectory) {await FileSystem.deleteAsync(cached, { idempotent: true }).catch(() => undefined);}}+ if (signal.aborted) throw abortError();+ const completed = await FileSystem.getInfoAsync(ready);+ if (completed.exists && !completed.isDirectory) return ready;+ const transfer = (transferSignal: AbortSignal) => transferApk(url, file, ready, transferSignal, progress);+ return wifiOnly ? downloadOnWifi(signal, transfer) : transfer(signal);+}++/** Subscribe before reading the network, and pause the native writer on Wi-Fi loss.+ * The normal download queue still owns cleanup and the file throughout the wait. */+async function downloadOnWifi(signal: AbortSignal, transfer: (signal: AbortSignal) => Promise<string>): Promise<string> {+ let wifi = false;+ let observed = false;+ let attempt: AbortController | null = null;+ let wake: (() => void) | undefined;+ const onNetwork = (state: Network.NetworkState) => {+ observed = true;+ wifi = state.type === Network.NetworkStateType.WIFI && state.isConnected === true && state.isInternetReachable !== false;+ if (!wifi) attempt?.abort();+ wake?.();+ };+ const subscription = Network.addNetworkStateListener(onNetwork);+ const abort = () => { attempt?.abort(); wake?.(); };+ signal.addEventListener('abort', abort);+ try {+ const initial = await Network.getNetworkStateAsync();+ if (!observed) onNetwork(initial);+ for (;;) {+ if (signal.aborted) throw abortError();+ if (!wifi) {+ await new Promise<void>((resolve) => { wake = resolve; });+ wake = undefined;+ continue;+ }+ const currentAttempt = new AbortController();+ attempt = currentAttempt;+ try {+ return await transfer(currentAttempt.signal);+ } catch (error) {+ if (signal.aborted || !currentAttempt.signal.aborted) throw error;+ // A network transition paused the transfer; wait for Wi-Fi and resume disk bytes.+ } finally {+ attempt = null;+ }+ }+ } finally {+ subscription.remove();+ signal.removeEventListener('abort', abort);+ }+}++async function transferApk(+ url: string, file: string, ready: string, signal: AbortSignal, progress: (value: number | null) => void,+): Promise<string> {if (signal.aborted) throw abortError();const info = await FileSystem.getInfoAsync(file);let offset = info.exists && !info.isDirectory ? info.size : 0;@@ -104,7 +165,6 @@ async function runDownload(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) {@@ -130,11 +190,13 @@ export const androidInstaller = new AndroidInstallController({hasPermission: () => native!.hasPermission(),requestPermission: () => native!.requestPermission(),download: downloadApk,+ waitForForeground,install: async (file, version, signal) => {await waitForForeground(signal);if (signal.aborted) throw abortError();await native!.install(file, version);},- remove: (file) => FileSystem.deleteAsync(file, { idempotent: true }),+ // A rejected cached APK must finish deletion before an immediate retry can reuse it.+ remove: (file) => withDownloadCache(() => FileSystem.deleteAsync(file, { idempotent: true })),openBrowser: (url) => Linking.openURL(url),});diff --git a/apps/mobile/src/update/bundleInstallRouting.test.ts b/apps/mobile/src/update/bundleInstallRouting.test.tsindex b0b09cde26..cd09c1e308 100644--- a/apps/mobile/src/update/bundleInstallRouting.test.ts+++ b/apps/mobile/src/update/bundleInstallRouting.test.ts@@ -16,11 +16,27 @@ vi.mock('./androidInstaller', () => ({ androidInstaller: { start: mocks.start }vi.mock('./androidInstallSource', () => ({ isGooglePlayInstallation: mocks.playInstall }));vi.mock('./forcedUpdateStore', () => ({ enterForcedUpdate: mocks.forced }));vi.mock('./canaryChannelStore', () => ({ resolveUpdateChannelForDevice: () => 'release' }));-import { openBundleInstall, promptBundleUpdate } from './useBundleUpdatePrompt';+import { downloadAndroidBundleUpdate, openBundleInstall, promptBundleUpdate } from './useBundleUpdatePrompt';const target = { version: '1.2.3', runtimeVersion: 'new', installUrl: 'https://updates.example.invalid/app.apk', itmsUrl: '' };beforeEach(() => { vi.clearAllMocks(); mocks.platform.OS = 'android'; mocks.start.mockReturnValue(true); mocks.playInstall.mockReturnValue(false); });describe('shared bundle install routing', () => {+ // Unit: startup/resume must select silent Wi-Fi downloading, while manual+ // discovery and unsupported resume paths keep their existing presentation.+ it('automatic discovery starts a silent Wi-Fi download without an alert', () => {+ promptBundleUpdate({ needsUpdate: true, forced: false, target }, true);+ expect(mocks.start).toHaveBeenCalledWith(+ { version: target.version, installUrl: target.installUrl },+ { confirm: true, automatic: true },+ );+ expect(mocks.alert).not.toHaveBeenCalled();+ });+ it('resume discovery on an older binary stays quiet instead of showing a browser prompt', () => {+ mocks.start.mockReturnValue(false);+ downloadAndroidBundleUpdate({ needsUpdate: true, forced: false, target });+ expect(mocks.alert).not.toHaveBeenCalled();+ expect(mocks.openURL).not.toHaveBeenCalled();+ });it('ordinary updates open the in-app card directly and wait there for the user to confirm', () => {promptBundleUpdate({ needsUpdate: true, forced: false, target: { ...target, releaseNotes: ' Faster sync\n' } });expect(mocks.alert).not.toHaveBeenCalled();diff --git a/apps/mobile/src/update/resumeUpdateCheck.test.ts b/apps/mobile/src/update/resumeUpdateCheck.test.tsindex 84632d0969..50b42ea4ab 100644--- a/apps/mobile/src/update/resumeUpdateCheck.test.ts+++ b/apps/mobile/src/update/resumeUpdateCheck.test.ts@@ -233,11 +233,17 @@ describe('createResumeUpdateChecker 整包路径', () => {expect(bundle).toBe('up-to-date');});- it('非强更整包更新 → update-available 但完全静默(不回调)', async () => {- const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord()) });+ // Unit: resume used to discard ordinary APK releases, so long-running Android+ // apps could not prepare a new package. The public checker now forwards them.+ it('非强更整包更新交给自动下载出口,不进入强更闸门', async () => {+ const onAvailableUpdate = vi.fn();+ const deps = makeDeps({ fetchLatest: vi.fn(async () => latestRecord()), onAvailableUpdate });const { bundle } = await runOnce(deps);expect(bundle).toBe('update-available');expect(deps.onForcedUpdate).not.toHaveBeenCalled();+ expect(onAvailableUpdate).toHaveBeenCalledWith(expect.objectContaining({+ forced: false, target: expect.objectContaining({ version: '2.0.0' }),+ }));});it.each(['0.1.4', '0.1.5'])('整包 version=%s 不高于本机 → 忽略整包,OTA 仍正常下载', async (version) => {diff --git a/apps/mobile/src/update/resumeUpdateCheck.ts b/apps/mobile/src/update/resumeUpdateCheck.tsindex 003d1677b7..72ee3631d9 100644--- a/apps/mobile/src/update/resumeUpdateCheck.ts+++ b/apps/mobile/src/update/resumeUpdateCheck.ts@@ -4,9 +4,8 @@// 后台的 App 永远吃不到新版本;这里在 background → active 时补一次检查,但表现必须无感:// - JS OTA:静默 check → fetch,**绝不 reload**(reload 会闪屏断状态);下载好的 bundle// 由 expo-updates 在下次冷启动自动生效。-// - 整包(runtimeVersion 变化):静默拉 /latest 比对;唯一允许出 UI 的情况是命中-// minVersion 强更(强更本身无法无感),此时上报给 onForcedUpdate 进入阻断态;-// 非强更完全静默(启动路径已有一次性提示,不在每次切回时骚扰)。+// - 整包(runtimeVersion 变化):静默拉 /latest 比对,强更上报 onForcedUpdate 进入阻断态;+// 普通更新交给 onAvailableUpdate,Android 在 Wi-Fi 下备好 APK 后才提示安装。// - 节流:只认真正的 background → active(iOS 通知中心/来电导致的 inactive 抖动不算),// 两次检查最小间隔 minIntervalMs;创建时间视为"刚检查过"(冷启动路径刚跑完,首次// 切回不重复查)。@@ -54,6 +53,7 @@ export interface ResumeUpdateCheckDeps {* 实现因故无法给出出口(如拿不到安装地址)时应自行 no-op,不要留下无出口的阻断屏。*/onForcedUpdate: (evaluation: BundleUpdateEvaluation) => void;+ onAvailableUpdate?: (evaluation: BundleUpdateEvaluation) => void;now: () => number;/** hook 卸载/账号切换后使旧检查失效,避免迟到结果给新账号弹窗。 */isCurrent?: () => boolean;@@ -138,7 +138,10 @@ export function createResumeUpdateChecker(latest,});if (!evaluation.needsUpdate || !evaluation.target) return 'up-to-date';- if (!evaluation.forced) return 'update-available'; // 非强更静默:启动路径已负责提示+ if (!evaluation.forced) {+ deps.onAvailableUpdate?.(evaluation);+ return 'update-available';+ }if (deps.isCurrent && !deps.isCurrent()) return 'skipped';deps.onForcedUpdate(evaluation); // 幂等,不去重:阻断态重复上报无副作用return 'forced';diff --git a/apps/mobile/src/update/useBundleUpdatePrompt.ts b/apps/mobile/src/update/useBundleUpdatePrompt.tsindex d66c698970..d33ac5745c 100644--- a/apps/mobile/src/update/useBundleUpdatePrompt.ts+++ b/apps/mobile/src/update/useBundleUpdatePrompt.ts@@ -70,14 +70,19 @@ async function openGooglePlay(packageName: string): Promise<void> {type BundleInstallTarget = { version?: string; itmsUrl?: string; installUrl?: string; releaseNotes?: string };/** Android 应用内安装:旧原生包、网页地址或 Play 安装返回 false,由调用方走原有出口。 */-function startAndroidInstall(target: BundleInstallTarget, confirm: boolean): boolean {+function startAndroidInstall(target: BundleInstallTarget, confirm: boolean, automatic = false): boolean {if (Platform.OS !== 'android' || isGooglePlayInstallation() || !target.version || !target.installUrl) return false;const releaseNotes = target.releaseNotes?.trim();return androidInstaller.start({version: target.version,installUrl: target.installUrl,...(releaseNotes ? { releaseNotes } : {}),- }, { confirm });+ }, { confirm, ...(automatic ? { automatic: true } : {}) });+}++/** Resume discovery stays quiet on platforms/builds without in-app APK downloads. */+export function downloadAndroidBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUpdate>): void {+ if (evaluation.target && !evaluation.forced) startAndroidInstall(evaluation.target, true, true);}/** 普通更新与强更共用的安装出口;旧 Android 包及网页地址保留浏览器回退。 */@@ -98,11 +103,11 @@ export function openBundleInstall(target: BundleInstallTarget): void {* - 强更:不弹窗,进入模块级阻断态,由 root 层渲染只有「去更新」的闸门屏。* 弹窗做不到阻断——RN Alert 的按钮点一下就关(cancelable: false 只挡点外部/返回键),* 弹窗消失后底下的 App 照旧可用,那是"强提醒"不是"强制"。- * - 非强更:可跳过的普通提示,行为不变。+ * - 非强更:Android 自动检查先静默下载,手动检查与其他安装渠道保留普通提示。* 两种情况都要求先解析出可跳转的安装地址:拿不到地址就什么都不做,* 尤其不能把用户关进一个没有出口的阻断屏(见 forcedUpdateStore 的三层保证)。*/-export function promptBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUpdate>): void {+export function promptBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUpdate>, automatic = false): void {if (!evaluation.target) return;const url = preferredInstallUrl(evaluation.target);if (!url) return;@@ -111,9 +116,8 @@ export function promptBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUenterForcedUpdate(evaluation.target);return;}- // Android 应用内安装:发现即呈现更新卡(版本、更新内容、授权与下载同卡完成),- // 不再先弹系统对话框;卡内主按钮才是用户的确认。- if (startAndroidInstall(evaluation.target, true)) return;+ // 自动检查先在 Wi-Fi 下静默备好 APK;手动检查仍可直接打开更新卡。+ if (startAndroidInstall(evaluation.target, true, automatic)) return;const notes = evaluation.target.releaseNotes?.trim();const message = [@@ -174,7 +178,7 @@ export function useBundleUpdatePrompt({});if (evaluation.needsUpdate) {setState('update-available');- promptBundleUpdate(evaluation);+ promptBundleUpdate(evaluation, auto);return 'update-available';} else {setState('up-to-date');@@ -191,7 +195,7 @@ export function useBundleUpdatePrompt({} finally {inFlightChannels.current.delete(channel);}- }, [bundleCheckEnabled, channel, notifyWhenUpToDate]);+ }, [auto, bundleCheckEnabled, channel, notifyWhenUpToDate]);useEffect(() => {if (auto && bundleCheckEnabled) void checkNow();diff --git a/apps/mobile/src/update/useResumeUpdateCheck.ts b/apps/mobile/src/update/useResumeUpdateCheck.tsindex 07f2f041c4..5b764bfdb9 100644--- a/apps/mobile/src/update/useResumeUpdateCheck.ts+++ b/apps/mobile/src/update/useResumeUpdateCheck.ts@@ -18,7 +18,7 @@ import { shouldCheckBundleUpdate } from './bundleUpdate';import { isGooglePlayInstallation } from './androidInstallSource';import { fetchLatestRelease } from './fetchLatestRelease';import { createResumeUpdateChecker } from './resumeUpdateCheck';-import { promptBundleUpdate } from './useBundleUpdatePrompt';+import { downloadAndroidBundleUpdate, promptBundleUpdate } from './useBundleUpdatePrompt';import { resolveUpdateChannelForDevice } from './canaryChannelStore';import { runSelfHostedOtaRequest } from './otaRequestCoordinator';import type { UpdateChannel } from '@cindy/maker-shared/update-channel';@@ -54,6 +54,7 @@ export function useResumeUpdateCheck(// 与 useBundleUpdatePrompt / useForcedUpdateRecheck 同口径:强更比较按原生真值,热更后不漂移。getCurrentVersion: () => APP_BINARY_VERSION || null,onForcedUpdate: promptBundleUpdate,+ onAvailableUpdate: downloadAndroidBundleUpdate,now: () => Date.now(),isCurrent: () => current,});diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex a562c3c6b9..700425444c 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -399,12 +399,15 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。- 全程只用一张内容高度的 Material 底部更新卡(`SheetModal.nativePresentation`):应用图标、版本变化与更新内容固定在上方,授权说明、下载进度、安装与失败在同一张卡内- 切换,不再叠系统对话框。启动/设置页/回前台发现普通更新时直接呈现该卡,卡上- 「立即更新」才是用户确认;强更屏的「去更新」本身就是确认,不再出现确认步骤。+ 切换,不再叠系统对话框。启动/回前台自动发现普通更新时,先在 Wi-Fi 下静默下载,+ 下载完成且回到前台后才显示「安装更新」卡;自动下载不预先申请安装权限,不自动拉起安装器。+ Wi-Fi 断开时暂停并保留字节,恢复 Wi-Fi 后续传;自动失败静默留待后续检查重试。+ 选择「稍后」后,本进程不再重复提示同一目标;手动检查仍可打开更新卡,明确确认后可在移动网络下载。+ 强更屏的「去更新」本身就是确认,不再出现确认步骤。旧原生包、网页地址与 Play 安装仍走原系统对话框和既有出口。-- 已授权时确认后直接下载;未授权时卡内先说明权限,用户点「允许并更新」才打开系统设置,- 返回后读取实际权限,授权成功即继续下载。拒绝不会循环申请,卡上保留「改用浏览器下载」。-- 下载显示进度条并支持取消,服务器未给大小时显示不定进度(系统减弱动态效果时静止);+- 点击安装时已授权则直接使用已下载的包;未授权时卡内先说明权限,用户点「允许并更新」才打开系统设置,+ 返回后读取实际权限,授权成功即继续安装(尚未下载的手动更新先下载)。拒绝不会循环申请,卡上保留「改用浏览器下载」。+- 手动下载显示进度条并支持取消,服务器未给大小时显示不定进度(系统减弱动态效果时静止);网络停滞会结束并提供重试。中断、取消或进程重启后,按下载地址与目标版本复用私有缓存中已落盘的 APK 字节,重试时续传;不同目标版本不共用文件。服务器忽略 Range 时安全从头写入,返回 416 时仅回退重下一次;HTTP 错误响应不写入已有文件。关闭后立即重开会等待@@ -412,8 +415,9 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。解除原有强制更新闸门。- APK 只写入 app 私有 `cache/cindy-updates/`。原生桥只接受该目录内的 APK,校验包名、目标版本与递增的 versionCode;最终签名校验、安装确认和覆盖安装由 Android 负责。-- 安装器已打开不代表安装完成。取消系统安装后可再次安装已下载的文件;交接后的文件- 不立即删除,后续下载时清理超过 24 小时的本功能缓存。+- 安装器已打开不代表安装完成。取消系统安装或关闭更新卡后保留当前目标的完整包,+ 再次安装或进程重启后直接复用,不重复下载或改写。发现新目标时(包括等待 Wi-Fi 期间),+ 立即清理本功能其他目标的完整包、断点包和旧命名安装包,不再等待 24 小时;只清理已知命名的文件。实现:`modules/cindy-app-installer/`、`src/update/androidInstallController.ts`、`src/update/androidInstaller.ts`、`src/update/AndroidUpdateSheet.tsx`。