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): 系统相册/相机选图的 HEIC/HEIF 就位时转 JPEG,补齐 picker 入口缺失的格式归一 (#3892)

fico-hubde0bd4608168
diff --git a/apps/mobile/src/__tests__/mobileImageAttachment.test.ts b/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
index 6d08ff0bf2..8cee4b6da6 100644
--- a/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
+++ b/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
@@ -1,9 +1,10 @@
-import { beforeAll, describe, expect, it } from 'vitest';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
import { MOBILE_MAX_ATTACHMENT_BYTES } from '@/session/attachments';
import {
assertMobileImageSize,
buildMobileImageAttachmentCandidate,
+ needsJpegConversion,
} from '@/session/mobileImageAttachment';
// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。
@@ -56,3 +57,62 @@ describe('mobileImageAttachment', () => {
expect(() => assertMobileImageSize(MOBILE_MAX_ATTACHMENT_BYTES + 1)).toThrow('图片超过');
});
});
+
+describe('buildMobileImageAttachmentCandidate · HEIC / HEIF 归一(#3889)', () => {
+ it('白名单格式(png / jpg / webp)不带 resolve 钩子,候选形状不变', () => {
+ for (const [fileName, mimeType] of [['a.png', 'image/png'], ['b.JPG', null], ['c.webp', 'image/webp']] as const) {
+ const candidate = buildMobileImageAttachmentCandidate({ uri: `file:///tmp/${fileName}`, fileName, mimeType }, 0);
+ expect(candidate).not.toHaveProperty('resolve');
+ }
+ });
+
+ it('文件名为 .heic / .HEIF 时带 resolve:预览仍用原始 uri,就位时转 JPEG 并改名', async () => {
+ const convertToJpeg = vi.fn().mockResolvedValue('file:///tmp/converted.jpg');
+ const candidate = buildMobileImageAttachmentCandidate({
+ uri: 'file:///tmp/IMG_0001.HEIF',
+ fileName: 'IMG_0001.HEIF',
+ fileSize: 321,
+ mimeType: null,
+ }, 0, { convertToJpeg });
+ // 入队当帧:原始 uri / 名字不动,托盘预览用得上。
+ expect(candidate).toMatchObject({ uri: 'file:///tmp/IMG_0001.HEIF', name: 'IMG_0001.HEIF', size: 321 });
+ expect(convertToJpeg).not.toHaveBeenCalled();
+ await expect(candidate.resolve!()).resolves.toEqual({
+ uri: 'file:///tmp/converted.jpg',
+ name: 'IMG_0001.jpg',
+ mimeType: 'image/jpeg',
+ // 转码后 size 必须归 0:管线据此 stat 真实大小,否则沿用原 HEIC 字节数会撞大小校验。
+ size: 0,
+ });
+ expect(convertToJpeg).toHaveBeenCalledWith('file:///tmp/IMG_0001.HEIF');
+ });
+
+ it('MIME 明示 image/heic 即使文件名扩展名像白名单也转 JPEG(MIME 为准)', async () => {
+ const convertToJpeg = vi.fn().mockResolvedValue('file:///tmp/shot.jpg');
+ const candidate = buildMobileImageAttachmentCandidate({
+ uri: 'file:///tmp/screenshot.png',
+ fileName: 'screenshot.png',
+ mimeType: 'image/heic',
+ }, 3, { convertToJpeg });
+ await expect(candidate.resolve!()).resolves.toEqual({
+ uri: 'file:///tmp/shot.jpg',
+ name: 'screenshot.jpg',
+ mimeType: 'image/jpeg',
+ size: 0,
+ });
+ });
+
+ it('未知扩展名(如 .tiff)同样归一;无扩展名但 MIME 为 jpeg 的 ph:// 资产不转', () => {
+ expect(buildMobileImageAttachmentCandidate({ uri: 'file:///tmp/x.tiff', fileName: 'x.tiff', mimeType: 'image/tiff' }, 0))
+ .toHaveProperty('resolve');
+ expect(buildMobileImageAttachmentCandidate({ uri: 'ph://asset-no-ext', mimeType: 'image/jpeg' }, 0))
+ .not.toHaveProperty('resolve');
+ });
+
+ it('needsJpegConversion 判定与粘贴链路口径一致', () => {
+ expect(needsJpegConversion('a.heic', null)).toBe(true);
+ expect(needsJpegConversion('a.jpg', 'image/heif')).toBe(true);
+ expect(needsJpegConversion('a.jpg', 'image/jpeg')).toBe(false);
+ expect(needsJpegConversion('a.GIF', undefined)).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/session/mobileImageAttachment.ts b/apps/mobile/src/session/mobileImageAttachment.ts
index 102a1dfe76..cc2be97146 100644
--- a/apps/mobile/src/session/mobileImageAttachment.ts
+++ b/apps/mobile/src/session/mobileImageAttachment.ts
@@ -15,18 +15,40 @@ export type MobileImageAttachmentCandidate = MobileAttachmentUploadCandidate & {
uri: string;
width?: number | null;
height?: number | null;
+ /**
+ * 仅 HEIC / HEIF 等非白名单格式带此钩子:任务开跑时就地转 JPEG(#3889)。
+ * 托盘预览仍用原始 uri;返回字段由上传管线覆盖到 candidate 上。
+ */
+ resolve?: () => Promise<{ uri: string; name: string; mimeType: string; size: number }>;
};
+/** JPEG 转换器(可注入,单测用假实现避免触碰原生模块)。 */
+export type MobileImageJpegConverter = (uri: string) => Promise<string>;
+
+export interface BuildMobileImageAttachmentCandidateDeps {
+ convertToJpeg?: MobileImageJpegConverter;
+}
+
+/**
+ * 附件白名单与下游模型图像接口都只认这四种(与 attachments.ts 的
+ * SUPPORTED_IMAGE_EXTS、pastedImageAttachment 的 WHITELISTED_IMAGE_EXTS 同口径)。
+ */
+const WHITELISTED_IMAGE_EXTS = new Set(['.jpeg', '.jpg', '.png', '.gif', '.webp']);
+const HEIC_MIME_TYPES = new Set(['image/heic', 'image/heif', 'image/heic-sequence', 'image/heif-sequence']);
+/** 与 useContextSheetMediaAssets / pastedImageAttachment 同口径:0.9 视觉无损,体积可控。 */
+const IMAGE_JPEG_COMPRESS = 0.9;
+
export function buildMobileImageAttachmentCandidate(
asset: MobileImagePickerAssetLike,
index: number,
+ deps: BuildMobileImageAttachmentCandidateDeps = {},
): MobileImageAttachmentCandidate {
const uri = asset.uri?.trim();
if (!uri) throw new Error(i18n.t('composer.upload.noImageRead'));
const mimeType = normalizeImageMimeType(asset.mimeType, uri);
const name = normalizeImageFileName(asset.fileName, uri, mimeType, index);
const size = Number(asset.fileSize ?? 0);
- return {
+ const candidate: MobileImageAttachmentCandidate = {
uri,
name,
size: Number.isFinite(size) && size > 0 ? size : 0,
@@ -34,6 +56,50 @@ export function buildMobileImageAttachmentCandidate(
width: asset.width,
height: asset.height,
};
+ if (!needsJpegConversion(name, mimeType)) return candidate;
+ // 系统 Photos picker / 相机可能直接交出 HEIC / HEIF(iOS 原生格式):MIME 原样
+ // 放行、文件名保留 .heic,而 preprocess 只在大图 / 超长边时才顺带 JPEG 重编码,
+ // 小图会原样直传进只认 jpeg/png/gif/webp 的下游,表现为「截图发送失败」(#3889)。
+ // 与相册 ph:// 链路、粘贴链路同一口径:在就位钩子里就地转 JPEG。
+ const convert = deps.convertToJpeg ?? convertMobileImageToJpegNative;
+ return {
+ ...candidate,
+ resolve: async () => ({
+ uri: await convert(uri),
+ name: replaceImageFileExt(name, 'jpg'),
+ mimeType: 'image/jpeg',
+ // 转码后字节数已变:置 0 让管线 stat 转换产物的真实大小。沿用 picker 给的原
+ // HEIC 字节数会在 uploadMobileAttachmentFromFile 的大小一致性校验处被拒
+ //(Attachment size changed),恰好卡死本次要修的小图场景(review P1)。
+ size: 0,
+ }),
+ };
+}
+
+/** 文件名扩展名不在白名单、或 MIME 明示 HEIC / HEIF → 需转 JPEG 才能进上传管线。 */
+export function needsJpegConversion(name: string, mimeType: string | null | undefined): boolean {
+ const mime = mimeType?.trim().toLowerCase() ?? '';
+ if (HEIC_MIME_TYPES.has(mime)) return true;
+ return !WHITELISTED_IMAGE_EXTS.has(extractRemoteFileExt(name));
+}
+
+/**
+ * 默认 JPEG 转换:expo-image-manipulator 动态 import,保证本模块在 vitest(node)
+ * 下可导入;测试路径经 deps.convertToJpeg 注入。粘贴链路复用同一实现。
+ */
+export async function convertMobileImageToJpegNative(uri: string): Promise<string> {
+ const { ImageManipulator, SaveFormat } = await import('expo-image-manipulator');
+ const context = ImageManipulator.manipulate(uri);
+ const image = await context.renderAsync();
+ try {
+ const saved = await image.saveAsync({ compress: IMAGE_JPEG_COMPRESS, format: SaveFormat.JPEG });
+ return saved.uri;
+ } finally {
+ // render 结果持有 native GPU 纹理,不显式 release 会在 GC 前持续占用
+ //(与 useContextSheetMediaAssets / mobileImagePreprocess 同模式)。
+ image.release();
+ context.release();
+ }
}
export function assertMobileImageSize(size: number): void {
@@ -69,6 +135,12 @@ function normalizeImageFileName(
return `mobile-image-${index + 1}.${extForImageMimeType(mimeType)}`;
}
+function replaceImageFileExt(name: string, targetExt: string): string {
+ const ext = extractRemoteFileExt(name);
+ const base = ext ? name.slice(0, name.length - ext.length) : name;
+ return `${base}.${targetExt}`;
+}
+
function basenameFromUri(uri: string): string {
const withoutQuery = uri.split(/[?#]/)[0] ?? uri;
const slash = Math.max(withoutQuery.lastIndexOf('/'), withoutQuery.lastIndexOf('\\'));
diff --git a/apps/mobile/src/session/pastedImageAttachment.ts b/apps/mobile/src/session/pastedImageAttachment.ts
index 8e5b41e907..61130f9d80 100644
--- a/apps/mobile/src/session/pastedImageAttachment.ts
+++ b/apps/mobile/src/session/pastedImageAttachment.ts
@@ -8,9 +8,8 @@
* 就地转 JPEG,避免在链路下游变成不可用附件(同 Context 面板相册链路的处理)。
*/
import { extractRemoteFileExt } from '@/session/attachments';
+import { convertMobileImageToJpegNative } from '@/session/mobileImageAttachment';
-/** 与 useContextSheetMediaAssets 同口径:iOS 原生格式,白名单与下游模型接口都不收。 */
-const PASTED_JPEG_COMPRESS = 0.9;
export const COMPOSER_PASTED_IMAGE_FILE_PREFIX = 'cindy-composer-paste-';
const WHITELISTED_IMAGE_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp'] as const;
@@ -83,7 +82,7 @@ export async function resolvePastedImageAsset(
mimeType: mimeTypeForPastedImageExt(classified.ext),
};
}
- const convert = deps.convertToJpeg ?? convertToJpegNative;
+ const convert = deps.convertToJpeg ?? convertMobileImageToJpegNative;
return {
uri: await convert(uri),
fileName: buildPastedImageFileName(index, 'jpg'),
@@ -91,14 +90,6 @@ export async function resolvePastedImageAsset(
};
}
-/** 默认 JPEG 转换:同 resolveContextSheetMediaAssetForUpload 的 HEIC 处理方式。 */
-async function convertToJpegNative(uri: string): Promise<string> {
- const { ImageManipulator, SaveFormat } = await import('expo-image-manipulator');
- const image = await ImageManipulator.manipulate(uri).renderAsync();
- const saved = await image.saveAsync({ compress: PASTED_JPEG_COMPRESS, format: SaveFormat.JPEG });
- return saved.uri;
-}
-
function basenameFromUri(uri: string): string {
const withoutQuery = uri.split(/[?#]/)[0] ?? uri;
const slash = Math.max(withoutQuery.lastIndexOf('/'), withoutQuery.lastIndexOf('\\'));