Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): use Android system photo picker (#3397)
bobob4395047d5d5
diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex ec24a7504b..203308d5b1 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -43,7 +43,15 @@"monochromeImage": "./assets/android-icon-monochrome.png"},"predictiveBackGestureEnabled": false,- "permissions": ["android.permission.MODIFY_AUDIO_SETTINGS"]+ "permissions": ["android.permission.MODIFY_AUDIO_SETTINGS"],+ "blockedPermissions": [+ "android.permission.READ_EXTERNAL_STORAGE",+ "android.permission.WRITE_EXTERNAL_STORAGE",+ "android.permission.READ_MEDIA_AUDIO",+ "android.permission.READ_MEDIA_IMAGES",+ "android.permission.READ_MEDIA_VIDEO",+ "android.permission.READ_MEDIA_VISUAL_USER_SELECTED"+ ]},"web": {"favicon": "./assets/favicon.png"@@ -134,7 +142,8 @@{"photosPermission": "Cindy needs photo library access to show recent photos and screenshots for quick attaching.","savePhotosPermission": false,- "isAccessMediaLocationEnabled": false+ "isAccessMediaLocationEnabled": false,+ "granularPermissions": []}]],diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 564c472446..616964341d 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -224,6 +224,7 @@ import {} from '@/session/useComposerImageAnnotations';import { buildMediaPayload } from '@/session/messagePayload';import type { MobileMessageGalleryImage } from '@/session/messageGallery';+import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';import {prefetchContextSheetMediaAssets,resolveContextSheetMediaAssetForUpload,@@ -1102,6 +1103,7 @@ export default function SessionScreen() {// Context 面板(+ 号弹出的可拖动 sheet):open + 面板内子视图(主视图 / 截图列表 / 目标模式)。const [contextSheetOpen, setContextSheetOpen] = useState(false);const [contextSheetView, setContextSheetView] = useState<'main' | 'screenshots' | 'goal'>('main');+ const contextSheetMediaLibraryEnabled = canBrowsePhotoLibraryDirectly(Platform.OS);// 模型 + 权限浮窗(ContextSheet 同款 Modal,含二级「模型选项 / 权限」叠层)。const [modelSheetOpen, setModelSheetOpen] = useState(false);// 权限模式独立浮窗(composer 左侧图标钮点开,与模型浮窗同属 composer 激活态)。@@ -7850,10 +7852,12 @@ export default function SessionScreen() {useEffect(() => {if (!contextSheetOpen) setPendingMediaAssets([]);}, [contextSheetOpen]);- // 进页面就静默预取最近照片(仅已授权时),打开 + 面板即刻出图。+ // iOS 进页面就静默预取最近照片(仅已授权时),打开 + 面板即刻出图;Android 统一走系统选择器。useEffect(() => {- void prefetchContextSheetMediaAssets('recent');- }, []);+ if (contextSheetMediaLibraryEnabled) {+ void prefetchContextSheetMediaAssets('recent');+ }+ }, [contextSheetMediaLibraryEnabled]);// 目标模式:面板打开时拉一次快照(push 只送变更);动作后再拉一次收敛,避免依赖单一 push。const goalStatus = useSessionGoalStatus(sessionId);@@ -8986,15 +8990,17 @@ export default function SessionScreen() {>{contextSheetView === 'main' ? (<>- <RecentPhotosStrip- busyAssetIds={uploadingMediaAssetIds}- disabled={!canUseComposer}- enabled={contextSheetOpen}- onToggleAsset={toggleMediaAssetAttachment}- pendingOrder={pendingMediaOrder}- selectedAssetIds={selectedMediaAssetIds}- testID="session.contextSheetPhotos"- />+ {contextSheetMediaLibraryEnabled ? (+ <RecentPhotosStrip+ busyAssetIds={uploadingMediaAssetIds}+ disabled={!canUseComposer}+ enabled={contextSheetOpen}+ onToggleAsset={toggleMediaAssetAttachment}+ pendingOrder={pendingMediaOrder}+ selectedAssetIds={selectedMediaAssetIds}+ testID="session.contextSheetPhotos"+ />+ ) : null}<ContextSheetGroup label={t('session.common.groupMode')}>{planModeSupported ? (// 点击即切换计划模式并关面板(产品决策,不做开关);已开启时显示 ✓,再点退出。@@ -9035,14 +9041,16 @@ export default function SessionScreen() {onPress={() => void addLocalImageAttachments('library')}testID="session.contextSheetPhotoRow"/>- <ContextSheetRow- disabled={!canUseComposer}- icon={<Scan color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />}- label={t('session.common.screenshot')}- onPress={() => setContextSheetView('screenshots')}- testID="session.contextSheetScreenshotsRow"- trailing="chevron"- />+ {contextSheetMediaLibraryEnabled ? (+ <ContextSheetRow+ disabled={!canUseComposer}+ icon={<Scan color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />}+ label={t('session.common.screenshot')}+ onPress={() => setContextSheetView('screenshots')}+ testID="session.contextSheetScreenshotsRow"+ trailing="chevron"+ />+ ) : null}<ContextSheetRowaccessibilityHint={composerSendUnavailableReason ?? undefined}disabled={!canUseComposer}@@ -9066,7 +9074,7 @@ export default function SessionScreen() {</Text>) : null}</>- ) : contextSheetView === 'screenshots' ? (+ ) : contextSheetView === 'screenshots' && contextSheetMediaLibraryEnabled ? (<ScreenshotsGridbusyAssetIds={uploadingMediaAssetIds}contentWidth={Math.min(windowDimensions.width, nativeShellLayout.contentMaxWidth) - 40}diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 2fe416b5be..2812b30ef9 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -130,6 +130,7 @@ import {resolveContextSheetMediaAssetForUpload,type ContextSheetMediaAsset,} from '@/session/useContextSheetMediaAssets';+import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';import {detectComposerTrigger,filterAtResources,@@ -497,6 +498,7 @@ export default function NewRemoteSessionScreen() {// Context 面板(+ 号弹出的可拖动 sheet):open + 子视图(主视图 / 截图列表 / 目标草稿)。const [contextSheetOpen, setContextSheetOpen] = useState(false);const [contextSheetView, setContextSheetView] = useState<'main' | 'screenshots' | 'goal'>('main');+ const contextSheetMediaLibraryEnabled = canBrowsePhotoLibraryDirectly(Platform.OS);// 目标模式(对齐桌面 NewMakerDraftRoute.handleCreateGoal):填完表单直接建会话 + setGoal,// 被控端落目标消息并自动开跑第一轮,成功后跳转会话页。const [goalBusy, setGoalBusy] = useState(false);@@ -3830,10 +3832,12 @@ export default function NewRemoteSessionScreen() {useEffect(() => {if (!contextSheetOpen) setPendingMediaAssets([]);}, [contextSheetOpen]);- // 进页面就静默预取最近照片(仅已授权时),打开 + 面板即刻出图。+ // iOS 进页面就静默预取最近照片(仅已授权时),打开 + 面板即刻出图;Android 统一走系统选择器。useEffect(() => {- void prefetchContextSheetMediaAssets('recent');- }, []);+ if (contextSheetMediaLibraryEnabled) {+ void prefetchContextSheetMediaAssets('recent');+ }+ }, [contextSheetMediaLibraryEnabled]);// Context 面板「计划模式」入口,双路径(#494 迁移):// - 新协议(capabilities.planMode.supported):本地布尔草稿态,创建会话后经@@ -5755,15 +5759,17 @@ export default function NewRemoteSessionScreen() {>{contextSheetView === 'main' ? (<>- <RecentPhotosStrip- busyAssetIds={uploadingMediaAssetIds}- disabled={creating}- enabled={contextSheetOpen}- onToggleAsset={toggleMediaAssetAttachment}- pendingOrder={pendingMediaOrder}- selectedAssetIds={selectedMediaAssetIds}- testID="newSession.contextSheetPhotos"- />+ {contextSheetMediaLibraryEnabled ? (+ <RecentPhotosStrip+ busyAssetIds={uploadingMediaAssetIds}+ disabled={creating}+ enabled={contextSheetOpen}+ onToggleAsset={toggleMediaAssetAttachment}+ pendingOrder={pendingMediaOrder}+ selectedAssetIds={selectedMediaAssetIds}+ testID="newSession.contextSheetPhotos"+ />+ ) : null}<ContextSheetGroup label={t('session.common.groupMode')}>{planModeSupported ? (// 点击即切换计划模式并关面板(产品决策,不做开关);已开启时显示 ✓,再点退出。@@ -5796,14 +5802,16 @@ export default function NewRemoteSessionScreen() {onPress={() => void addLocalImageAttachments('library')}testID="newSession.contextSheetPhotoRow"/>- <ContextSheetRow- disabled={creating}- icon={<Scan color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />}- label={t('session.common.screenshot')}- onPress={() => setContextSheetView('screenshots')}- testID="newSession.contextSheetScreenshotsRow"- trailing="chevron"- />+ {contextSheetMediaLibraryEnabled ? (+ <ContextSheetRow+ disabled={creating}+ icon={<Scan color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />}+ label={t('session.common.screenshot')}+ onPress={() => setContextSheetView('screenshots')}+ testID="newSession.contextSheetScreenshotsRow"+ trailing="chevron"+ />+ ) : null}<ContextSheetRowdisabled={creating}icon={<Camera color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />}@@ -5825,7 +5833,7 @@ export default function NewRemoteSessionScreen() {</Text>) : null}</>- ) : contextSheetView === 'screenshots' ? (+ ) : contextSheetView === 'screenshots' && contextSheetMediaLibraryEnabled ? (<ScreenshotsGridbusyAssetIds={uploadingMediaAssetIds}contentWidth={windowDimensions.width - 40}diff --git a/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts b/apps/mobile/src/__tests__/contextSheetMediaAssets.test.tsindex 0f60ffa7f0..bd09b86363 100644--- a/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts+++ b/apps/mobile/src/__tests__/contextSheetMediaAssets.test.ts@@ -58,6 +58,15 @@ beforeEach(() => {});describe('prefetchContextSheetMediaAssets', () => {+ it('Android 不读取媒体库,由系统照片选择器承担图片选择', async () => {+ platform.os = 'android';++ await prefetchContextSheetMediaAssets('recent');++ expect(mediaLibrary.getPermissionsAsync).not.toHaveBeenCalled();+ expect(mediaLibrary.getAssetsAsync).not.toHaveBeenCalled();+ });+it('iOS 受限照片权限不在页面预取时读取资产,避免每次冷启动弹系统提醒', async () => {platform.os = 'ios';mediaLibrary.getPermissionsAsync.mockResolvedValue({diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.tsindex 5b59dc9cec..738706b758 100644--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts@@ -477,6 +477,31 @@ describe('mobile native app config', () => {expect(appJson.expo.ios.infoPlist.UIBackgroundModes ?? []).not.toContain('audio');});+ it('uses the Android system photo picker without broad media permissions', () => {+ const appJson = JSON.parse(+ readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),+ );+ const mediaLibraryPlugin = appJson.expo.plugins.find(+ (plugin: unknown) =>+ Array.isArray(plugin) && plugin[0] === 'expo-media-library',+ );++ expect(mediaLibraryPlugin).toEqual([+ 'expo-media-library',+ expect.objectContaining({ granularPermissions: [] }),+ ]);+ expect(appJson.expo.android.blockedPermissions).toEqual(+ expect.arrayContaining([+ 'android.permission.READ_EXTERNAL_STORAGE',+ 'android.permission.WRITE_EXTERNAL_STORAGE',+ 'android.permission.READ_MEDIA_AUDIO',+ 'android.permission.READ_MEDIA_IMAGES',+ 'android.permission.READ_MEDIA_VIDEO',+ 'android.permission.READ_MEDIA_VISUAL_USER_SELECTED',+ ]),+ );+ });+it('keeps Metro React resolution on the mobile app dependency', () => {const metroConfig = readFileSync(resolve(process.cwd(), 'metro.config.js'),diff --git a/apps/mobile/src/__tests__/photoLibraryPolicy.test.ts b/apps/mobile/src/__tests__/photoLibraryPolicy.test.tsnew file mode 100644index 0000000000..d938435f68--- /dev/null+++ b/apps/mobile/src/__tests__/photoLibraryPolicy.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest';+import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';++describe('photo library policy', () => {+ it('keeps direct photo-library browsing on iOS', () => {+ expect(canBrowsePhotoLibraryDirectly('ios')).toBe(true);+ });++ it('requires Android and web to use system pickers instead', () => {+ expect(canBrowsePhotoLibraryDirectly('android')).toBe(false);+ expect(canBrowsePhotoLibraryDirectly('web')).toBe(false);+ });+});diff --git a/apps/mobile/src/session/photoLibraryPolicy.ts b/apps/mobile/src/session/photoLibraryPolicy.tsnew file mode 100644index 0000000000..120564c587--- /dev/null+++ b/apps/mobile/src/session/photoLibraryPolicy.ts@@ -0,0 +1,11 @@+/**+ * Google Play only permits broad Android photo-library access when it is+ * essential to the app's primary purpose. Cindy only attaches user-selected+ * images, so Android must use the system photo picker instead.+ *+ * iOS keeps the existing recent-photo and screenshot surfaces, whose asset+ * resolution still depends on expo-media-library.+ */+export function canBrowsePhotoLibraryDirectly(platform: string): boolean {+ return platform === 'ios';+}diff --git a/apps/mobile/src/session/useContextSheetMediaAssets.ts b/apps/mobile/src/session/useContextSheetMediaAssets.tsindex 1d97f80b24..f517128a9a 100644--- a/apps/mobile/src/session/useContextSheetMediaAssets.ts+++ b/apps/mobile/src/session/useContextSheetMediaAssets.ts@@ -6,14 +6,15 @@ import * as MediaLibrary from 'expo-media-library/legacy';import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';import { i18n } from '@/i18n';import { MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE } from '@/session/mobileImagePreprocess';+import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';/** Context 面板媒体列表的单个资产(展示 + 附加所需的最小字段)。 */export interface ContextSheetMediaAsset {id: string;filename: string;- /** 展示用 URI(iOS ph:// / Android content://);渲染走 expo-image,RN Image 在新架构下不支持 ph://。 */+ /** 展示用 URI(iOS 通常为 ph://);渲染走 expo-image,RN Image 在新架构下不支持 ph://。 */uri: string;- /** 列表查询已返回的尺寸;Android full info 权限失败时供上传预处理继续使用。 */+ /** 列表查询已返回的尺寸;解析完整资产信息失败时供上传预处理继续使用。 */width?: number;height?: number;}@@ -44,19 +45,13 @@ const DEFAULT_FIRST: Record<ContextSheetMediaKind, number> = { recent: 24, scree/** 按 kind 拉一页资产(权限已就绪的前提下)。 */async function fetchAssets(kind: ContextSheetMediaKind, first: number): Promise<ContextSheetMediaAsset[] | null> {- let album: MediaLibrary.Album | null = null;- if (kind === 'screenshots' && Platform.OS === 'android') {- album = await MediaLibrary.getAlbumAsync('Screenshots');- if (!album) return [];- }const page = await MediaLibrary.getAssetsAsync({first,mediaType: [MediaLibrary.MediaType.photo],sortBy: [[MediaLibrary.SortBy.creationTime, false]],- ...(kind === 'screenshots' && Platform.OS === 'ios'+ ...(kind === 'screenshots'? { mediaSubtypes: ['screenshot' as MediaLibrary.MediaSubtype] }: {}),- ...(album ? { album } : {}),});return page.assets.map((asset) => ({id: asset.id,@@ -68,12 +63,12 @@ async function fetchAssets(kind: ContextSheetMediaKind, first: number): Promise<}/**- * 页面挂载时静默预取(打开面板即刻出图)。只在照片权限已授予、且 iOS 不是受限访问时拉取——+ * iOS 页面挂载时静默预取(打开面板即刻出图)。只在照片权限已授予、且不是受限访问时拉取——* iOS 受限访问虽然 granted=true,首次读取资产仍可能触发系统自动提醒;预取绝不能打断用户。* 首次授权和受限资产读取仍由用户打开面板后触发;失败静默,面板打开时照常加载。*/export async function prefetchContextSheetMediaAssets(kind: ContextSheetMediaKind = 'recent'): Promise<void> {- if (Platform.OS === 'web' || assetsCache.has(kind)) return;+ if (!canBrowsePhotoLibraryDirectly(Platform.OS) || assetsCache.has(kind)) return;try {const permission = await MediaLibrary.getPermissionsAsync(false, ['photo']);if (!permission.granted) return;@@ -86,12 +81,11 @@ export async function prefetchContextSheetMediaAssets(kind: ContextSheetMediaKin}/**- * Context 面板的相册资产加载 hook(最近照片条 / 截图列表共用)。+ * Context 面板的 iOS 相册资产加载 hook(最近照片条 / 截图列表共用)。** enabled 变 true(面板打开)时才请求权限并加载,面板关闭不清缓存——再次打开先显示* 旧列表再后台刷新,遵守规则 7(先有内容再刷新,不闪空白帧)。- * 截图过滤:iOS 用 mediaSubtypes=['screenshot'];Android 找 Screenshots 相册,- * 找不到则退化为空列表(UI 显示「没有找到截图」)。+ * 截图过滤使用 mediaSubtypes=['screenshot'];Android 不挂载此界面,统一走系统照片选择器。*/export function useContextSheetMediaAssets(input: {enabled: boolean;@@ -107,7 +101,7 @@ export function useContextSheetMediaAssets(input: {const load = useCallback(async (requestIfNeeded: boolean) => {const seq = ++loadSeqRef.current;- if (Platform.OS === 'web') {+ if (!canBrowsePhotoLibraryDirectly(Platform.OS)) {setStatus('unavailable');return;}diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.tsindex ee14dee4da..49184c51e7 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -20,6 +20,7 @@ import * as DocumentPicker from 'expo-document-picker';import * as FileSystem from 'expo-file-system/legacy';import * as ImagePicker from 'expo-image-picker';import { formatRemoteError } from '@/device-link/remoteStatus';+import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';import {MOBILE_MAX_ATTACHMENTS,assertMobileDocumentSize,@@ -414,15 +415,17 @@ export function useMobileLocalAttachments(optionsRef.current.onError(t('composer.upload.simulatorNoCamera'));return;}- const permission = source === 'camera'- ? await ImagePicker.requestCameraPermissionsAsync()- : await ImagePicker.requestMediaLibraryPermissionsAsync(false);- if (!isAttachmentScopeActive()) return;- if (!permission.granted) {- optionsRef.current.onError(source === 'camera'- ? t('composer.upload.cameraPermission')- : t('composer.upload.photoPermission'));- return;+ if (source === 'camera' || canBrowsePhotoLibraryDirectly(Platform.OS)) {+ const permission = source === 'camera'+ ? await ImagePicker.requestCameraPermissionsAsync()+ : await ImagePicker.requestMediaLibraryPermissionsAsync(false);+ if (!isAttachmentScopeActive()) return;+ if (!permission.granted) {+ optionsRef.current.onError(source === 'camera'+ ? t('composer.upload.cameraPermission')+ : t('composer.upload.photoPermission'));+ return;+ }}const picked = source === 'camera'