Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): route iOS shared content to tasks and companions
Chrisc6ba2ad7d3f3
diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex b7fc3702e7..0cf4829372 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -100,12 +100,17 @@"./plugins/with-communication-notifications","expo-secure-store","expo-web-browser",+ "./plugins/with-incoming-share-files",["expo-sharing",{"ios": {"enabled": true,"activationRule": {+ "supportsText": true,+ "supportsWebUrlWithMaxCount": 20,+ "supportsWebPageWithMaxCount": 20,+ "supportsMovieWithMaxCount": 20,"supportsFileWithMaxCount": 20,"supportsImageWithMaxCount": 20}@@ -140,7 +145,6 @@}}],- "./plugins/with-incoming-share-files","./plugins/with-remote-desktop-presentation","./plugins/with-foreground-only-audio",[diff --git a/apps/mobile/app/incoming-share.tsx b/apps/mobile/app/incoming-share.tsxnew file mode 100644index 0000000000..8642062579--- /dev/null+++ b/apps/mobile/app/incoming-share.tsx@@ -0,0 +1,151 @@+import { useEffect, useState } from 'react';+import { ActivityIndicator, Pressable, ScrollView, StyleSheet, View } from 'react-native';+import { useIsFocused, useNavigation, useRouter } from 'expo-router';+import { usePreventRemove } from 'expo-router/react-navigation';+import { SafeAreaView } from 'react-native-safe-area-context';+import { useTranslation } from 'react-i18next';+import { resolveRemoteText } from '@cindy/device-link';+import { Text, TextInput } from '@/components/AppText';+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { toDeviceListItems } from '@/device-link/devices';+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';+import { useAuth } from '@/auth/AuthContext';+import { discardIncomingShareBatch, incomingShareDestination, incomingShareText, selectIncomingShareDestination, useIncomingShareBatch } from '@/session/incomingShare';+import { useTeammateRoster } from '@/session/useTeammateRoster';+import { teammateResourceRoute } from '@/session/teammateNavigation';+import { remoteSessionStore } from '@/session/remoteSessionStore';+import type { RemoteSession } from '@/session/types';+import { fontWeight, lineHeight, radius, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';++type Task = { deviceId: string; deviceName: string; session: RemoteSession };++/** A destination chooser, not a second sending pipeline. Nothing is sent by selecting a row. */+export default function IncomingShareScreen() {+ const batch = useIncomingShareBatch();+ const focused = useIsFocused();+ const router = useRouter();+ const navigation = useNavigation();+ const { t, i18n } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const { accountGeneration } = useAuth();+ const { readDeviceList, openLink, invoke, status, presenceVersion } = useDeviceLink();+ const revoked = useRevokedDevices();+ const roster = useTeammateRoster(focused && !!batch);+ const [query, setQuery] = useState('');+ const [dismissError, setDismissError] = useState<string | null>(null);+ const [tasks, setTasks] = useState<Task[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(false);+ const [attempt, setAttempt] = useState(0);+ useEffect(() => {+ if (!focused || !batch) return;+ const owner = getMobileAuthOwner();+ let disposed = false;+ const current = () => !disposed && isMobileAuthOwnerCurrent(owner);+ setTasks([]); setLoading(true); setError(false);+ void readDeviceList().then(async response => {+ const devices = toDeviceListItems(response.devices, Date.now(), revoked);+ const groups: Task[][] = devices.map(() => []);+ let failed = false;+ await Promise.all(devices.map(async ({ device, canOpen }, index) => {+ const publish = (sessions: RemoteSession[]) => {+ groups[index] = sessions.filter(session => session.status === 'active' && session.source !== 'bot'+ && session.orcaRole !== 'worker').map(session => ({ deviceId: device.deviceId, deviceName: device.name, session }));+ if (current()) setTasks(groups.flat());+ };+ if (!current()) return;+ publish(remoteSessionStore.getSessions().filter(session => session.deviceLinkDeviceId === device.deviceId));+ if (!canOpen) return;+ try {+ await openLink(device.deviceId);+ const sessions = await invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list',+ [500, 'active', { includePinned: true, fresh: true }], { preSend: () => {+ if (!current()) throw new Error('INCOMING_SHARE_PICKER_CLOSED');+ } });+ if (current()) publish(Array.isArray(sessions) ? sessions : []);+ } catch { failed = true; }+ }));+ if (current()) setError(failed);+ }).catch(() => { if (current()) setError(true); })+ .finally(() => { if (current()) setLoading(false); });+ return () => { disposed = true; };+ }, [focused, batch?.id, accountGeneration, readDeviceList, openLink, invoke, status, presenceVersion, attempt, revoked]);+ const needle = query.normalize('NFKC').trim().toLocaleLowerCase(i18n.language);+ const matches = (title: string) => title.normalize('NFKC').toLocaleLowerCase(i18n.language).includes(needle);+ const text = batch ? incomingShareText(batch.payloads) : '';+ const files = batch?.payloads.filter(item => item.shareType !== 'text' && item.shareType !== 'url') ?? [];+ const choose = (destination: string, action: () => void) => {+ if (batch && selectIncomingShareDestination(batch.id, destination)) action();+ };+ // Covers the header, iOS edge swipe and system back without cancelling a+ // forward push to the chosen composer. Failed acknowledgement keeps the share.+ usePreventRemove(!!batch, ({ data }) => {+ try { if (batch) discardIncomingShareBatch(batch.id); }+ catch { setDismissError(t('composer.upload.shareReceiveFailed')); return; }+ navigation.dispatch(data.action);+ });+ const back = () => router.canGoBack() ? router.back() : router.replace('/');+ return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>+ <SimpleStackHeader title={t('composer.incomingShare.title')} onBack={back} />+ {!!dismissError && <Text style={styles.note}>{dismissError}</Text>}+ {!batch ? <Text style={styles.note}>{t('composer.incomingShare.empty')}</Text> : <>+ <View style={styles.preview}>+ {!!text && <Text numberOfLines={4} style={styles.body}>{text}</Text>}+ {files.slice(0, 3).map((file, index) => <Text key={index} numberOfLines={1} style={styles.note}>+ {file.originalName || t('composer.incomingShare.file')}+ </Text>)}+ {files.length > 3 && <Text style={styles.note}>{t('composer.incomingShare.fileCount', { count: files.length })}</Text>}+ <Text style={styles.note}>{t('composer.incomingShare.hint')}</Text>+ </View>+ <TextInput value={query} onChangeText={setQuery} style={styles.search}+ placeholder={t('composer.incomingShare.search')} accessibilityLabel={t('composer.incomingShare.search')}+ placeholderTextColor={colors.textPlaceholder} autoCorrect={false} />+ <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.list}>+ <Pressable accessibilityRole="button" style={styles.row} onPress={() => choose('new', () => router.push('/sessions/new'))}>+ <Text style={styles.title}>{t('composer.incomingShare.newTask')}</Text>+ </Pressable>+ <Text style={styles.sectionLabel}>{t('composer.incomingShare.companions')}</Text>+ {roster.items.filter(row => matches(resolveRemoteText(row.item.display.title, i18n.language))).map(row => {+ const route = teammateResourceRoute(row, i18n.language);+ const conversation = row.item.links.find(link => link.rel === 'conversation')?.target;+ return <Pressable key={row.key} accessibilityRole="button" style={styles.row}+ disabled={conversation?.kind !== 'session'} onPress={() => {+ if (conversation?.kind === 'session') choose(incomingShareDestination(row.host.deviceId, conversation.sessionId), () => router.push(route));+ }}>+ <Text style={styles.title}>{resolveRemoteText(row.item.display.title, i18n.language)}</Text>+ <Text style={styles.note}>{row.host.deviceName}{conversation?.kind !== 'session' ? ` · ${t('composer.incomingShare.unavailable')}` : ''}</Text>+ </Pressable>;+ })}+ {roster.loading && <ActivityIndicator color={colors.textSecondary} />}+ {!roster.loading && !roster.items.length && <Text style={styles.note}>{t('composer.incomingShare.noCompanions')}</Text>}+ {!!roster.error && <Pressable style={styles.row} onPress={() => void roster.refresh()}><Text style={styles.note}>{t('composer.incomingShare.retry')}</Text></Pressable>}+ <Text style={styles.sectionLabel}>{t('composer.incomingShare.tasks')}</Text>+ {tasks.filter(row => matches(row.session.title)).map(row => <Pressable+ key={incomingShareDestination(row.deviceId, row.session.id)} accessibilityRole="button" style={styles.row}+ onPress={() => choose(incomingShareDestination(row.deviceId, row.session.id), () => router.push({+ pathname: '/sessions/[sessionId]', params: { deviceId: row.deviceId, deviceName: row.deviceName, sessionId: row.session.id },+ }))}>+ <Text style={styles.title}>{row.session.title}</Text><Text style={styles.note}>{row.deviceName}</Text>+ </Pressable>)}+ {loading && <ActivityIndicator color={colors.textSecondary} />}+ {!loading && !tasks.length && <Text style={styles.note}>{t('composer.incomingShare.noTasks')}</Text>}+ {error && <Pressable style={styles.row} onPress={() => setAttempt(value => value + 1)}><Text style={styles.note}>{t('composer.incomingShare.retry')}</Text></Pressable>}+ </ScrollView>+ </>}+ </SafeAreaView>;+}+const makeStyles = (c: ThemeColors) => StyleSheet.create({+ root: { flex: 1, backgroundColor: c.surface },+ preview: { margin: spacing.md, gap: spacing.xs },+ search: { marginHorizontal: spacing.md, padding: spacing.md, borderRadius: radius.control,+ backgroundColor: c.surfaceChip, color: c.textPrimary, fontSize: typeScale.bodySmall, fontWeight: fontWeight.regular },+ list: { padding: spacing.md },+ row: { minHeight: 48, paddingVertical: spacing.md, gap: spacing.xs },+ title: { fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium, color: c.textPrimary },+ body: { fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular, color: c.textPrimary },+ note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: c.textSecondary },+ sectionLabel: { marginTop: spacing.md, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold, color: c.textTertiary },+});diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 113586d4d4..30bea42e38 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1,3 +1,5 @@+import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';+import { incomingShareDestination } from '@/session/incomingShare';import { useSessionHistorySearch } from '@/session/useSessionHistorySearch';import { useContentRecoveryDiagnostics } from '@/debug/useContentRecoveryDiagnostics';import { modelNeedsReselection } from '@/session/modelReselection';@@ -3226,6 +3228,14 @@ function SessionScreenContent() {applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);}, [applyComposerDraft]);+ useIncomingShareComposer({+ destination: incomingShareDestination(deviceId, sessionId),+ ready: composerDraftHydrated && canUseComposer && !queueEditingRef.current,+ appendText: text => setComposerDraft(current => [current, text].filter(Boolean).join('\n\n')),+ attachmentCount: attachments.length,+ enqueueUploads, getPendingUploadCount, onError: setAttachmentError,+ });+const writeVoiceDraft = useComposerVoiceDraftWriter(sessionId, (update: ComposerVoiceDraftUpdate) => {applyRichComposerChange(reconcileComposerVoiceDraft(composerDocumentRef.current, update));});diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 8bbd11d6f0..9f9dd72d37 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -1,3 +1,4 @@+import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';import { useNewSessionHostDefaults } from '@/session/useNewSessionHostDefaults';import { ErrorNotice } from '@/components/ErrorNotice';import { useNewSessionDefaultSelection } from '@/session/useNewSessionDefaultSelection';@@ -121,9 +122,6 @@ import { goBackGuarded } from '@/utils/backGuard';import { buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttachment';import { useMobileLocalAttachments } from '@/session/useMobileLocalAttachments';import {- consumeIncomingShareBatch,- deleteIncomingSharedFiles,- selectIncomingShareUploadCandidates,useIncomingShareBatch,} from '@/session/incomingShare';import {@@ -973,53 +971,12 @@ export default function NewRemoteSessionScreen() {hasInput: hasRecoveryInput,onResume: next => router.setParams(next),});- useEffect(() => {- if (!isShareTargetFocused || !auth.isAuthenticated || !incomingShareBatch- || getMobileAuthOwner().accountId !== auth.user?.id) return;- try {- if (!consumeIncomingShareBatch(incomingShareBatch.id)) return;- } catch {- setAttachmentError(i18n.t('composer.upload.shareReceiveFailed'));- return;- }- const selection = selectIncomingShareUploadCandidates(incomingShareBatch.payloads);- const remainingSlots = Math.max(- 0,- MOBILE_MAX_ATTACHMENTS- - attachmentsRef.current.length- - getPendingUploadCount(),- );- const accepted = selection.candidates.slice(0, remainingSlots);- const dropped = selection.candidates.slice(remainingSlots);- const cleanupUris = [- ...selection.rejectedUris,- ...dropped.map((candidate) => candidate.uri),- ];- if (cleanupUris.length > 0) {- void deleteIncomingSharedFiles(cleanupUris).catch(() => undefined);- }- if (accepted.length > 0) {- enqueueUploads(accepted.map((candidate) => ({- ...candidate,- cleanupLocalUris: deleteIncomingSharedFiles,- })), { token: auth.getAccessToken() });- }- if (dropped.length > 0) {- setAttachmentError(i18n.t('composer.upload.maxAttachments', {- count: MOBILE_MAX_ATTACHMENTS,- }));- } else if (selection.rejectedUris.length > 0) {- setAttachmentError(i18n.t('composer.upload.noFileRead'));- } else {- setAttachmentError(null);- }- }, [- auth,- enqueueUploads,- getPendingUploadCount,- incomingShareBatch,- isShareTargetFocused,- ]);+ useIncomingShareComposer({+ destination: 'new', ready: isShareTargetFocused && newSessionPreferencesLoaded && !creating,+ appendText: text => setDraft(current => ({ ...current, firstMessage: [current.firstMessage, text].filter(Boolean).join('\n\n') })),+ attachmentCount: attachments.length,+ enqueueUploads, getPendingUploadCount, onError: setAttachmentError,+ });const pendingGoalSkillRef = useRef<string | null>(null);useEffect(() => {pendingGoalSkillRef.current = null;@@ -2045,6 +2002,9 @@ export default function NewRemoteSessionScreen() {autoDefaultDeviceRef.current = null;setRuntimeSettledDeviceId(null);}+ // A share can arrive before the first computer is selected. Its uploads+ // are not tied to a previous host; only a real host switch invalidates them.+ const changesExistingDevice = !!selectedDeviceIdRef.current && option.deviceId !== selectedDeviceIdRef.current;selectedDeviceIdRef.current = option.deviceId;setSelectedDeviceId(option.deviceId);setSelectedDeviceName(option.name || option.deviceId);@@ -2066,19 +2026,21 @@ export default function NewRemoteSessionScreen() {setBrowseLoading(false);setBrowseError(null);setContextSheetOpen(false);- // 切换电脑丢弃草稿附件前 best-effort 回收已上传的中转对象(codex review #504)。- for (const attachment of attachments) {- discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });+ if (changesExistingDevice) {+ // 切换电脑丢弃草稿附件前 best-effort 回收已上传的中转对象(codex review #504)。+ for (const attachment of attachments) {+ discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });+ }+ // 在途上传同样作废(codex review R10):不取消的话它们完成后会经 onUploaded 把+ // 上一台电脑期间选的附件塞进新电脑的草稿;丢弃后由控制器在完成时回收 OSS 对象。+ discardAllPendingUploads();+ releaseUploadedSources(attachments.map((attachment) => attachment.id));+ setAttachments([]);+ setMediaAssetAttachments({});+ setAttachmentPreviews({});+ composerAnnotationsRef.current?.forgetAllAttachments();+ setAttachmentError(null);}- // 在途上传同样作废(codex review R10):不取消的话它们完成后会经 onUploaded 把- // 上一台电脑期间选的附件塞进新电脑的草稿;丢弃后由控制器在完成时回收 OSS 对象。- discardAllPendingUploads();- releaseUploadedSources(attachments.map((attachment) => attachment.id));- setAttachments([]);- setMediaAssetAttachments({});- setAttachmentPreviews({});- composerAnnotationsRef.current?.forgetAllAttachments();- setAttachmentError(null);initialWorkspaceKeyRef.current = null;setDraft((current) => ({...current,diff --git a/apps/mobile/docs/incoming-sharing.md b/apps/mobile/docs/incoming-sharing.mdnew file mode 100644index 0000000000..dc397bdbed--- /dev/null+++ b/apps/mobile/docs/incoming-sharing.md@@ -0,0 +1,82 @@+# iOS incoming sharing++Cindy's iOS share extension accepts representations exported through `NSItemProvider`.+Sharing opens a destination picker: a new task, an existing active task, or a companion+with a writable conversation. Selection populates the ordinary composer, preserving its+existing draft. The user can add instructions, review uploads, and send normally.+Back cancels the unclaimed share and releases only its owned copies.+It never dispatches a message just because an external app opened Cindy.++## Supported representations++| Source representation | Result |+| --- | --- |+| Plain text, selected text | Composer text |+| Web URL / deep link | Composer text; never automatically fetched or executed |+| Safari preprocessing result | Page title, URL and selection when Safari supplies them |+| Image (including UIImage / raw data) | Attachment; HEIC/HEIF/TIFF/BMP follow the existing JPEG conversion path; vector/source encodings remain original files |+| Movie, audio | File attachment |+| PDF, Office, HTML/RTF, Markdown, JSON, archives | Original exported file |+| vCard, calendar, models, custom data types | Original exported file through the generic data adapter |+| File URL / security-scoped document | Owned copy, retaining its filename |+| Directory / document package | Coordinated upload snapshot (ZIP) |+| Mixed or multiple items | Text plus attachments, preserving source order within each |++Formats describe transfer support, not a promise that every agent can interpret every+format. The source app must export bytes, a file, text or a URL. Private in-app objects,+protected streams and content the source does not export cannot be recovered from a+share sheet. Live Photos export the representation offered by the source; this does+not claim preservation of their private paired-resource metadata.++One share accepts at most **20 provider items**. Oversized shares remain in the source+app with an explicit instruction to split them. The composer retains its existing+20-attachment limit; when its tray is full the incoming batch stays unclaimed until+space is available. An unreadable provider fails the entire incoming operation rather+than silently forwarding a partial set. Unsupported/offline destinations do not gain+new sending privileges: normal conversation hydration and authorization still apply.++## Implementation and extension points++- `plugins/incoming-share-formats.swift`: ordered representation adapters. File-backed+ media and exported documents take precedence over their text/link previews. Add a+ semantic adapter only when a new representation requires decoding; generic data+ formats need no extension allowlist.+- `plugins/with-incoming-share-formats.js`: generated Expo controller integration.+ Checked patch anchors fail prebuild if the upstream template changes.+- `plugins/with-incoming-share-files.js`: App Group file ownership, activation predicate,+ Safari script packaging and existing native-slot write/launch feedback. Expo Xcode+ mods run in reverse registration order; keep this plugin before `expo-sharing`.+- `src/session/incomingShare.ts`: account-fenced mailbox, explicit destination identity,+ text normalization and attachment conversion selection.+- `src/session/useIncomingShareComposer.ts`: shared handoff into new-task and existing+ task/companion composers. Upload, retries and send stay in the established pipeline.+- `app/incoming-share.tsx`: destination discovery; companion identities come from their+ advertised conversation links, not names or guessed sessions. Hosts without a+ conversation link remain visible but unavailable. Tasks use the existing active-list+ API (latest 500 per computer plus pinned tasks); archived/worker/bot sessions are not+ duplicated in the task section.++Provider temporary URLs are copied **inside** the `loadFileRepresentation` callback.+Security-scoped access is balanced; directories use `NSFileCoordinator.forUploading`.+Each input owns a unique App Group directory, so equal filenames cannot overwrite.+The native slot is acknowledged only by the selected, focused, hydrated composer;+account changes and upload cleanup use the existing ownership fences. The existing+native inbox is a single persistent slot, with an in-process JS queue; this change does+not promise a durable history of multiple shares received before Cindy opens.++## Verification++Run the focused mailbox/native/bridge/composer tests and mobile typecheck. Native changes+require rebuilding the iOS binary, checking that `incoming-share-webpage.js` is inside+`expo-sharing-extension.appex` (not only the main app), then exercising real system share+sheets. Cover Safari, text, image, mixed files, new/existing/companion destinations,+full composer, source read failure, 21-item rejection, and account switching. Native+launch-feedback tests execute the generated Swift methods rather than only matching+source strings. Simulator/source-specific coverage is not a claim that every third-party+app exposes the same providers.++## Apple references++- [Share extensions and Safari preprocessing](https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html)+- [NSItemProvider file representation lifetime](https://developer.apple.com/documentation/foundation/nsitemprovider/loadfilerepresentation(fortypeidentifier:completionhandler:))+- [Coordinated upload snapshots](https://developer.apple.com/documentation/foundation/nsfilecoordinator/readingoptions/foruploading)diff --git a/apps/mobile/plugins/incoming-share-feedback.swift b/apps/mobile/plugins/incoming-share-feedback.swiftindex bb9eeaaf76..5d92edae90 100644--- a/apps/mobile/plugins/incoming-share-feedback.swift+++ b/apps/mobile/plugins/incoming-share-feedback.swift@@ -12,9 +12,9 @@ private extension ShareIntoViewController {}}- func showShareFeedback(received: Bool) {+ func showShareFeedback(received: Bool, tooMany: Bool = false) {guard !shareClosed else { return }- let prefix = received ? "received" : "failed"+ let prefix = tooMany ? "tooMany" : received ? "received" : "failed"let alert = UIAlertController(title: shareString(prefix + "Title"),message: shareString(prefix + "Message"),diff --git a/apps/mobile/plugins/incoming-share-formats.swift b/apps/mobile/plugins/incoming-share-formats.swiftnew file mode 100644index 0000000000..be7be398b0--- /dev/null+++ b/apps/mobile/plugins/incoming-share-formats.swift@@ -0,0 +1,86 @@+ // Ordered semantic adapters. File-backed content wins over its text/URL preview.+ // Unknown exportable types use their original bytes; new formats normally need+ // no special handler. Add an adapter only when its representation needs decoding.+ private func parseProvider(_ provider: NSItemProvider) async -> SharePayload? {+ if provider.hasItemConformingToTypeIdentifier(UTType.propertyList.identifier),+ let value = await loadShareItem(provider, identifier: UTType.propertyList.identifier) as? [String: Any],+ let page = value[NSExtensionJavaScriptPreprocessingResultsKey] as? [String: Any],+ let url = page["url"] as? String {+ let text = [page["title"] as? String, url, page["selection"] as? String]+ .compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: "\n\n")+ return SharePayload(type: .text, value: text, mimeType: "text/plain", metadata: nil)+ }+ if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {+ if let value = await loadShareItem(provider, identifier: UTType.fileURL.identifier) as? URL,+ let file = copyAndProcessFile(url: value, type:+ (provider.hasItemConformingToTypeIdentifier(UTType.image.identifier)+ || UTType(filenameExtension: value.pathExtension)?.conforms(to: .image) == true) ? .image : .file) { return file }+ }+ let formats: [(UTType, ShareType)] = [(.image, .image), (.movie, .video), (.audio, .audio), (.directory, .file)]+ for (format, kind) in formats where provider.hasItemConformingToTypeIdentifier(format.identifier) {+ if let file = await loadShareFile(provider, format: format, kind: kind) { return file }+ }+ // Prefer an exported document to its plain-text/link preview.+ if let file = await loadShareFile(provider, format: .data, kind: .file, excludePlainText: true) { return file }+ if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier),+ let value = await loadShareItem(provider, identifier: UTType.url.identifier) {+ let url = (value as? URL) ?? (value as? String).flatMap(URL.init(string:))+ if let url, !url.isFileURL {+ return SharePayload(type: .url, value: url.absoluteString, mimeType: "text/uri-list", metadata: nil)+ }+ }+ if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier),+ let value = await loadShareItem(provider, identifier: UTType.plainText.identifier) {+ let text = (value as? String) ?? (value as? NSAttributedString)?.string+ ?? (value as? Data).flatMap { String(data: $0, encoding: .utf8) }+ if let text, !text.isEmpty {+ return SharePayload(type: .text, value: text, mimeType: "text/plain", metadata: nil)+ }+ }+ // PDF, Office, archives, vCard, calendar, HTML/RTF, models and custom exports.+ return await loadShareFile(provider, format: .data, kind: .file)+ }++ private func loadShareItem(_ provider: NSItemProvider, identifier: String) async -> NSSecureCoding? {+ await withCheckedContinuation { continuation in+ provider.loadItem(forTypeIdentifier: identifier, options: nil) { value, _ in+ continuation.resume(returning: value)+ }+ }+ }++ private func loadShareFile(_ provider: NSItemProvider, format: UTType, kind: ShareType, excludePlainText: Bool = false) async -> SharePayload? {+ let identifiers = provider.registeredTypeIdentifiers.filter {+ let type = UTType($0)+ return type?.conforms(to: format) == true && type?.conforms(to: .url) != true+ && (!excludePlainText || (type?.conforms(to: .plainText) != true && type?.conforms(to: .propertyList) != true))+ }+ for identifier in identifiers {+ // Copy inside the callback: provider-owned URLs expire when it returns.+ var file: SharePayload?+ // UIKit can serialize the abstract public.image representation as an+ // NSKeyedArchive, not image bytes. Decode its UIImage via loadItem below.+ if identifier != UTType.image.identifier {+ file = await withCheckedContinuation { continuation in+ provider.loadFileRepresentation(forTypeIdentifier: identifier) { url, _ in+ continuation.resume(returning: url.flatMap { self.copyAndProcessFile(url: $0, type: kind) })+ }+ }+ }+ if let file { return file }+ guard let value = await loadShareItem(provider, identifier: identifier) else { continue }+ if let url = value as? URL, let file = copyAndProcessFile(url: url, type: kind) { return file }+ let data = (value as? Data) ?? (value as? UIImage)?.pngData()+ if let data {+ let isRenderedImage = value is UIImage+ let type = isRenderedImage ? UTType.png : UTType(identifier)+ let ext = type?.preferredFilenameExtension ?? "bin"+ let suggested = provider.suggestedName.map { URL(fileURLWithPath: $0).lastPathComponent } ?? UUID().uuidString+ let name = suggested.isEmpty || suggested == "." || suggested == ".." ? UUID().uuidString : suggested+ let filename = isRenderedImage ? (name as NSString).deletingPathExtension + ".png"+ : (name as NSString).pathExtension.isEmpty ? name + "." + ext : name+ if let file = saveDataToAppGroup(data: data, fileName: filename, type: kind, mimeType: type?.preferredMIMEType) { return file }+ }+ }+ return nil+ }diff --git a/apps/mobile/plugins/incoming-share-strings.json b/apps/mobile/plugins/incoming-share-strings.jsonindex 6e0508a517..aa0c0e9983 100644--- a/apps/mobile/plugins/incoming-share-strings.json+++ b/apps/mobile/plugins/incoming-share-strings.json@@ -1,37 +1,47 @@{"en": {- "receivedTitle": "Files received",+ "receivedTitle": "Content received","receivedMessage": "Open Cindy manually to continue.",- "failedTitle": "Couldn’t receive files",- "failedMessage": "Share the files again.",- "done": "Close Share"+ "failedTitle": "Couldn’t receive this share",+ "failedMessage": "Try sharing again from the original app.",+ "done": "Close Share",+ "tooManyTitle": "Too many items",+ "tooManyMessage": "Share up to 20 items at a time. Return to the source app and select fewer items."},"zh-Hans": {- "receivedTitle": "文件已接收",+ "receivedTitle": "内容已接收","receivedMessage": "请手动打开 Cindy 继续。",- "failedTitle": "未能接收文件",- "failedMessage": "请重新分享文件。",- "done": "关闭分享"+ "failedTitle": "未能接收分享",+ "failedMessage": "请从原应用重新分享。",+ "done": "关闭分享",+ "tooManyTitle": "分享内容过多",+ "tooManyMessage": "一次最多接收 20 项内容。请返回来源 App,分批选择后分享。"},"zh-Hant": {- "receivedTitle": "已接收檔案",+ "receivedTitle": "內容已接收","receivedMessage": "請手動開啟 Cindy 繼續。",- "failedTitle": "無法接收檔案",- "failedMessage": "請重新分享檔案。",- "done": "關閉分享"+ "failedTitle": "無法接收分享",+ "failedMessage": "請從原應用程式重新分享。",+ "done": "關閉分享",+ "tooManyTitle": "分享內容過多",+ "tooManyMessage": "一次最多接收 20 項內容。請返回來源 App,分批選取後分享。"},"ja": {- "receivedTitle": "ファイルを受け取りました",+ "receivedTitle": "共有内容を受け取りました","receivedMessage": "Cindy を手動で開いて続けてください。",- "failedTitle": "ファイルを受け取れませんでした",- "failedMessage": "もう一度ファイルを共有してください。",- "done": "共有を閉じる"+ "failedTitle": "共有内容を受け取れませんでした",+ "failedMessage": "元のアプリからもう一度共有してください。",+ "done": "共有を閉じる",+ "tooManyTitle": "共有項目が多すぎます",+ "tooManyMessage": "一度に共有できるのは20項目までです。元のアプリに戻り、分けて共有してください。"},"ko": {- "receivedTitle": "파일을 받았어요",+ "receivedTitle": "공유 내용을 받았어요","receivedMessage": "Cindy를 직접 열어 계속해 주세요.",- "failedTitle": "파일을 받지 못했어요",- "failedMessage": "파일을 다시 공유해 주세요.",- "done": "공유 닫기"+ "failedTitle": "공유 내용을 받지 못했어요",+ "failedMessage": "원래 앱에서 다시 공유해 주세요.",+ "done": "공유 닫기",+ "tooManyTitle": "공유 항목이 너무 많습니다",+ "tooManyMessage": "한 번에 최대 20개 항목을 공유할 수 있습니다. 원래 앱으로 돌아가 나누어 공유하세요."}}diff --git a/apps/mobile/plugins/incoming-share-webpage.js b/apps/mobile/plugins/incoming-share-webpage.jsnew file mode 100644index 0000000000..d20764eff8--- /dev/null+++ b/apps/mobile/plugins/incoming-share-webpage.js@@ -0,0 +1,11 @@+// Safari invokes this only after the user selects Cindy in the share sheet.+// Keep the page untouched. Include the selected passage, never form fields.+var ExtensionPreprocessingJS = {+ run: function (args) {+ args.completionFunction({+ title: document.title || '',+ url: document.location.href,+ selection: String(window.getSelection() || ''),+ });+ },+};diff --git a/apps/mobile/plugins/with-incoming-share-files.js b/apps/mobile/plugins/with-incoming-share-files.jsindex d39c74ed16..8a039e84c0 100644--- a/apps/mobile/plugins/with-incoming-share-files.js+++ b/apps/mobile/plugins/with-incoming-share-files.js@@ -1,6 +1,7 @@const fs = require("node:fs");const path = require("node:path");const { withXcodeProject } = require("@expo/config-plugins");+const { patchIncomingShareFormats } = require("./with-incoming-share-formats");const { patchShareFeedback } = require("./with-incoming-share-feedback");// expo-sharing 57 copies files to AppGroup/<basename>, overwriting same-name@@ -60,6 +61,7 @@ function patchShareExtension(source) {' print("Error: Expo-sharing has failed to serialize shared data to JSON")\n return false',1,);+ source = patchIncomingShareFormats(source);return (patchShareFeedback(source) +"\n" +@@ -82,6 +84,39 @@ module.exports = (config) =>"ShareIntoViewController.swift",);fs.writeFileSync(file, patchShareExtension(fs.readFileSync(file, "utf8")));+ const plist = require('@expo/plist').default;+ const folder = path.dirname(file);+ const infoPath = path.join(folder, 'Info.plist');+ const info = plist.parse(fs.readFileSync(infoPath, 'utf8'));+ const attributes = info.NSExtension.NSExtensionAttributes;+ // Match exportable representations, including mixed shares and custom data.+ // No TRUEPREDICATE: unsupported provider-only objects do not advertise Cindy.+ attributes.NSExtensionActivationRule = 'SUBQUERY(extensionItems, $item, SUBQUERY($item.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.data" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.url" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.text" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.directory" OR ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "com.apple.property-list").@count == $item.attachments.@count).@count == extensionItems.@count';+ attributes.NSExtensionJavaScriptPreprocessingFile = 'incoming-share-webpage';+ fs.writeFileSync(infoPath, plist.build(info));+ const jsName = 'incoming-share-webpage.js';+ fs.copyFileSync(path.join(__dirname, jsName), path.join(folder, jsName));+ const project = mod.modResults;+ const targets = project.pbxNativeTargetSection();+ const target = Object.keys(targets).find(key => !key.endsWith('_comment') && String(targets[key].name).replaceAll('"', '') === 'expo-sharing-extension');+ if (!target) throw new Error('expo-sharing extension target missing');+ const resourcePath = 'expo-sharing-extension/' + jsName;+ const added = project.addResourceFile(resourcePath, { target });+ // Expo-created phases can lack the comments xcode's target lookup needs.+ // Resolve by ISA instead, including an existing reference on repeated prebuilds.+ const references = project.pbxFileReferenceSection();+ const reference = added?.fileRef ?? Object.keys(references).find(key =>+ !key.endsWith('_comment') && String(references[key].path).replaceAll('"', '') === resourcePath);+ const builds = project.pbxBuildFileSection();+ const build = added?.uuid ?? Object.keys(builds).find(key =>+ !key.endsWith('_comment') && builds[key].fileRef === reference);+ const phases = project.hash.project.objects.PBXResourcesBuildPhase;+ const phase = targets[target].buildPhases.map(item => phases[item.value]).find(Boolean);+ if (!build || !phase) throw new Error('expo-sharing resource phase missing');+ for (const [key, value] of Object.entries(phases)) {+ if (!key.endsWith('_comment')) value.files = value.files.filter(item => item.value !== build);+ }+ phase.files.push({ value: build, comment: jsName + ' in Resources' });return mod;});module.exports.patchShareExtension = patchShareExtension;diff --git a/apps/mobile/plugins/with-incoming-share-formats.js b/apps/mobile/plugins/with-incoming-share-formats.jsnew file mode 100644index 0000000000..323af43c2c--- /dev/null+++ b/apps/mobile/plugins/with-incoming-share-formats.js@@ -0,0 +1,54 @@+const fs = require('node:fs');+const path = require('node:path');++// Keep Expo's app-group/launch contract; format policy lives in one Swift unit.+function patchIncomingShareFormats(source) {+ const replace = (from, to) => {+ if (source.split(from).length !== 2) throw new Error('expo-sharing input contract changed');+ return source.replace(from, to);+ };+ const start = source.indexOf(' private func parseProvider(');+ const end = source.indexOf(' // MARK: - File Management', start);+ if (start < 0 || end < 0) throw new Error('expo-sharing provider contract changed');+ source = source.slice(0, start) + fs.readFileSync(path.join(__dirname, 'incoming-share-formats.swift'), 'utf8') + '\n' + source.slice(end);+ source = replace(' Task {', ` guard items.reduce(0, { $0 + ($1.attachments?.count ?? 0) }) <= 20 else {+ showShareFeedback(received: false, tooMany: true)+ return+ }+ Task {`);+ source = replace(' guard let attachments = item.attachments else { continue }', ` let attachments = item.attachments ?? []+ let firstResult = results.count`);+ source = replace(' }\n\n return results', ` if let text = item.attributedContentText?.string, !text.isEmpty,+ !results.dropFirst(firstResult).contains(where: { $0.value == text || $0.value.components(separatedBy: "\\n").contains(text) }) {+ results.append(SharePayload(type: .text, value: text, mimeType: "text/plain", metadata: nil))+ }+ }++ return results`);+ source = replace(' results.append(payload)\n }', ` results.append(payload)+ } else {+ // Do not silently deliver a subset. The source app still owns the inputs.+ for payload in results where payload.type != .text && payload.type != .url && payload.value.hasPrefix("file://") {+ if let url = URL(string: payload.value), url.deletingLastPathComponent().lastPathComponent.hasPrefix("cindy-share-") {+ try? FileManager.default.removeItem(at: url.deletingLastPathComponent())+ }+ }+ return []+ }`);+ source = replace(' let fileName = url.lastPathComponent.isEmpty', ` guard url.isFileURL else { return nil }+ let access = url.startAccessingSecurityScopedResource()+ defer { if access { url.stopAccessingSecurityScopedResource() } }+ let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey])+ if values?.isDirectory == true {+ var result: SharePayload?+ var error: NSError?+ NSFileCoordinator().coordinate(readingItemAt: url, options: .forUploading, error: &error) { archive in+ result = self.copyAndProcessFile(url: archive, type: .file)+ }+ return error == nil ? result : nil+ }+ guard values?.isRegularFile == true else { return nil }+ let fileName = url.lastPathComponent.isEmpty`);+ return source;+}+module.exports = { patchIncomingShareFormats };diff --git a/apps/mobile/scripts/test-incoming-share-feedback.mjs b/apps/mobile/scripts/test-incoming-share-feedback.mjsindex 1c824cb0d2..45f36fee86 100644--- a/apps/mobile/scripts/test-incoming-share-feedback.mjs+++ b/apps/mobile/scripts/test-incoming-share-feedback.mjs@@ -60,6 +60,20 @@ function method(signature) {const harness = `import Foundation+enum ShareType: String { case text, url, image, audio, video, file }+struct SharePayload { let type: ShareType; let value: String; let mimeType: String; let metadata: String? }+class NSItemProvider {+ let payload: SharePayload?+ init(_ payload: SharePayload?) { self.payload = payload }+}+class NSExtensionItem {+ var attachments: [NSItemProvider]?+ var attributedContentText: NSAttributedString?+ init(_ providers: [NSItemProvider], _ text: String? = nil) {+ attachments = providers+ attributedContentText = text.map { NSAttributedString(string: $0) }+ }+}class UIResponder { var next: UIResponder? }class UIApplication: UIResponder {var calls = 0@@ -103,6 +117,8 @@ class ShareIntoViewController: UIResponder {var alerts: [UIAlertController] = []func present(_ alert: UIAlertController, animated: Bool) { alerts.append(alert) }func shareString(_ key: String) -> String { key }+ func parseProvider(_ provider: NSItemProvider) async -> SharePayload? { provider.payload }+ ${method("nonisolated private func processInputItems").replace("private func", "func")}${method("func openParentApp()")}${method("private func openURL(")}${method("private func close()")}@@ -160,6 +176,37 @@ do {let action = controller.alerts[0].actions[0]; action.handler(action)check(controller.extensionContext!.completions == 1)}+do {+ let controller = ShareIntoViewController(); controller.showShareFeedback(received: false, tooMany: true)+ check(controller.alerts[0].title == "tooManyTitle")+ check(controller.extensionContext!.completions == 0)+}+// Execute the actual generated item assembly and partial-failure cleanup.+let finished = DispatchSemaphore(value: 0)+Task.detached {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: root); finished.signal() }+ let owned = root.appendingPathComponent("cindy-share-" + UUID().uuidString).appendingPathComponent("owned.txt")+ let referenced = root.appendingPathComponent("cindy-share-" + UUID().uuidString).appendingPathComponent("keep.txt")+ for url in [owned, referenced] {+ try! FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try! Data("fixture".utf8).write(to: url)+ }+ let controller = ShareIntoViewController()+ let file = SharePayload(type: .file, value: owned.absoluteString, mimeType: "text/plain", metadata: nil)+ let text = SharePayload(type: .text, value: referenced.absoluteString, mimeType: "text/plain", metadata: nil)+ let failed = await controller.processInputItems([NSExtensionItem([NSItemProvider(file), NSItemProvider(text), NSItemProvider(nil)])])+ check(failed.isEmpty)+ check(!FileManager.default.fileExists(atPath: owned.path))+ check(FileManager.default.fileExists(atPath: referenced.path))+ let captioned = await controller.processInputItems([NSExtensionItem([NSItemProvider(file)], "caption")])+ check(captioned.count == 2 && captioned.last?.value == "caption")+ let duplicate = await controller.processInputItems([NSExtensionItem([NSItemProvider(text)], text.value)])+ check(duplicate.count == 1)+ let standalone = await controller.processInputItems([NSExtensionItem([], "selection")])+ check(standalone.count == 1 && standalone[0].value == "selection")+}+check(finished.wait(timeout: .now() + 5) == .success)print("PASS: generated Swift share feedback (success, failure, timeout, missing responder, duplicate/late reply, cancel, Done)")`;const dir = mkdtempSync(join(tmpdir(), "cindy-share-feedback-test-"));diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.tsindex 078a5a47b8..fc7a273277 100644--- a/apps/mobile/src/__tests__/incomingShare.test.ts+++ b/apps/mobile/src/__tests__/incomingShare.test.ts@@ -5,6 +5,7 @@ import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch, isMobileAuthOwnimport {__resetIncomingShareForTest,consumeIncomingShareBatch,+ discardIncomingShareBatch,incomingShareBatchId,selectIncomingShareUploadCandidates,stageIncomingShareBatch,@@ -59,6 +60,20 @@ describe('incoming Share Extension payloads', () => {convertToJpeg.mockClear();});+ it('never interprets file-URL text as an upload or cleanup capability', async () => {+ const text = payload({ shareType: 'text', value: 'file:///private/document.txt', contentUri: 'file:///private/document.txt', contentType: 'text' });+ expect(selectIncomingShareUploadCandidates([text]).candidates).toEqual([]);+ const batch = stageIncomingShareBatch([text], vi.fn())!;+ expect(discardIncomingShareBatch(batch.id)).toBe(true);+ const clearSharedPayloads = vi.fn();+ const stop = watchIncomingShareAccount({ getSharedPayloads: () => [text], clearSharedPayloads });+ stageIncomingShareBatch([text], vi.fn());+ setMobileAuthOwner('account-b');+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(deleteAsync).not.toHaveBeenCalled();+ stop();+ });+it('converts non-sendable iOS image formats before entering the attachment uploader', async () => {const result = selectIncomingShareUploadCandidates([payload({@@ -88,6 +103,14 @@ describe('incoming Share Extension payloads', () => {expect(convertToJpeg).toHaveBeenCalledWith('file:///shared/IMG_0001.HEIC');});+ it.each(['svg', 'psd', 'dng'])('preserves %s image exports as files instead of forcing a JPEG decoder', (extension) => {+ const input = payload({ shareType: 'image', contentType: 'image', originalName: `drawing.${extension}` });+ const result = selectIncomingShareUploadCandidates([input]);+ expect(result.candidates).toEqual([expect.objectContaining({ kind: 'file', name: `drawing.${extension}` })]);+ expect(result.candidates[0]!.resolve).toBeUndefined();+ expect(convertToJpeg).not.toHaveBeenCalled();+ });+it('converts supported files and images into the existing attachment upload candidates', () => {const result = selectIncomingShareUploadCandidates([payload({}),diff --git a/apps/mobile/src/__tests__/incomingShareBridge.test.ts b/apps/mobile/src/__tests__/incomingShareBridge.test.tsindex 048ddb326e..b4198f10f3 100644--- a/apps/mobile/src/__tests__/incomingShareBridge.test.ts+++ b/apps/mobile/src/__tests__/incomingShareBridge.test.ts@@ -49,8 +49,8 @@ function navigatePendingShare() {it('lets users leave a failed handoff and navigates again for a fresh share', () => {mock.batch = { id: 'first' };navigatePendingShare();- expect(mock.navigate).toHaveBeenCalledExactlyOnceWith('/sessions/new');- mock.segments = ['sessions', 'new'];+ expect(mock.navigate).toHaveBeenCalledExactlyOnceWith('/incoming-share');+ mock.segments = ['incoming-share'];navigatePendingShare();mock.segments = [];navigatePendingShare();@@ -63,12 +63,12 @@ it('lets users leave a failed handoff and navigates again for a fresh share', ()it('does not mark a batch presented until authentication is ready', () => {mock.batch = { id: 'pending-login' };mock.auth.initialized = false;- mock.segments = ['sessions', 'new'];+ mock.segments = ['incoming-share'];navigatePendingShare();mock.segments = [];mock.auth.initialized = true;navigatePendingShare();- expect(mock.navigate).toHaveBeenCalledExactlyOnceWith('/sessions/new');+ expect(mock.navigate).toHaveBeenCalledExactlyOnceWith('/incoming-share');});it('finishes expiry before reading the native slot', async () => {diff --git a/apps/mobile/src/__tests__/incomingShareNative.test.ts b/apps/mobile/src/__tests__/incomingShareNative.test.tsindex a031ee4231..8e6c85e585 100644--- a/apps/mobile/src/__tests__/incomingShareNative.test.ts+++ b/apps/mobile/src/__tests__/incomingShareNative.test.ts@@ -156,3 +156,11 @@ it.each(['throw', 'false'])('preserves all mixed payloads after acknowledgementslot = snapshot;expect(restarted.getSharedPayloads()).toHaveLength(1);});++// A shared string that looks like a managed path is still content, not a file capability.+it('preserves literal file-URL text without consulting or deleting the filesystem', () => {+ fs.listings.set(root, []);+ native.readSnapshot.mockReturnValue(JSON.stringify([{ type: 'text', value: uri }]));+ expect(getSharedPayloads()).toEqual([{ shareType: 'text', value: uri, mimeType: undefined }]);+ expect(native.clearSnapshot).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.tsindex dc12755b30..539bb09873 100644--- a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts+++ b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts@@ -122,6 +122,8 @@ describe("incoming share native file ownership", () => {"failedTitle","receivedMessage","receivedTitle",+ "tooManyMessage",+ "tooManyTitle",]);expect(Object.values(values).every((value) => value.trim().length > 0),diff --git a/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts b/apps/mobile/src/__tests__/newSessionIncomingShare.test.tsnew file mode 100644index 0000000000..eb45002928--- /dev/null+++ b/apps/mobile/src/__tests__/newSessionIncomingShare.test.ts@@ -0,0 +1,52 @@+// Execute the real page callback: shares can upload before a computer is chosen.+// First/same-host selection must preserve them; a real host switch still discards.+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { expect, it, vi } from 'vitest';++const page = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),+ ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let callback: ts.ArrowFunction | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(page) === 'selectDevice'+ && node.initializer && ts.isCallExpression(node.initializer)) {+ const first = node.initializer.arguments[0];+ if (first && ts.isArrowFunction(first)) callback = first;+ }+ ts.forEachChild(node, visit);+}+visit(page);+if (!callback) throw new Error('Missing actual new-task device selection callback');+const setterNames = [...new Set(callback.getText(page).match(/\bset[A-Z]\w*/g) ?? [])];+const compiled = ts.transpileModule(`const selectDevice = ${callback.getText(page)};`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None, alwaysStrict: false },+}).outputText;+function run(bindings: Record<string, unknown>) {+ const select = new Function(...Object.keys(bindings), `${compiled}; return selectDevice;`)(...Object.values(bindings));+ select({ deviceId: 'new-host', name: 'Fixture' });+}++it.each([['', false], ['new-host', false], ['old-host', true]] as const)(+ 'preserves initial shares with previous host %s (discard=%s)', (previous, discard) => {+ const bindings: Record<string, unknown> = {+ creating: false, voiceIsProcessing: false, voiceState: 'idle',+ attachments: [{ id: 'shared-attachment' }], auth: { getAccessToken: vi.fn() },+ selectedDeviceIdRef: { current: previous }, browseSeqRef: { current: 0 },+ composerAnnotationsRef: { current: { forgetAllAttachments: vi.fn() } },+ };+ for (const name of ['voicePermissionRequestInFlightRef', 'voiceStopInFlightRef', 'voiceStartupInFlightRef',+ 'voiceRecordingActiveRef', 'userTouchedDeviceRef', 'userTouchedRuntimeRef']) bindings[name] = { current: false };+ for (const name of ['explicitProviderModelSelectionRef', 'autoDefaultDeviceRef', 'initialWorkspaceKeyRef']) bindings[name] = { current: null };+ for (const name of ['cancelVoiceForDeviceSwitch', 'saveNewSessionPreferences', 'discardMobileUploadedAttachment',+ 'discardAllPendingUploads', 'releaseUploadedSources']) bindings[name] = vi.fn();+ for (const name of setterNames) bindings[name] = vi.fn();+ run(bindings);+ expect(bindings.discardMobileUploadedAttachment).toHaveBeenCalledTimes(discard ? 1 : 0);+ expect(bindings.discardAllPendingUploads).toHaveBeenCalledTimes(discard ? 1 : 0);+ expect(bindings.releaseUploadedSources).toHaveBeenCalledTimes(discard ? 1 : 0);+ expect(bindings.selectedDeviceIdRef).toEqual({ current: 'new-host' });+ if (discard) expect(bindings.setAttachments).toHaveBeenCalledWith([]);+ else expect(bindings.setAttachments).not.toHaveBeenCalled();+ },+);diff --git a/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx b/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsxnew file mode 100644index 0000000000..c223d6326b--- /dev/null+++ b/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx@@ -0,0 +1,89 @@+// @vitest-environment jsdom+// Unit: a shared URL used to disappear, and existing tasks had no receiving path.+// Exercise the real mailbox/hook: wrong destination, draft hydration, full tray,+// persistence failure and account changes must not consume or redirect content.+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { beforeEach, afterEach, expect, it, vi } from 'vitest';+import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';+import { __resetIncomingShareForTest, discardIncomingShareBatch, receiveIncomingShare, stageIncomingShareBatch, selectIncomingShareDestination, incomingShareBatchId } from '@/session/incomingShare';+import { setMobileAuthOwner, __testing as ownerTesting } from '@/auth/authOwnerGeneration';+import type { ResolvedSharePayload } from 'expo-sharing';+const h = vi.hoisted(() => ({ focused: true, auth: { isAuthenticated: true, user: { id: 'a' }, getAccessToken: async () => 'token' } }));+vi.mock('expo-router', () => ({ useIsFocused: () => h.focused }));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));+vi.mock('react-i18next', async importOriginal => ({ ...await importOriginal<typeof import('react-i18next')>(), useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/session/pastedImageAttachment', () => ({ resolvePastedImageAsset: vi.fn() }));+vi.mock('expo-file-system/legacy', () => ({ deleteAsync: vi.fn() }));+let root: Root;+const appendText = vi.fn(), enqueueUploads = vi.fn(), onError = vi.fn();+const link: ResolvedSharePayload = { value: 'https://example.com', shareType: 'url', contentUri: 'https://example.com', contentType: 'website', contentMimeType: 'text/uri-list', originalName: 'example.com', contentSize: null };+const file: ResolvedSharePayload = { value: 'file:///share/report.pdf', shareType: 'file', contentUri: 'file:///share/report.pdf', contentType: 'file', contentMimeType: 'application/pdf', originalName: 'report.pdf', contentSize: 20 };+function Composer({ destination = 'chosen', ready = true, count = 0 }) {+ useIncomingShareComposer({ destination, ready, attachmentCount: count, appendText, enqueueUploads, onError, getPendingUploadCount: () => 0 });+ return null;+}+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ ownerTesting.reset(); setMobileAuthOwner('a'); __resetIncomingShareForTest();+ h.focused = true; vi.clearAllMocks(); root = createRoot(document.createElement('div'));+});+afterEach(() => { act(() => root.unmount()); __resetIncomingShareForTest(); });+function share(ack = vi.fn()) {+ const batch = stageIncomingShareBatch([link, file], ack)!;+ selectIncomingShareDestination(batch.id, 'chosen');+ return ack;+}+it('waits for the chosen focused composer to hydrate, then appends text and uploads once', () => {+ const ack = share();+ act(() => root.render(<Composer destination="other" />));+ act(() => root.render(<Composer ready={false} />));+ expect(ack).not.toHaveBeenCalled();+ act(() => root.render(<Composer />));+ expect(appendText).toHaveBeenCalledExactlyOnceWith(link.value);+ expect(enqueueUploads).toHaveBeenCalledWith([expect.objectContaining({ name: 'report.pdf', uri: file.value, cleanupLocalUris: expect.any(Function) })], expect.anything());+ act(() => root.render(<Composer />));+ expect(ack).toHaveBeenCalledOnce();+});+it('keeps every file pending when the destination tray is full', () => {+ const ack = share();+ act(() => root.render(<Composer count={20} />));+ expect(ack).not.toHaveBeenCalled(); expect(appendText).not.toHaveBeenCalled();+ expect(onError).toHaveBeenCalledWith('composer.upload.maxAttachments');+ act(() => root.render(<Composer count={19} />));+ expect(ack).toHaveBeenCalledOnce(); expect(enqueueUploads).toHaveBeenCalledOnce();+});+it('does not expose unacknowledged content, and retries when the composer refocuses', () => {+ const ack = share(vi.fn().mockImplementationOnce(() => { throw new Error('disk'); }));+ act(() => root.render(<Composer />));+ expect(appendText).not.toHaveBeenCalled();+ expect(onError).toHaveBeenCalledWith('composer.upload.shareReceiveFailed');+ h.focused = false; act(() => root.render(<Composer />));+ h.focused = true; act(() => root.render(<Composer />));+ expect(appendText).toHaveBeenCalledOnce(); expect(ack).toHaveBeenCalledTimes(2);+});+it('never hands a previous account share to the current composer', () => {+ share(); setMobileAuthOwner('b');+ act(() => root.render(<Composer />));+ expect(appendText).not.toHaveBeenCalled(); expect(enqueueUploads).not.toHaveBeenCalled();+});+it('receives a native text-only share as text instead of a fictitious file', () => {+ const ack = vi.fn();+ receiveIncomingShare({ getSharedPayloads: () => [{ shareType: 'text', value: 'A passage' }], clearSharedPayloads: ack });+ const expected: ResolvedSharePayload = { value: 'A passage', shareType: 'text', contentUri: null, contentType: 'text', contentMimeType: null, originalName: 'A passage', contentSize: null };+ expect(selectIncomingShareDestination(incomingShareBatchId([expected]), 'chosen')).toBe(true);+ act(() => root.render(<Composer />));+ expect(appendText).toHaveBeenCalledExactlyOnceWith('A passage');+ expect(enqueueUploads).not.toHaveBeenCalled(); expect(ack).toHaveBeenCalledOnce();+});++it('cancels an unclaimed share so sharing the same text again can open a fresh chooser', () => {+ const ack = share();+ expect(discardIncomingShareBatch(incomingShareBatchId([link, file]))).toBe(true);+ act(() => root.render(<Composer />));+ expect(ack).toHaveBeenCalledOnce(); expect(appendText).not.toHaveBeenCalled();+ let nextAck!: ReturnType<typeof share>;+ act(() => { nextAck = share(); });+ act(() => root.render(<Composer />));+ expect(nextAck).toHaveBeenCalledOnce(); expect(appendText).toHaveBeenCalledOnce();+});diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.jsonindex 356c050f9d..e09c668fcb 100644--- a/apps/mobile/src/i18n/locales/en/composer.json+++ b/apps/mobile/src/i18n/locales/en/composer.json@@ -103,5 +103,20 @@"transcriptKept": "{{message}} The text recognized so far was kept — you can edit it directly.","micPermission": "Microphone access is turned off. Allow {{appName}} to use the microphone in system settings.","realtimeAudioUnavailable": "This build does not support realtime voice input. Install a test build that includes the native recording module."+ },+ "incomingShare": {+ "title": "Send to Cindy",+ "empty": "No pending shared content",+ "file": "File",+ "fileCount": "{{count}} files",+ "hint": "Choose a destination, then add instructions and send.",+ "search": "Search tasks and companions",+ "newTask": "New task",+ "companions": "Companions",+ "tasks": "Tasks",+ "unavailable": "Cannot receive shares yet",+ "noCompanions": "No companions yet",+ "noTasks": "No tasks yet",+ "retry": "Could not load everything. Tap to retry."}}diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.jsonindex de7d2cb831..39332e8107 100644--- a/apps/mobile/src/i18n/locales/ja/composer.json+++ b/apps/mobile/src/i18n/locales/ja/composer.json@@ -103,5 +103,20 @@"transcriptKept": "{{message}}(ここまで認識したテキストは保持しており、そのまま編集できます)","micPermission": "マイクの権限が許可されていません。システム設定で {{appName}} にマイクの使用を許可してください。","realtimeAudioUnavailable": "現在のビルドはリアルタイム音声入力に対応していません。ネイティブ録音モジュールを含むテストビルドをインストールしてください。"+ },+ "incomingShare": {+ "title": "Cindy に送る",+ "empty": "受け取り待ちの共有はありません",+ "file": "ファイル",+ "fileCount": "ファイル {{count}} 件",+ "hint": "送信先を選び、指示を追加して送信できます。",+ "search": "タスクとパートナーを検索",+ "newTask": "新しいタスク",+ "companions": "パートナー",+ "tasks": "既存のタスク",+ "unavailable": "現在共有を受信できません",+ "noCompanions": "パートナーはまだありません",+ "noTasks": "タスクはまだありません",+ "retry": "一部を読み込めませんでした。タップして再試行。"}}diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.jsonindex e4c2ea179f..7e3dad9d4c 100644--- a/apps/mobile/src/i18n/locales/ko/composer.json+++ b/apps/mobile/src/i18n/locales/ko/composer.json@@ -103,5 +103,20 @@"transcriptKept": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 바로 이어서 편집할 수 있습니다.","micPermission": "마이크 권한이 꺼져 있습니다. 시스템 설정에서 {{appName}}의 마이크 사용을 허용해 주세요.","realtimeAudioUnavailable": "현재 설치 패키지는 실시간 음성 입력을 지원하지 않습니다. 네이티브 녹음 모듈이 포함된 테스트 빌드를 설치해 주세요."+ },+ "incomingShare": {+ "title": "Cindy로 보내기",+ "empty": "받을 공유 내용이 없습니다",+ "file": "파일",+ "fileCount": "파일 {{count}}개",+ "hint": "대상을 선택한 후 지시를 추가하고 보내세요.",+ "search": "작업 및 파트너 검색",+ "newTask": "새 작업",+ "companions": "파트너",+ "tasks": "기존 작업",+ "unavailable": "현재 공유를 받을 수 없습니다",+ "noCompanions": "아직 파트너가 없습니다",+ "noTasks": "아직 작업이 없습니다",+ "retry": "일부 내용을 불러오지 못했습니다. 눌러서 다시 시도하세요."}}diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.jsonindex 387e20535a..57de6fcce5 100644--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json@@ -103,5 +103,20 @@"transcriptKept": "{{message}}(识别出的文字已经保留,可以直接编辑)","micPermission": "麦克风权限未开启,请在系统设置里允许 {{appName}} 使用麦克风。","realtimeAudioUnavailable": "当前安装包不支持实时语音输入,请安装包含原生录音模块的测试版。"+ },+ "incomingShare": {+ "title": "发送到 Cindy",+ "empty": "没有待接收的分享",+ "file": "文件",+ "fileCount": "{{count}} 个文件",+ "hint": "选择去向后,可以补充交代再发送。",+ "search": "搜索任务和伙伴",+ "newTask": "新建任务",+ "companions": "伙伴",+ "tasks": "已有任务",+ "unavailable": "暂不可接收分享",+ "noCompanions": "还没有伙伴",+ "noTasks": "还没有任务",+ "retry": "部分内容未能读取,点此重试。"}}diff --git a/apps/mobile/src/i18n/locales/zh-TW/composer.json b/apps/mobile/src/i18n/locales/zh-TW/composer.jsonindex 1e8f1e6253..5eec32cdc4 100644--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json@@ -103,5 +103,20 @@"transcriptKept": "{{message}}(識別出的文字已經保留,可以直接編輯)","micPermission": "麥克風權限未開啟,請在系統設定裡允許 {{appName}} 使用麥克風。","realtimeAudioUnavailable": "當前安裝包不支援即時語音輸入,請安裝包含原生錄音模組的測試版。"+ },+ "incomingShare": {+ "title": "傳送到 Cindy",+ "empty": "沒有待接收的分享",+ "file": "檔案",+ "fileCount": "{{count}} 個檔案",+ "hint": "選擇去向後,可以補充說明再傳送。",+ "search": "搜尋任務和夥伴",+ "newTask": "新增任務",+ "companions": "夥伴",+ "tasks": "現有任務",+ "unavailable": "暫時無法接收分享",+ "noCompanions": "還沒有夥伴",+ "noTasks": "還沒有任務",+ "retry": "部分內容未能讀取,點此重試。"}}diff --git a/apps/mobile/src/session/IncomingShareBridge.tsx b/apps/mobile/src/session/IncomingShareBridge.tsxindex 3491a5adba..15318f2cfd 100644--- a/apps/mobile/src/session/IncomingShareBridge.tsx+++ b/apps/mobile/src/session/IncomingShareBridge.tsx@@ -12,7 +12,7 @@ import {/*** 根级 Share Extension 桥:未登录时先保留 App Group payload;登录、路由都就绪后- * 再进入新建任务。真正清除原生 payload 的时机由新建页领取成功后触发。+ * 再选择任务或伙伴。目标编辑器领取成功后才清除原生 payload。*/export function IncomingShareBridge() {const auth = useAuth();@@ -74,14 +74,14 @@ export function IncomingShareBridge() {) {return;}- if (segments.join('/') === 'sessions/new') {+ if (segments.join('/') === 'incoming-share') {presentedBatchId.current = batch.id;return;}// A storage error leaves the batch pending. Let the user leave the error// screen and return to retry instead of repeatedly forcing it back open.presentedBatchId.current = batch.id;- router.navigate('/sessions/new');+ router.navigate('/incoming-share');}, [auth.initialized, auth.isAuthenticated, batch, router, segments]);return null;diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.tsindex 161d3deb55..8db12948ac 100644--- a/apps/mobile/src/session/incomingShare.ts+++ b/apps/mobile/src/session/incomingShare.ts@@ -1,8 +1,8 @@/**- * iOS Share Extension → 新建任务附件信箱。+ * iOS Share Extension → 任务/伙伴的内容信箱。** expo-sharing 把扩展收到的文件复制进 App Group,并在主 App 激活后提供本地- * payload。根导航只负责把 payload 放进这个进程内信箱;新建会话页领取后复用现有+ * payload。根导航把 payload 放进这个进程内信箱;用户选择的目标编辑器领取后复用现有* MobileLocalAttachmentUpload 管线。原生 payload 在领取成功前不清,避免登录/导航* 期间丢文件。*/@@ -28,6 +28,7 @@ export interface IncomingShareBatch {payloads: readonly ResolvedSharePayload[];acknowledge: () => void;owner: MobileAuthOwnerGeneration;+ destination?: string;}export interface IncomingShareUploadSelection {@@ -40,6 +41,10 @@ const pendingBatches: IncomingShareBatch[] = [];const listeners = new Set<() => void>();let unsubscribeOwner: (() => void) | undefined;+function isFilePayload(payload: Pick<SharePayload, 'shareType'>): boolean {+ return payload.shareType !== 'text' && payload.shareType !== 'url';+}+export async function deleteIncomingSharedFiles(uris: readonly string[]): Promise<void> {const FileSystem = await import('expo-file-system/legacy');await Promise.all([...new Set(uris)].filter((uri) => uri.startsWith('file://')).map((uri) => (@@ -100,7 +105,7 @@ function updateIncomingShareOwner(for (const batch of discarded) {pendingBatches.splice(pendingBatches.indexOf(batch), 1);acknowledgeBatch(batch);- void deleteIncomingSharedFiles(batch.payloads.map((payload) => payload.contentUri ?? payload.value))+ void deleteIncomingSharedFiles(batch.payloads.filter(isFilePayload).map((payload) => payload.contentUri ?? payload.value)).catch(() => undefined);}// New snapshots also wake the focused consumer after a rollback/first login.@@ -127,7 +132,7 @@ export function watchIncomingShareAccount(try {const raw = native.getSharedPayloads();native.clearSharedPayloads(raw);- void deleteIncomingSharedFiles(raw.map((payload) => payload.value)).catch(() => undefined);+ void deleteIncomingSharedFiles(raw.filter(isFilePayload).map((payload) => payload.value)).catch(() => undefined);} catch { /* Sharing is unavailable in older native binaries. */ }}}, previous);@@ -179,6 +184,24 @@ export function stageIncomingShareBatch(return batch;}+/** Only the destination explicitly chosen by the user may claim this batch. */+export function selectIncomingShareDestination(id: string, destination: string): boolean {+ if (!currentBatch || currentBatch.id !== id || !isMobileAuthOwnerCurrent(currentBatch.owner)) return false;+ currentBatch = { ...currentBatch, destination };+ pendingBatches[0] = currentBatch;+ emit();+ return true;+}++export function incomingShareText(payloads: readonly ResolvedSharePayload[]): string {+ return payloads.filter(payload => payload.shareType === 'text' || payload.shareType === 'url')+ .map(payload => payload.value).filter(value => value.trim()).join('\n\n');+}++export function incomingShareDestination(deviceId: string, sessionId: string): string {+ return JSON.stringify([deviceId, sessionId]);+}+export function consumeIncomingShareBatch(id: string): boolean {if (getMobileAuthOwner().switching || !currentBatch || currentBatch.id !== id|| !currentBatch.owner.accountKey || !isMobileAuthOwnerCurrent(currentBatch.owner)) return false;@@ -192,19 +215,27 @@ export function consumeIncomingShareBatch(id: string): boolean {return true;}+/** Cancelling the chooser discards only this share, never the source app's files. */+export function discardIncomingShareBatch(id: string): boolean {+ const batch = currentBatch;+ if (!batch || !consumeIncomingShareBatch(id)) return false;+ void deleteIncomingSharedFiles(batch.payloads.filter(isFilePayload).map(payload => payload.contentUri ?? payload.value)).catch(() => undefined);+ return true;+}+/** Raw local files need no asynchronous resolver; the uploader stats their size. */export function receiveIncomingShare(native: IncomingShareNative): void {if (getMobileAuthOwner().switching) return;const raw = native.getSharedPayloads();if (raw.length === 0) return;- const payloads = raw.map((payload): ResolvedSharePayload => ({- ...payload,- contentUri: payload.value,- contentType: payload.shareType === 'image' ? 'image' : 'file',- contentMimeType: payload.mimeType ?? null,- originalName: basenameFromUri(payload.value),- contentSize: null,- }));+ const payloads = raw.map((payload): ResolvedSharePayload => {+ const common = { ...payload, contentMimeType: payload.mimeType ?? null,+ originalName: basenameFromUri(payload.value), contentSize: null };+ return payload.shareType === 'text'+ ? { ...common, contentUri: null, contentType: 'text' }+ : { ...common, contentUri: payload.value,+ contentType: payload.shareType === 'url' ? 'website' : payload.shareType === 'image' ? 'image' : 'file' };+ });stageIncomingShareBatch(payloads, () => {// Native compares the captured bytes and clears under the writer's lock.native.clearSharedPayloads(raw);@@ -243,6 +274,7 @@ export function selectIncomingShareUploadCandidates(const rejectedUris: string[] = [];for (const payload of payloads) {+ if (!isFilePayload(payload)) continue;const uri = payload.contentUri?.trim()|| (payload.shareType === 'file' || payload.shareType === 'image'? payload.value.trim()@@ -262,8 +294,11 @@ export function selectIncomingShareUploadCandidates(&& payload.contentSize > 0? payload.contentSize: 0;- // 系统判定为图片、但扩展名不是可直传的图片格式(如 HEIC):转 JPEG 后按图片发送。- if (category === 'file' && isImage) {+ // Convert known raster encodings only. Vector/source images such as SVG or+ // PSD remain original files rather than failing UIKit's raster decoder.+ const imageExtension = extractRemoteFileExt(name).replace(/^\./, '');+ const convertibleImage = isImage && (!imageExtension || ['heic', 'heif', 'tif', 'tiff', 'bmp'].includes(imageExtension));+ if (category === 'file' && convertibleImage) {const index = candidates.length;candidates.push({kind: 'image',diff --git a/apps/mobile/src/session/incomingShareNative.ts b/apps/mobile/src/session/incomingShareNative.tsindex 0a2f845d80..298b0ddee3 100644--- a/apps/mobile/src/session/incomingShareNative.ts+++ b/apps/mobile/src/session/incomingShareNative.ts@@ -35,7 +35,7 @@ export function getSharedPayloads(): SharePayload[] {const raw: SharePayload[] = JSON.parse(snapshot).map((item: { value: string; type: SharePayload['shareType']; mimeType?: string }) => ({value: item.value, shareType: item.type, mimeType: item.mimeType,}));- const payloads = raw.filter((payload) => !isMissingShareCopy(payload.value));+ const payloads = raw.filter((payload) => payload.shareType === 'text' || payload.shareType === 'url' || !isMissingShareCopy(payload.value));snapshots.set(payloads, snapshot);if (raw.length > 0 && payloads.length === 0) {// Do not navigate to an empty draft, even when native acknowledgement fails.diff --git a/apps/mobile/src/session/useIncomingShareComposer.ts b/apps/mobile/src/session/useIncomingShareComposer.tsnew file mode 100644index 0000000000..799f5e5972--- /dev/null+++ b/apps/mobile/src/session/useIncomingShareComposer.ts@@ -0,0 +1,51 @@+import { useEffect, useRef } from 'react';+import { useIsFocused } from 'expo-router';+import { useAuth } from '@/auth/AuthContext';+import { getMobileAuthOwner } from '@/auth/authOwnerGeneration';+import { MOBILE_MAX_ATTACHMENTS } from './attachments';+import { consumeIncomingShareBatch, deleteIncomingSharedFiles, incomingShareText, useIncomingShareBatch } from './incomingShare';+import { selectIncomingShareUploadCandidates } from './incomingShare';+import type { useMobileLocalAttachments } from './useMobileLocalAttachments';+import { useTranslation } from 'react-i18next';++/** Shares enter the real composer: its existing upload, retry and send pipeline owns delivery. */+export function useIncomingShareComposer(options: {+ destination: string;+ ready: boolean;+ appendText(text: string): void;+ attachmentCount: number;+ enqueueUploads: ReturnType<typeof useMobileLocalAttachments>['enqueueUploads'];+ getPendingUploadCount(): number;+ onError(message: string | null): void;+}) {+ const batch = useIncomingShareBatch();+ const focused = useIsFocused();+ const auth = useAuth();+ const { t } = useTranslation();+ const latest = useRef(options); latest.current = options;+ const pendingCount = options.getPendingUploadCount();+ useEffect(() => {+ const target = latest.current;+ if (!focused || !target.ready || !batch || batch.destination !== target.destination+ || !auth.isAuthenticated || getMobileAuthOwner().accountId !== auth.user?.id) return;+ const selection = selectIncomingShareUploadCandidates(batch.payloads);+ if (selection.candidates.length + target.attachmentCount + target.getPendingUploadCount() > MOBILE_MAX_ATTACHMENTS) {+ // Retain the complete batch until the user frees space. Never silently drop files.+ target.onError(t('composer.upload.maxAttachments', { count: MOBILE_MAX_ATTACHMENTS }));+ return;+ }+ try {+ if (!consumeIncomingShareBatch(batch.id)) return;+ } catch {+ target.onError(t('composer.upload.shareReceiveFailed'));+ return;+ }+ const text = incomingShareText(batch.payloads);+ if (text) target.appendText(text);+ if (selection.candidates.length) target.enqueueUploads(selection.candidates.map(candidate => ({+ ...candidate, cleanupLocalUris: deleteIncomingSharedFiles,+ })), { token: auth.getAccessToken() });+ if (selection.rejectedUris.length) void deleteIncomingSharedFiles(selection.rejectedUris).catch(() => undefined);+ target.onError(selection.rejectedUris.length ? t('composer.upload.noFileRead') : null);+ }, [auth, batch, focused, options.destination, options.ready, options.attachmentCount, pendingCount, t]);+}