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): allow share retry after exit and virtualize destinations

Chris744859be0c8c
diff --git a/apps/mobile/app/incoming-share.tsx b/apps/mobile/app/incoming-share.tsx
index 96771177e5..6f8b4c106a 100644
--- a/apps/mobile/app/incoming-share.tsx
+++ b/apps/mobile/app/incoming-share.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef, useState } from 'react';
-import { ActivityIndicator, Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { ActivityIndicator, Pressable, FlatList, StyleSheet, View } from 'react-native';
import { useIsFocused, useNavigation, useRouter } from 'expo-router';
import { usePreventRemove } from 'expo-router/react-navigation';
import { goBackGuarded } from '@/utils/backGuard';
@@ -13,7 +13,7 @@ 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 { leaveIncomingShareChooser, incomingShareDestination, incomingShareText, selectIncomingShareDestination, useIncomingShareBatch } from '@/session/incomingShare';
import { useTeammateRoster } from '@/session/useTeammateRoster';
import { teammateResourceRoute } from '@/session/teammateNavigation';
import { remoteSessionStore } from '@/session/remoteSessionStore';
@@ -22,6 +22,14 @@ import { fontWeight, lineHeight, radius, spacing, typeScale, useTheme, useThemed
type Task = { deviceId: string; deviceName: string; session: RemoteSession };
+type Row = { key: string } & (
+ | { kind: 'new' }
+ | { kind: 'heading'; label: string }
+ | { kind: 'status'; label?: string; loading?: boolean; retry?: 'roster' | 'tasks' }
+ | { kind: 'companion'; item: ReturnType<typeof useTeammateRoster>['items'][number] }
+ | { kind: 'task'; item: Task }
+);
+
/** A destination chooser, not a second sending pipeline. Nothing is sent by selecting a row. */
export default function IncomingShareScreen() {
const batch = useIncomingShareBatch();
@@ -36,7 +44,6 @@ export default function IncomingShareScreen() {
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);
@@ -75,7 +82,23 @@ export default function IncomingShareScreen() {
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 rows = useMemo<Row[]>(() => {
+ const matches = (title: string) => title.normalize('NFKC').toLocaleLowerCase(i18n.language).includes(needle);
+ const result: Row[] = [{ key: 'new', kind: 'new' },
+ { key: 'companions', kind: 'heading', label: t('composer.incomingShare.companions') }];
+ for (const item of roster.items) if (matches(resolveRemoteText(item.item.display.title, i18n.language)))
+ result.push({ key: `companion:${item.key}`, kind: 'companion', item });
+ if (roster.loading) result.push({ key: 'companions-loading', kind: 'status', loading: true });
+ else if (!roster.items.length) result.push({ key: 'companions-empty', kind: 'status', label: t('composer.incomingShare.noCompanions') });
+ if (roster.error) result.push({ key: 'companions-retry', kind: 'status', retry: 'roster', label: t('composer.incomingShare.retry') });
+ result.push({ key: 'tasks', kind: 'heading', label: t('composer.incomingShare.tasks') });
+ for (const item of tasks) if (matches(item.session.title))
+ result.push({ key: `task:${incomingShareDestination(item.deviceId, item.session.id)}`, kind: 'task', item });
+ if (loading) result.push({ key: 'tasks-loading', kind: 'status', loading: true });
+ else if (!tasks.length) result.push({ key: 'tasks-empty', kind: 'status', label: t('composer.incomingShare.noTasks') });
+ if (error) result.push({ key: 'tasks-retry', kind: 'status', retry: 'tasks', label: t('composer.incomingShare.retry') });
+ return result;
+ }, [needle, i18n.language, t, roster.items, roster.loading, roster.error, tasks, loading, error]);
const text = batch ? incomingShareText(batch.payloads) : '';
const files = batch?.payloads.filter(item => item.shareType !== 'text' && item.shareType !== 'url') ?? [];
const handoffBatchId = useRef<string | null>(null);
@@ -88,14 +111,12 @@ export default function IncomingShareScreen() {
// Removing the chooser during a handoff retains the batch for its composer.
// Header/gesture cancellation still acknowledges and cleans the owned copies.
usePreventRemove(!!batch, ({ data }) => {
- try { if (batch && handoffBatchId.current !== batch.id) discardIncomingShareBatch(batch.id); }
- catch { setDismissError(t('composer.upload.shareReceiveFailed')); return; }
- navigation.dispatch(data.action);
+ leaveIncomingShareChooser(batch && handoffBatchId.current !== batch.id ? batch.id : null,
+ () => navigation.dispatch(data.action));
});
const back = () => goBackGuarded(router);
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>}
@@ -108,37 +129,41 @@ export default function IncomingShareScreen() {
<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.dismissTo('/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.dismissTo(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>
+ <FlatList<Row> data={rows} keyExtractor={row => row.key}
+ keyboardShouldPersistTaps="handled" contentContainerStyle={styles.list}
+ initialNumToRender={12} maxToRenderPerBatch={12} windowSize={7}
+ renderItem={({ item: row }) => {
+ if (row.kind === 'heading') return <Text style={styles.sectionLabel}>{row.label}</Text>;
+ if (row.kind === 'status') {
+ if (row.loading) return <ActivityIndicator color={colors.textSecondary} />;
+ if (row.retry) return <Pressable style={styles.row} onPress={() => row.retry === 'roster'
+ ? void roster.refresh() : setAttempt(value => value + 1)}><Text style={styles.note}>{row.label}</Text></Pressable>;
+ return <Text style={styles.note}>{row.label}</Text>;
+ }
+ if (row.kind === 'new') return <Pressable accessibilityRole="button" style={styles.row}
+ onPress={() => choose('new', () => router.dismissTo('/sessions/new'))}>
+ <Text style={styles.title}>{t('composer.incomingShare.newTask')}</Text>
+ </Pressable>;
+ if (row.kind === 'companion') {
+ const item = row.item;
+ const conversation = item.item.links.find(link => link.rel === 'conversation')?.target;
+ return <Pressable accessibilityRole="button" style={styles.row}
+ disabled={conversation?.kind !== 'session'} onPress={() => {
+ if (conversation?.kind === 'session') choose(incomingShareDestination(item.host.deviceId, conversation.sessionId),
+ () => router.dismissTo(teammateResourceRoute(item, i18n.language)));
+ }}>
+ <Text style={styles.title}>{resolveRemoteText(item.item.display.title, i18n.language)}</Text>
+ <Text style={styles.note}>{item.host.deviceName}{conversation?.kind !== 'session' ? ` · ${t('composer.incomingShare.unavailable')}` : ''}</Text>
+ </Pressable>;
+ }
+ const item = row.item;
+ return <Pressable accessibilityRole="button" style={styles.row}
+ onPress={() => choose(incomingShareDestination(item.deviceId, item.session.id), () => router.dismissTo({
+ pathname: '/sessions/[sessionId]', params: { deviceId: item.deviceId, deviceName: item.deviceName, sessionId: item.session.id },
+ }))}>
+ <Text style={styles.title}>{item.session.title}</Text><Text style={styles.note}>{item.deviceName}</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.dismissTo({
- 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>;
}
diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.ts
index fc7a273277..3e78a6665e 100644
--- a/apps/mobile/src/__tests__/incomingShare.test.ts
+++ b/apps/mobile/src/__tests__/incomingShare.test.ts
@@ -6,6 +6,7 @@ import {
__resetIncomingShareForTest,
consumeIncomingShareBatch,
discardIncomingShareBatch,
+ leaveIncomingShareChooser,
incomingShareBatchId,
selectIncomingShareUploadCandidates,
stageIncomingShareBatch,
@@ -60,6 +61,18 @@ describe('incoming Share Extension payloads', () => {
convertToJpeg.mockClear();
});
+ it('leaves after native cancellation fails without losing files or the retryable batch', () => {
+ const acknowledge = vi.fn().mockImplementationOnce(() => { throw new Error('storage unavailable'); });
+ const batch = stageIncomingShareBatch([payload({})], acknowledge)!;
+ const leave = vi.fn();
+ leaveIncomingShareChooser(batch.id, leave);
+ expect(leave).toHaveBeenCalledOnce();
+ expect(deleteAsync).not.toHaveBeenCalled();
+ expect(stageIncomingShareBatch([payload({})], vi.fn())).toBe(batch);
+ expect(consumeIncomingShareBatch(batch.id)).toBe(true);
+ expect(acknowledge).toHaveBeenCalledTimes(2);
+ });
+
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([]);
diff --git a/apps/mobile/src/__tests__/incomingShareBridge.test.ts b/apps/mobile/src/__tests__/incomingShareBridge.test.ts
index b4198f10f3..6d2f78b5b0 100644
--- a/apps/mobile/src/__tests__/incomingShareBridge.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareBridge.test.ts
@@ -2,6 +2,8 @@ import { beforeEach, expect, it, vi } from 'vitest';
import { IncomingShareBridge } from '@/session/IncomingShareBridge';
const mock = vi.hoisted(() => ({
+ linkReceived: undefined as ((event: { url: string }) => void) | undefined,
+ shareLinkAttempt: 0,
effects: [] as Array<() => (() => void) | void>,
cleanup: vi.fn(), receive: vi.fn(), stop: vi.fn(),
ownerChanged: undefined as (() => void) | undefined,
@@ -14,11 +16,12 @@ const mock = vi.hoisted(() => ({
vi.mock('react', () => ({
useEffect: (effect: () => void) => mock.effects.push(effect),
useRef: () => mock.presented,
+ useState: () => [mock.shareLinkAttempt, (next: (value: number) => number) => { mock.shareLinkAttempt = next(mock.shareLinkAttempt); }],
}));
vi.mock('react-native', () => ({
Platform: { OS: 'ios' },
AppState: { get currentState() { return mock.appState; }, addEventListener: () => ({ remove: vi.fn() }) },
- Linking: { addEventListener: () => ({ remove: vi.fn() }) },
+ Linking: { addEventListener: (_event: string, listener: (event: { url: string }) => void) => { mock.linkReceived = listener; return { remove: vi.fn() }; } },
}));
vi.mock('expo-router', () => ({ useRouter: () => ({ navigate: mock.navigate }), useSegments: () => mock.segments }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => mock.auth }));
@@ -34,7 +37,7 @@ vi.mock('@/session/incomingShareNative', () => ({}));
vi.mock('@/session/incomingShareCleanup', () => ({ cleanupExpiredIncomingShares: mock.cleanup }));
beforeEach(() => {
- mock.effects.length = 0; mock.ownerChanged = undefined;
+ mock.effects.length = 0; mock.ownerChanged = undefined; mock.linkReceived = undefined; mock.shareLinkAttempt = 0;
mock.presented.current = null; mock.batch = null; mock.segments = [];
mock.auth = { initialized: true, isAuthenticated: true };
mock.switching = false; mock.appState = 'active'; vi.clearAllMocks();
@@ -122,3 +125,24 @@ it('refreshes shares when a switch settles in foreground, and unsubscribes on un
unmount?.();
expect(mock.unsubscribe).toHaveBeenCalledOnce();
});
+
+// Native acknowledgement failure leaves the same batch pending. Background/route
+// changes must not trap the user, but a deliberate new share link can retry it.
+it('reopens a retained batch only when another explicit share link arrives', async () => {
+ mock.batch = { id: 'retained' };
+ IncomingShareBridge();
+ const stop = mock.effects[0]!();
+ await vi.waitFor(() => expect(mock.linkReceived).toBeDefined());
+ navigatePendingShare();
+ mock.segments = []; navigatePendingShare();
+ expect(mock.navigate).toHaveBeenCalledTimes(1);
+ mock.linkReceived!({ url: 'cindy://auth?code=example' });
+ await vi.waitFor(() => expect(mock.receive).toHaveBeenCalledTimes(2));
+ navigatePendingShare();
+ expect(mock.navigate).toHaveBeenCalledTimes(1);
+ mock.linkReceived!({ url: 'cindy://expo-sharing' });
+ await vi.waitFor(() => expect(mock.shareLinkAttempt).toBe(1));
+ navigatePendingShare();
+ expect(mock.navigate).toHaveBeenCalledTimes(2);
+ stop?.();
+});
diff --git a/apps/mobile/src/session/IncomingShareBridge.tsx b/apps/mobile/src/session/IncomingShareBridge.tsx
index 15318f2cfd..ffa7361deb 100644
--- a/apps/mobile/src/session/IncomingShareBridge.tsx
+++ b/apps/mobile/src/session/IncomingShareBridge.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { AppState, Linking, Platform } from 'react-native';
import { useRouter, useSegments } from 'expo-router';
@@ -19,6 +19,7 @@ export function IncomingShareBridge() {
const router = useRouter();
const segments = useSegments();
const batch = useIncomingShareBatch();
+ const [shareLinkAttempt, setShareLinkAttempt] = useState(0);
const presentedBatchId = useRef<string | null>(null);
useEffect(() => {
if (Platform.OS !== 'ios') return;
@@ -29,7 +30,7 @@ export function IncomingShareBridge() {
void import('@/session/incomingShareNative').then((sharing) => {
if (!active) return;
stopWatchingAccount = watchIncomingShareAccount(sharing, initialOwner);
- const refresh = () => {
+ const refresh = (explicitShare = false) => {
void import('@/session/incomingShareCleanup')
.then(({ cleanupExpiredIncomingShares }) => cleanupExpiredIncomingShares())
.catch(() => undefined)
@@ -40,6 +41,10 @@ export function IncomingShareBridge() {
// copies before they can trigger navigation.
try {
receiveIncomingShare(sharing);
+ if (explicitShare) {
+ presentedBatchId.current = null;
+ setShareLinkAttempt(value => value + 1);
+ }
} catch {
// Inbound sharing is unavailable in older native binaries.
}
@@ -47,7 +52,7 @@ export function IncomingShareBridge() {
};
subscriptions = [
AppState.addEventListener('change', (state) => { if (state === 'active') refresh(); }),
- Linking.addEventListener('url', refresh),
+ Linking.addEventListener('url', ({ url }) => refresh(/^[a-z][a-z0-9+.-]*:\/\/expo-sharing(?:[/?#]|$)/i.test(url))),
{ remove: subscribeMobileAuthOwner(() => {
if (!getMobileAuthOwner().switching && AppState.currentState === 'active') refresh();
}) },
@@ -82,7 +87,7 @@ export function IncomingShareBridge() {
// screen and return to retry instead of repeatedly forcing it back open.
presentedBatchId.current = batch.id;
router.navigate('/incoming-share');
- }, [auth.initialized, auth.isAuthenticated, batch, router, segments]);
+ }, [auth.initialized, auth.isAuthenticated, batch, router, segments, shareLinkAttempt]);
return null;
}
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index 8db12948ac..eb7618b7b2 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -223,6 +223,13 @@ export function discardIncomingShareBatch(id: string): boolean {
return true;
}
+/** A failed native acknowledgement retains the batch, but must not trap navigation. */
+export function leaveIncomingShareChooser(cancelBatchId: string | null, leave: () => void): void {
+ try { if (cancelBatchId) discardIncomingShareBatch(cancelBatchId); }
+ catch { /* Keep the unacknowledged batch and owned files available for retry. */ }
+ leave();
+}
+
/** Raw local files need no asynchronous resolver; the uploader stats their size. */
export function receiveIncomingShare(native: IncomingShareNative): void {
if (getMobileAuthOwner().switching) return;