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): 修复 Android 相册图片位置权限失败 (#287)

Dash3d22580abcf3
diff --git a/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts b/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts
new file mode 100644
index 0000000000..0125e0fd38
--- /dev/null
+++ b/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts
@@ -0,0 +1,100 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const platform = vi.hoisted(() => ({ os: 'android' }));
+const mediaLibrary = vi.hoisted(() => ({
+ getAssetInfoAsync: vi.fn(),
+}));
+const imageManipulator = vi.hoisted(() => ({
+ manipulate: vi.fn(),
+}));
+
+vi.mock('react-native', () => ({
+ Linking: { openSettings: vi.fn() },
+ Platform: { get OS() { return platform.os; } },
+}));
+vi.mock('expo-media-library/legacy', () => ({
+ getAssetInfoAsync: mediaLibrary.getAssetInfoAsync,
+ MediaType: { photo: 'photo' },
+ SortBy: { creationTime: 'creationTime' },
+}));
+vi.mock('expo-image-manipulator', () => ({
+ ImageManipulator: { manipulate: imageManipulator.manipulate },
+ SaveFormat: { JPEG: 'jpeg' },
+}));
+vi.mock('@/i18n', () => ({
+ i18n: { t: (key: string) => key },
+}));
+
+import {
+ resolveContextSheetMediaAssetForUpload,
+ type ContextSheetMediaAsset,
+} from '@/session/useContextSheetMediaAssets';
+
+function asset(overrides: Partial<ContextSheetMediaAsset> = {}): ContextSheetMediaAsset {
+ return {
+ id: 'asset-1',
+ filename: 'Screenshot.png',
+ uri: 'content://media/external/images/media/1',
+ width: 1080,
+ height: 2400,
+ ...overrides,
+ };
+}
+
+describe('resolveContextSheetMediaAssetForUpload', () => {
+ beforeEach(() => {
+ platform.os = 'android';
+ mediaLibrary.getAssetInfoAsync.mockReset();
+ imageManipulator.manipulate.mockReset();
+ });
+
+ it('Android 缺少媒体位置权限时回退列表 URI 与尺寸,继续图片上传解析', async () => {
+ mediaLibrary.getAssetInfoAsync.mockRejectedValue(Object.assign(
+ new Error('Unable to load asset'),
+ { code: 'ERR_UNABLE_TO_LOAD' },
+ ));
+
+ await expect(resolveContextSheetMediaAssetForUpload(asset())).resolves.toEqual({
+ filename: 'Screenshot.png',
+ uri: 'content://media/external/images/media/1',
+ width: 1080,
+ height: 2400,
+ });
+ expect(mediaLibrary.getAssetInfoAsync).toHaveBeenCalledWith('asset-1');
+ expect(imageManipulator.manipulate).not.toHaveBeenCalled();
+ });
+
+ it('Android 非 ERR_UNABLE_TO_LOAD 错误继续抛出,不延后真实故障', async () => {
+ const failure = Object.assign(new Error('Media library internal failure'), {
+ code: 'ERR_INTERNAL',
+ });
+ mediaLibrary.getAssetInfoAsync.mockRejectedValue(failure);
+
+ await expect(resolveContextSheetMediaAssetForUpload(asset())).rejects.toBe(failure);
+ });
+
+ it('正常路径优先使用 full info 的 localUri 与尺寸', async () => {
+ mediaLibrary.getAssetInfoAsync.mockResolvedValue({
+ localUri: 'file:///storage/emulated/0/Pictures/Screenshot.png',
+ width: 1440,
+ height: 3200,
+ });
+
+ await expect(resolveContextSheetMediaAssetForUpload(asset())).resolves.toEqual({
+ filename: 'Screenshot.png',
+ uri: 'file:///storage/emulated/0/Pictures/Screenshot.png',
+ width: 1440,
+ height: 3200,
+ });
+ });
+
+ it('iOS full info 失败时保留原错误,不把 ph:// 交给上传层', async () => {
+ platform.os = 'ios';
+ const failure = new Error('iCloud asset unavailable');
+ mediaLibrary.getAssetInfoAsync.mockRejectedValue(failure);
+
+ await expect(resolveContextSheetMediaAssetForUpload(asset({
+ uri: 'ph://asset-1',
+ }))).rejects.toBe(failure);
+ });
+});
diff --git a/apps/mobile/src/session/useContextSheetMediaAssets.ts b/apps/mobile/src/session/useContextSheetMediaAssets.ts
index 4d074feaec..bdd6d97aef 100644
--- a/apps/mobile/src/session/useContextSheetMediaAssets.ts
+++ b/apps/mobile/src/session/useContextSheetMediaAssets.ts
@@ -13,6 +13,9 @@ export interface ContextSheetMediaAsset {
filename: string;
/** 展示用 URI(iOS ph:// / Android content://);渲染走 expo-image,RN Image 在新架构下不支持 ph://。 */
uri: string;
+ /** 列表查询已返回的尺寸;Android full info 权限失败时供上传预处理继续使用。 */
+ width?: number;
+ height?: number;
}
export type ContextSheetMediaKind = 'recent' | 'screenshots';
@@ -59,6 +62,8 @@ async function fetchAssets(kind: ContextSheetMediaKind, first: number): Promise<
id: asset.id,
filename: asset.filename,
uri: asset.uri,
+ width: asset.width,
+ height: asset.height,
}));
}
@@ -164,6 +169,14 @@ const HEIC_JPEG_COMPRESS = 0.9;
* race 超时后系统下载仍在后台继续,用户重试时大概率已就位,重试即成功。
*/
const ASSET_INFO_TIMEOUT_MS = 60_000;
+const ANDROID_ASSET_INFO_FALLBACK_ERROR_CODE = 'ERR_UNABLE_TO_LOAD';
+
+function isAndroidAssetInfoFallbackError(error: unknown): boolean {
+ return typeof error === 'object'
+ && error !== null
+ && 'code' in error
+ && error.code === ANDROID_ASSET_INFO_FALLBACK_ERROR_CODE;
+}
async function getAssetInfoWithTimeout(assetId: string): Promise<MediaLibrary.AssetInfo> {
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -187,7 +200,9 @@ async function getAssetInfoWithTimeout(assetId: string): Promise<MediaLibrary.As
* 把相册资产解析成可上传的 file:// 信息。iOS 的 ph:// 不是文件路径,
* 必须经 getAssetInfoAsync 换 localUri(带 iCloud 下载超时兜底);iOS 拿不到
* localUri 时直接报错——ph:// 喂给原生上传层只会变成下游玄学失败,就地把
- * 「照片没就位」说清楚;Android 保留 content:// 回退(原生上传可读)。
+ * 「照片没就位」说清楚;Android 的 full info 可能因未授予媒体位置权限返回
+ * ERR_UNABLE_TO_LOAD,此时回退列表查询已返回的 content:// 与尺寸(原生上传可读),
+ * 不为普通附件扩大权限;其它错误继续抛出,避免把真实故障延后到下游。
* HEIC / HEIF(iOS 相机默认格式)在这里就地转成 JPEG——附件类型白名单与模型图像
* 接口都只认 jpeg/png/gif/webp,直接放行 HEIC 会在链路下游变成不可用附件。
* 转 JPEG 的同一次 manipulate 里顺带把长边压到上传上限(见 mobileImagePreprocess),
@@ -196,20 +211,27 @@ async function getAssetInfoWithTimeout(assetId: string): Promise<MediaLibrary.As
export async function resolveContextSheetMediaAssetForUpload(
asset: ContextSheetMediaAsset,
): Promise<{ uri: string; filename: string; width?: number; height?: number; optimized?: boolean }> {
- const info = await getAssetInfoWithTimeout(asset.id);
- const localUri = info.localUri?.trim();
+ let info: MediaLibrary.AssetInfo | undefined;
+ try {
+ info = await getAssetInfoWithTimeout(asset.id);
+ } catch (error) {
+ if (Platform.OS !== 'android' || !isAndroidAssetInfoFallbackError(error)) throw error;
+ }
+ const localUri = info?.localUri?.trim();
if (!localUri && Platform.OS === 'ios') {
throw new Error(i18n.t('interaction.contextSheet.photoNotReadable'));
}
const uri = localUri || asset.uri;
+ const width = typeof info?.width === 'number' ? info.width : asset.width;
+ const height = typeof info?.height === 'number' ? info.height : asset.height;
if (!HEIC_EXT_PATTERN.test(asset.filename) && !HEIC_EXT_PATTERN.test(uri)) {
- return { filename: asset.filename, uri, width: info.width, height: info.height };
+ return { filename: asset.filename, uri, width, height };
}
const context = ImageManipulator.manipulate(uri);
- const width = typeof info.width === 'number' ? info.width : 0;
- const height = typeof info.height === 'number' ? info.height : 0;
- if (Math.max(width, height) > MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE) {
- context.resize(width >= height
+ const resolvedWidth = width ?? 0;
+ const resolvedHeight = height ?? 0;
+ if (Math.max(resolvedWidth, resolvedHeight) > MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE) {
+ context.resize(resolvedWidth >= resolvedHeight
? { width: MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE }
: { height: MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE });
}