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): 保护安装器副本并取消旧通道更新任务

Dash0fec066183ad
diff --git a/apps/mobile/src/update/androidInstallController.test.ts b/apps/mobile/src/update/androidInstallController.test.ts
index b1189d4c74..26c1354f7e 100644
--- a/apps/mobile/src/update/androidInstallController.test.ts
+++ b/apps/mobile/src/update/androidInstallController.test.ts
@@ -26,6 +26,20 @@ function setup(overrides: Partial<AndroidInstallIO> = {}) {
}
describe('Android in-app installation', () => {
+ // PR #6977: permission/denial cards also expose Later. Existing dismissal
+ // coverage only closed ready; the same target must stay suppressed here too.
+ it.each([false, true])('remembers Later from the permission card (denied=%s)', async (denied) => {
+ const { controller } = setup({ requestPermission: vi.fn(async () => false) });
+ controller.start(target, { automatic: true }); await settle();
+ controller.retry(); await settle();
+ if (denied) { controller.retry(); await settle(); }
+ expect(controller.getSnapshot().phase).toBe(denied ? 'permission-denied' : 'permission-required');
+ controller.close();
+ controller.start(target, { automatic: true }); await settle();
+ expect(controller.getSnapshot().phase).toBe('idle');
+ controller.start(target); await settle();
+ expect(controller.getSnapshot().phase).toBe('permission-required');
+ });
// 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 () => {
diff --git a/apps/mobile/src/update/androidInstallController.ts b/apps/mobile/src/update/androidInstallController.ts
index e318438777..c1dee1c679 100644
--- a/apps/mobile/src/update/androidInstallController.ts
+++ b/apps/mobile/src/update/androidInstallController.ts
@@ -145,9 +145,14 @@ export class AndroidInstallController {
}
close = (): void => {
- if (this.state.phase === 'ready' && this.state.target) {
+ if (!this.state.silent && this.state.target) {
this.dismissedAutomaticTarget = JSON.stringify([this.state.target.installUrl, this.state.target.version]);
}
+ this.cancel();
+ };
+
+ /** Channel-owner cleanup is cancellation, not the user's Later choice. */
+ cancel = (): void => {
this.operation?.abort();
this.operation = null;
this.file = null;
diff --git a/apps/mobile/src/update/androidInstaller.test.ts b/apps/mobile/src/update/androidInstaller.test.ts
index b180d5b064..7d69565129 100644
--- a/apps/mobile/src/update/androidInstaller.test.ts
+++ b/apps/mobile/src/update/androidInstaller.test.ts
@@ -8,6 +8,7 @@ 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>(),
+ modified: 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(),
@@ -38,12 +39,15 @@ vi.mock('expo-file-system/legacy', () => ({
cacheDirectory: 'file:///cache/', makeDirectoryAsync: vi.fn(async () => undefined),
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: true, isDirectory: false, size: mocks.files.get(file), modificationTime: mocks.modified.get(file) ?? Date.now() / 1000 }
: { exists: false }),
deleteAsync: mocks.remove,
moveAsync: vi.fn(async ({ from, to }: { from: string; to: string }) => {
mocks.files.set(to, mocks.files.get(from) ?? 0); mocks.files.delete(from);
}),
+ copyAsync: vi.fn(async ({ from, to }: { from: string; to: string }) => {
+ mocks.files.set(to, mocks.files.get(from) ?? 0);
+ }),
}));
vi.mock('expo-file-system', () => ({
File: class { constructor(public uri: string) {} },
@@ -67,7 +71,7 @@ const target = { installUrl: 'https://updates.example.invalid/app.apk', version:
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.files.clear();
+ vi.useFakeTimers(); vi.clearAllMocks(); mocks.files.clear(); mocks.modified.clear();
mocks.state.currentState = 'active'; mocks.rejectDownload = undefined; mocks.resolveDownload = undefined;
mocks.network = { type: 'WIFI', isConnected: true, isInternetReachable: true };
mocks.networkListener = undefined;
@@ -80,10 +84,23 @@ 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', () => {
+ // PR #6977: startActivity resolves before Android opens its URI. A new target
+ // must reclaim the old download cache while preserving that installer's bytes.
+ it('keeps a recent installer handoff readable while reclaiming an obsolete ready package', async () => {
+ androidInstaller.start(target); await settle();
+ const handedOff = mocks.native.install.mock.calls[0][0];
+ const cached = [...mocks.files.keys()].find((file) => file.includes('update-ready-'))!;
+ androidInstaller.start({ ...target, version: '3.0.1' }, { automatic: true }); await settle();
+ expect(mocks.files.has(cached)).toBe(false);
+ expect(mocks.files.has(handedOff)).toBe(true);
+ mocks.modified.set(handedOff, Date.now() / 1000 - 86401);
+ androidInstaller.start({ ...target, version: '3.0.2' }, { automatic: true }); await settle();
+ expect(mocks.files.has(handedOff)).toBe(false);
+ });
// 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 old = `file:///cache/cindy-updates/update-ready-${'a'.repeat(64)}.apk`;
const unrelated = 'file:///cache/cindy-updates/user.apk';
mocks.files.set(old, 500); mocks.files.set(unrelated, 200);
mocks.network.type = 'CELLULAR';
@@ -135,13 +152,14 @@ describe('Android installer IO', () => {
mocks.network.type = 'CELLULAR';
androidInstaller.start(next); await settle();
expect(mocks.download).toHaveBeenCalledOnce();
- expect(mocks.native.install).toHaveBeenCalledWith(cached, next.version);
+ expect(mocks.files.has(cached)).toBe(true);
+ expect(mocks.native.install).toHaveBeenCalledWith(expect.stringMatching(/\/update-[0-9]+-[a-z0-9]+\.apk$/), 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-ready-[a-f0-9]{64}\.apk$/), target.version);
+ 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();
@@ -158,7 +176,7 @@ 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]).toBe(handedOff);
+ expect(mocks.native.install.mock.calls[1][0]).not.toBe(handedOff);
expect(mocks.download).toHaveBeenCalledOnce();
});
@@ -246,7 +264,8 @@ describe('Android installer IO', () => {
it('waits for rejected APK deletion before a reopened update can reuse the cache', async () => {
let finishRemoval!: () => void;
- mocks.remove.mockImplementationOnce(async (file) => {
+ mocks.remove.mockImplementationOnce(async (file) => { mocks.files.delete(file); }); // Rejected handoff.
+ mocks.remove.mockImplementationOnce(async (file) => { // Invalid reusable cache.
await new Promise<void>((resolve) => { finishRemoval = resolve; });
mocks.files.delete(file);
});
diff --git a/apps/mobile/src/update/androidInstaller.ts b/apps/mobile/src/update/androidInstaller.ts
index 27b50b3fce..6fdccd92bb 100644
--- a/apps/mobile/src/update/androidInstaller.ts
+++ b/apps/mobile/src/update/androidInstaller.ts
@@ -67,6 +67,10 @@ async function runDownload(
if (cached === file || cached === ready) continue;
const info = await FileSystem.getInfoAsync(cached);
if (info.exists && !info.isDirectory) {
+ // Timestamp-named files are immutable system-installer handoffs (including
+ // older clients' handoffs). Retain their existing 24-hour grace period.
+ if (/^update-[0-9]+-[a-z0-9]+\.apk$/.test(name)
+ && Date.now() / 1000 - info.modificationTime <= 86400) continue;
await FileSystem.deleteAsync(cached, { idempotent: true }).catch(() => undefined);
}
}
@@ -193,8 +197,20 @@ export const androidInstaller = new AndroidInstallController({
waitForForeground,
install: async (file, version, signal) => {
await waitForForeground(signal);
- if (signal.aborted) throw abortError();
- await native!.install(file, version);
+ await withDownloadCache(async () => {
+ if (signal.aborted) throw abortError();
+ // Android may open the URI after startActivity has returned. Give it a
+ // separate immutable handoff, so new-target cleanup can reclaim the cache.
+ const handoff = file.replace(/[^/]+$/, `update-${Date.now()}-${Math.random().toString(36).slice(2)}.apk`);
+ try {
+ await FileSystem.copyAsync({ from: file, to: handoff });
+ if (signal.aborted) throw abortError();
+ await native!.install(handoff, version);
+ } catch (error) {
+ await FileSystem.deleteAsync(handoff, { idempotent: true }).catch(() => undefined);
+ throw error;
+ }
+ });
},
// A rejected cached APK must finish deletion before an immediate retry can reuse it.
remove: (file) => withDownloadCache(() => FileSystem.deleteAsync(file, { idempotent: true })),
diff --git a/apps/mobile/src/update/playUpdateEntries.test.ts b/apps/mobile/src/update/playUpdateEntries.test.ts
index f9c13a8159..1ec9a810cb 100644
--- a/apps/mobile/src/update/playUpdateEntries.test.ts
+++ b/apps/mobile/src/update/playUpdateEntries.test.ts
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
playInstall: vi.fn(() => true),
- fetchLatest: vi.fn(async () => null),
+ fetchLatest: vi.fn<() => Promise<unknown>>(async () => null),
+ download: vi.fn<(_url: string, signal: AbortSignal) => Promise<string>>(async () => 'ready.apk'),
+ install: vi.fn(async () => undefined),
checkOta: vi.fn(async () => ({ isAvailable: false })),
fetchOta: vi.fn(async () => ({ isNew: false })),
appStateListener: null as ((state: string) => void) | null,
@@ -44,7 +46,14 @@ vi.mock('@/config/env', () => ({
}));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('./androidInstallSource', () => ({ isGooglePlayInstallation: mocks.playInstall }));
-vi.mock('./androidInstaller', () => ({ androidInstaller: { start: vi.fn() } }));
+vi.mock('./androidInstaller', async () => {
+ const { AndroidInstallController } = await import('./androidInstallController');
+ return { androidInstaller: new AndroidInstallController({
+ supported: () => true, hasPermission: async () => true, requestPermission: async () => true,
+ download: mocks.download, install: mocks.install, waitForForeground: async () => undefined,
+ remove: async () => undefined, openBrowser: async () => undefined,
+ }) };
+});
vi.mock('./fetchLatestRelease', () => ({ fetchLatestRelease: mocks.fetchLatest }));
vi.mock('./forcedUpdateStore', () => ({ enterForcedUpdate: vi.fn() }));
vi.mock('./canaryChannelStore', () => ({ resolveUpdateChannelForDevice: () => 'release' }));
@@ -61,20 +70,50 @@ vi.mock('./otaRequestCoordinator', () => ({
import { useBundleUpdatePrompt } from './useBundleUpdatePrompt';
import { useResumeUpdateCheck } from './useResumeUpdateCheck';
import { runManualUpdateCheck } from './manualUpdateCheck';
+import { androidInstaller } from './androidInstaller';
beforeEach(() => {
vi.clearAllMocks();
mocks.playInstall.mockReturnValue(true);
mocks.appStateListener = null;
mocks.cleanup = null;
+ mocks.fetchLatest.mockResolvedValue(null);
});
afterEach(() => {
mocks.cleanup?.();
+ androidInstaller.cancel();
vi.restoreAllMocks();
});
describe('Google Play update entry points', () => {
+ // PR #6977: root channel cleanup must also own transfers started by resume.
+ // Existing checks only blocked late manifests, not an already-started download.
+ it('cancels a resume download on channel change even when the next channel has no update', async () => {
+ mocks.playInstall.mockReturnValue(false);
+ useBundleUpdatePrompt({ auto: true, channel: 'canary' });
+ const rootCleanup = mocks.cleanup;
+ let complete!: (file: string) => void;
+ let oldSignal!: AbortSignal;
+ mocks.download.mockImplementationOnce((_url, signal) => {
+ oldSignal = signal;
+ return new Promise((resolve) => { complete = resolve; });
+ });
+ mocks.fetchLatest.mockResolvedValueOnce({ version: '2.0.0', runtimeVersion: 'new',
+ installUrl: 'https://updates.example.invalid/app.apk', itmsUrl: '' });
+ vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValue(300_001);
+ useResumeUpdateCheck('canary');
+ const resumeCleanup = mocks.cleanup;
+ mocks.appStateListener!('background'); mocks.appStateListener!('active');
+ await vi.waitFor(() => expect(mocks.download).toHaveBeenCalledOnce());
+ rootCleanup?.(); resumeCleanup?.();
+ expect(oldSignal.aborted).toBe(true);
+ useBundleUpdatePrompt({ auto: true, channel: 'release' });
+ complete('old-canary.apk');
+ for (let i = 0; i < 50; i++) await Promise.resolve();
+ expect(androidInstaller.getSnapshot().phase).toBe('idle');
+ expect(mocks.install).not.toHaveBeenCalled();
+ });
it('startup hook skips the website release check', async () => {
const { checkNow } = useBundleUpdatePrompt({ auto: true, channel: 'release' });
await expect(checkNow()).resolves.toBe('skipped');
diff --git a/apps/mobile/src/update/useBundleUpdatePrompt.ts b/apps/mobile/src/update/useBundleUpdatePrompt.ts
index d33ac5745c..f2280fbfb0 100644
--- a/apps/mobile/src/update/useBundleUpdatePrompt.ts
+++ b/apps/mobile/src/update/useBundleUpdatePrompt.ts
@@ -198,7 +198,14 @@ export function useBundleUpdatePrompt({
}, [auto, bundleCheckEnabled, channel, notifyWhenUpToDate]);
useEffect(() => {
- if (auto && bundleCheckEnabled) void checkNow();
+ if (!auto || !bundleCheckEnabled) return;
+ void checkNow();
+ return () => {
+ // The root auto hook owns the shared installer's channel lifetime, including
+ // work started by resume checks. Settings' manual hook never owns cleanup.
+ channelEpochRef.current += 1;
+ androidInstaller.cancel();
+ };
// auto hook 在登录/切账号导致 channel 变化时再检查一次,避免新的账号
// 继续沿用旧账号的 release 指针;手动检查入口仍由调用方通过 checkNow 触发。
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 700425444c..409f5f0a75 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -403,6 +403,8 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。
下载完成且回到前台后才显示「安装更新」卡;自动下载不预先申请安装权限,不自动拉起安装器。
Wi-Fi 断开时暂停并保留字节,恢复 Wi-Fi 后续传;自动失败静默留待后续检查重试。
选择「稍后」后,本进程不再重复提示同一目标;手动检查仍可打开更新卡,明确确认后可在移动网络下载。
+ 权限说明或拒绝权限卡上的「稍后」也沿用同一规则。根部自动检查 hook 持有共享安装器的通道生命周期,
+ 通道变化或卸载时取消已启动的下载与安装卡,回前台启动的下载同样受此约束;取消不视为用户选择「稍后」。
强更屏的「去更新」本身就是确认,不再出现确认步骤。
旧原生包、网页地址与 Play 安装仍走原系统对话框和既有出口。
- 点击安装时已授权则直接使用已下载的包;未授权时卡内先说明权限,用户点「允许并更新」才打开系统设置,
@@ -417,7 +419,9 @@ JS OTA 仍按现有通道检查,设置页手动检查只报告内容更新。
目标版本与递增的 versionCode;最终签名校验、安装确认和覆盖安装由 Android 负责。
- 安装器已打开不代表安装完成。取消系统安装或关闭更新卡后保留当前目标的完整包,
再次安装或进程重启后直接复用,不重复下载或改写。发现新目标时(包括等待 Wi-Fi 期间),
- 立即清理本功能其他目标的完整包、断点包和旧命名安装包,不再等待 24 小时;只清理已知命名的文件。
+ 立即清理本功能其他目标的完整包和断点包;只清理已知命名的文件。
+ 系统安装器使用独立、不可改写的时间戳命名副本,沿用既有 24 小时清理宽限(包括旧客户端的同类副本),
+ 避免 `startActivity` 返回后才读取 APK 时被新目标清理;打开安装器失败则立即回收该副本。
实现:`modules/cindy-app-installer/`、`src/update/androidInstallController.ts`、
`src/update/androidInstaller.ts`、`src/update/AndroidUpdateSheet.tsx`。