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): 防止已处理分享附件在重启后恢复

Dashfd3713202eda
diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts
index 51ecb9cae4..812c1b4c03 100644
--- a/apps/mobile/app/+native-intent.ts
+++ b/apps/mobile/app/+native-intent.ts
@@ -17,7 +17,7 @@
import { WECHAT_APP_ID, WECHAT_UNIVERSAL_LINK } from '@/config/env';
import { isWechatSdkCallback } from '@/auth/wechatCallback';
-export function redirectSystemPath({ path }: { path: string; initial: boolean }): string {
+export function redirectSystemPath({ path, initial }: { path: string; initial: boolean }): string {
try {
// OpenSDK 的授权及 Universal Link 校验回调也会被 Expo Linking 广播给 Router。
// 它们由原生 delegate 消费,不能当页面显示(更不能在 404 中展示 code)。
@@ -31,7 +31,9 @@ export function redirectSystemPath({ path }: { path: string; initial: boolean })
const pathname = noScheme.split('?')[0].split('#')[0].replace(/\/+$/, '') || '/';
// 命中 OAuth 回调 → 回首页;Share Extension → 新建任务;其余深链原样放行。
if (pathname === '/auth') return '/';
- if (pathname === '/expo-sharing') return '/sessions/new';
+ // A restored launch URL is not proof of an unconsumed share. On cold start,
+ // let IncomingShareBridge navigate only after reading an actual pending batch.
+ if (pathname === '/expo-sharing') return initial ? '/' : '/sessions/new';
return path;
} catch {
return path;
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 750315fa8c..25c946569c 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -777,8 +777,13 @@ export default function NewRemoteSessionScreen() {
const isShareTargetFocused = useIsFocused();
useEffect(() => {
if (!isShareTargetFocused || !auth.isAuthenticated || !incomingShareBatch
- || getMobileAuthOwner().accountId !== auth.user?.id
- || !consumeIncomingShareBatch(incomingShareBatch.id)) return;
+ || 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,
diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.ts
index 9935140bec..a81b854d28 100644
--- a/apps/mobile/src/__tests__/incomingShare.test.ts
+++ b/apps/mobile/src/__tests__/incomingShare.test.ts
@@ -5,6 +5,7 @@ import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch, isMobileAuthOwn
import {
__resetIncomingShareForTest,
consumeIncomingShareBatch,
+ deleteIncomingSharedFiles,
incomingShareBatchId,
selectIncomingShareUploadCandidates,
stageIncomingShareBatch,
@@ -13,7 +14,7 @@ import {
} from '@/session/incomingShare';
const convertToJpeg = vi.fn(async (uri: string) => `${uri}.jpg`);
-const deleteAsync = vi.hoisted(() => vi.fn(async () => undefined));
+const deleteAsync = vi.hoisted(() => vi.fn(async (_uri: string, _options: { idempotent: boolean }) => undefined));
vi.mock('expo-file-system/legacy', () => ({ deleteAsync }));
vi.mock('@/session/pastedImageAttachment', async (importOriginal) => {
@@ -192,6 +193,27 @@ describe('incoming Share Extension payloads', () => {
expect(native.clearSharedPayloads).toHaveBeenCalledTimes(2);
});
+ it('retains the mailbox until durable acknowledgement succeeds', () => {
+ const acknowledge = vi.fn().mockImplementationOnce(() => { throw new Error('storage unavailable'); });
+ const batch = stageIncomingShareBatch([payload({})], acknowledge)!;
+ expect(() => consumeIncomingShareBatch(batch.id)).toThrow('storage unavailable');
+ expect(stageIncomingShareBatch([payload({})], vi.fn())).toBe(batch);
+ expect(consumeIncomingShareBatch(batch.id)).toBe(true);
+ expect(consumeIncomingShareBatch(batch.id)).toBe(false);
+ expect(acknowledge).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the receipt directory when cancelling cannot delete the copy', async () => {
+ const directory = 'file:///group/cindy-share-12345678-1234-1234-1234-123456789abc';
+ const uri = `${directory}/report.pdf`;
+ deleteAsync.mockRejectedValueOnce(new Error('busy'));
+ await deleteIncomingSharedFiles([uri]);
+ expect(deleteAsync).toHaveBeenCalledExactlyOnceWith(uri, { idempotent: true });
+ deleteAsync.mockClear();
+ await deleteIncomingSharedFiles([uri]);
+ expect(deleteAsync.mock.calls.map(([uri]) => uri)).toEqual([uri, directory]);
+ });
+
it('never treats remote URLs as local upload/cleanup targets', () => {
expect(selectIncomingShareUploadCandidates([payload({ contentUri: 'https://example.com/report.pdf' })]))
.toEqual({ candidates: [], rejectedUris: [] });
diff --git a/apps/mobile/src/__tests__/incomingShareCleanup.test.ts b/apps/mobile/src/__tests__/incomingShareCleanup.test.ts
index 67b80e3f3f..b517e07c6d 100644
--- a/apps/mobile/src/__tests__/incomingShareCleanup.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareCleanup.test.ts
@@ -4,10 +4,12 @@ import { cleanupExpiredIncomingShares } from '@/session/incomingShareCleanup';
const fs = vi.hoisted(() => {
class Directory {
uri: string;
+ children: Array<Directory | { uri: string }> = [];
constructor(public name: string, public created?: number) {
this.uri = `file:///app-group/${name}`;
}
info() { return { creationTime: this.created }; }
+ list() { return this.children; }
}
return { Directory, roots: {} as Record<string, { list: () => unknown[] }>, delete: vi.fn() };
});
@@ -58,4 +60,17 @@ describe('incoming share copy expiry', () => {
await cleanupExpiredIncomingShares(now);
expect(fs.delete).toHaveBeenCalledTimes(4);
});
+
+ it('retains receipts when an expired copy cannot be deleted', async () => {
+ const expired = new fs.Directory(name, 1);
+ const copy = { uri: `${expired.uri}/report.pdf` };
+ expired.children = [new fs.Directory('.cindy-share-consumed'), copy];
+ fs.roots.sharing = { list: () => [expired] };
+ fs.delete.mockRejectedValueOnce(new Error('busy'));
+ await cleanupExpiredIncomingShares(now);
+ expect(fs.delete).toHaveBeenCalledExactlyOnceWith(copy.uri, { idempotent: true });
+ fs.delete.mockClear();
+ await cleanupExpiredIncomingShares(now);
+ expect(fs.delete.mock.calls.map(([uri]) => uri)).toEqual([copy.uri, expired.uri]);
+ });
});
diff --git a/apps/mobile/src/__tests__/incomingShareNative.test.ts b/apps/mobile/src/__tests__/incomingShareNative.test.ts
index aa26b8f2e4..4a6b55f640 100644
--- a/apps/mobile/src/__tests__/incomingShareNative.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareNative.test.ts
@@ -1,10 +1,46 @@
import { beforeEach, expect, it, vi } from 'vitest';
const native = vi.hoisted(() => ({ readSnapshot: vi.fn(), clearSnapshot: vi.fn() }));
+const fs = vi.hoisted(() => {
+ const listings = new Map<string, Array<{ uri: string; name: string }> | Error>();
+ const failCreate = new Set<string>();
+ class Directory {
+ uri: string;
+ constructor(parent: string | Directory, name?: string) {
+ this.uri = `${typeof parent === 'string' ? parent : parent.uri}${name ? `/${name}` : ''}`;
+ }
+ get name() { return this.uri.split('/').at(-1)!; }
+ list(): Array<{ uri: string; name: string }> {
+ const value = listings.get(this.uri);
+ if (!value || value instanceof Error) throw value ?? new Error('unavailable');
+ return value;
+ }
+ create() {
+ if (failCreate.has(this.uri)) throw new Error('disk full');
+ const parent = new Directory(this.uri.slice(0, this.uri.lastIndexOf('/')));
+ const entries = parent.list();
+ if (entries.some((entry) => entry.name === this.name)) throw new Error('already exists');
+ entries.push(this);
+ listings.set(this.uri, []);
+ }
+ delete() {
+ const parent = new Directory(this.uri.slice(0, this.uri.lastIndexOf('/')));
+ listings.set(parent.uri, parent.list().filter((entry) => entry.uri !== this.uri));
+ listings.delete(this.uri);
+ }
+ }
+ return { Directory, listings, failCreate };
+});
vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => native }));
+vi.mock('expo-file-system', () => ({ Directory: fs.Directory }));
import { getSharedPayloads, clearSharedPayloads } from '@/session/incomingShareNative';
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.resetAllMocks();
+ fs.listings.clear();
+ fs.failCreate.clear();
+ native.clearSnapshot.mockReturnValue(true);
+});
it('acknowledges the exact captured bytes, not a subsequent read or re-encoded payload', () => {
const first = '[ { "type":"file", "value":"file:///a/report.pdf", "mimeType":"application/pdf" } ]';
@@ -23,3 +59,135 @@ it('never clears a slot for an unknown array or missing native snapshot', () =>
clearSharedPayloads([]);
expect(native.clearSnapshot).not.toHaveBeenCalled();
});
+
+const root = 'file:///group';
+const directory = new fs.Directory(`${root}/cindy-share-12345678-1234-1234-1234-123456789abc`);
+const uri = `${directory.uri}/report.pdf`;
+const snapshot = JSON.stringify([{ type: 'file', value: uri }]);
+
+it.each(['directory', 'file'])('does not replay a share whose %s was deleted before restart', (missing) => {
+ fs.listings.set(root, missing === 'directory' ? [] : [directory]);
+ fs.listings.set(directory.uri, []);
+ native.readSnapshot.mockReturnValue(snapshot);
+ expect(getSharedPayloads()).toEqual([]);
+ expect(native.clearSnapshot).toHaveBeenCalledExactlyOnceWith(snapshot);
+ // There is no in-memory consumed flag: a fresh read must also reject the orphan.
+ expect(getSharedPayloads()).toEqual([]);
+});
+
+it('does not navigate to an orphan even if native clearing fails', () => {
+ fs.listings.set(root, []);
+ native.readSnapshot.mockReturnValue(snapshot);
+ native.clearSnapshot.mockImplementation(() => { throw new Error('native write failed'); });
+ expect(getSharedPayloads()).toEqual([]);
+ expect(getSharedPayloads()).toEqual([]);
+});
+
+it.each(['root', 'directory'])('preserves shares when the %s cannot be read', (inaccessible) => {
+ fs.listings.set(root, inaccessible === 'root' ? new Error('protected') : [directory]);
+ fs.listings.set(directory.uri, new Error('protected'));
+ native.readSnapshot.mockReturnValue(snapshot);
+ expect(getSharedPayloads()).toEqual([{ shareType: 'file', value: uri, mimeType: undefined }]);
+ expect(native.clearSnapshot).not.toHaveBeenCalled();
+});
+
+it('preserves a real file with Unicode, spaces and literal percent escapes in its name', () => {
+ const encodedUri = `${directory.uri}/${encodeURIComponent('讨论稿 100% %20.pdf')}`;
+ fs.listings.set(root, [directory]);
+ fs.listings.set(directory.uri, [{ uri: encodedUri, name: encodedUri.split('/').at(-1)! }]);
+ native.readSnapshot.mockReturnValue(JSON.stringify([{ type: 'file', value: encodedUri }]));
+ expect(getSharedPayloads()).toHaveLength(1);
+ expect(native.clearSnapshot).not.toHaveBeenCalled();
+});
+
+it('keeps valid files in a mixed batch and acknowledges the original bytes only after consumption', () => {
+ const live = `${directory.uri}/live.pdf`;
+ const mixed = JSON.stringify([{ type: 'file', value: uri }, { type: 'file', value: live }]);
+ fs.listings.set(root, [directory]);
+ fs.listings.set(directory.uri, [{ uri: live, name: 'live.pdf' }]);
+ native.readSnapshot.mockReturnValue(mixed);
+ const payloads = getSharedPayloads();
+ expect(payloads).toEqual([{ shareType: 'file', value: live, mimeType: undefined }]);
+ expect(native.clearSnapshot).not.toHaveBeenCalled();
+ clearSharedPayloads(payloads);
+ expect(native.clearSnapshot).toHaveBeenCalledExactlyOnceWith(mixed);
+});
+
+it('never clears a newer share that arrives during stale-file inspection', () => {
+ let slot = snapshot;
+ native.readSnapshot.mockImplementation(() => slot);
+ native.clearSnapshot.mockImplementation((expected) => {
+ if (slot === expected) slot = '';
+ return slot === '';
+ });
+ const next = '[{"type":"file","value":"file:///new/report.pdf"}]';
+ fs.listings.set(root, []);
+ const list = vi.spyOn(fs.Directory.prototype, 'list').mockImplementationOnce(() => {
+ slot = next;
+ return [];
+ });
+ expect(getSharedPayloads()).toEqual([]);
+ expect(slot).toBe(next);
+ expect(getSharedPayloads()).toHaveLength(1);
+ list.mockRestore();
+});
+
+it('leaves unmanaged paths and remote URLs to the existing share handling', () => {
+ native.readSnapshot.mockReturnValue(JSON.stringify([
+ { type: 'file', value: 'file:///original.pdf' },
+ { type: 'url', value: 'https://example.com/report.pdf' },
+ ]));
+ expect(getSharedPayloads()).toHaveLength(2);
+ expect(native.clearSnapshot).not.toHaveBeenCalled();
+});
+
+it.each(['throw', 'false'])('does not replay existing files after native acknowledgement returns %s', async (failure) => {
+ fs.listings.set(root, [directory]);
+ fs.listings.set(directory.uri, [{ uri, name: 'report.pdf' }]);
+ native.readSnapshot.mockReturnValue(snapshot);
+ native.clearSnapshot.mockImplementation(() => {
+ if (failure === 'throw') throw new Error('native storage failed');
+ return false;
+ });
+ clearSharedPayloads(getSharedPayloads());
+ expect(directory.list().some((entry) => entry.uri === uri)).toBe(true);
+ // Simulate process death: native storage and filesystem survive; JS receipts do not.
+ vi.resetModules();
+ const restarted = await import('@/session/incomingShareNative');
+ expect(restarted.getSharedPayloads()).toEqual([]);
+ // Explicitly sharing the same named file again produces a fresh UUID directory.
+ const nextDirectory = new fs.Directory(`${root}/cindy-share-abcdefab-1234-1234-1234-123456789abc`);
+ const nextUri = `${nextDirectory.uri}/report.pdf`;
+ fs.listings.set(root, [directory, nextDirectory]);
+ fs.listings.set(nextDirectory.uri, [{ uri: nextUri, name: 'report.pdf' }]);
+ native.readSnapshot.mockReturnValue(JSON.stringify([{ type: 'file', value: nextUri }]));
+ expect(restarted.getSharedPayloads()).toEqual([{ shareType: 'file', value: nextUri, mimeType: undefined }]);
+});
+
+it('never overwrites a source file named like the receipt directory', () => {
+ const collisionUri = `${directory.uri}/.cindy-share-consumed`;
+ fs.listings.set(root, [directory]);
+ fs.listings.set(directory.uri, [{ uri: collisionUri, name: '.cindy-share-consumed' }]);
+ native.readSnapshot.mockReturnValue(JSON.stringify([{ type: 'file', value: collisionUri }]));
+ native.clearSnapshot.mockImplementation(() => { throw new Error('native storage failed'); });
+ const payloads = getSharedPayloads();
+ expect(payloads).toHaveLength(1);
+ expect(() => clearSharedPayloads(payloads)).toThrow('already exists');
+ expect(directory.list()).toEqual([{ uri: collisionUri, name: '.cindy-share-consumed' }]);
+});
+
+it('rolls back partial receipts when acknowledgement fails for a multi-file share', () => {
+ const other = new fs.Directory(`${root}/cindy-share-abcdefab-1234-1234-1234-123456789abc`);
+ const otherUri = `${other.uri}/report.pdf`;
+ fs.listings.set(root, [directory, other]);
+ fs.listings.set(directory.uri, [{ uri, name: 'report.pdf' }]);
+ fs.listings.set(other.uri, [{ uri: otherUri, name: 'report.pdf' }]);
+ native.readSnapshot.mockReturnValue(JSON.stringify([
+ { type: 'file', value: uri }, { type: 'file', value: otherUri },
+ ]));
+ native.clearSnapshot.mockImplementation(() => { throw new Error('native storage failed'); });
+ fs.failCreate.add(`${other.uri}/.cindy-share-consumed`);
+ expect(() => clearSharedPayloads(getSharedPayloads())).toThrow('disk full');
+ expect(getSharedPayloads()).toHaveLength(2);
+ expect(directory.list()).toEqual([{ uri, name: 'report.pdf' }]);
+});
diff --git a/apps/mobile/src/__tests__/nativeIntent.test.ts b/apps/mobile/src/__tests__/nativeIntent.test.ts
index 7d509ca5f6..fb2da4705a 100644
--- a/apps/mobile/src/__tests__/nativeIntent.test.ts
+++ b/apps/mobile/src/__tests__/nativeIntent.test.ts
@@ -47,11 +47,11 @@ describe('mobile native deep-link redirects', () => {
}
});
- it('routes the Share Extension handoff into a new conversation', () => {
+ it('waits for a pending batch on cold start and preserves the warm share handoff', () => {
expect(redirectSystemPath({
path: 'cindycn://expo-sharing',
initial: true,
- })).toBe('/sessions/new');
+ })).toBe('/');
expect(redirectSystemPath({
path: '/expo-sharing?source=share-extension',
initial: false,
diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.json
index 0103352456..7ae777052e 100644
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@ -42,6 +42,7 @@
}
},
"upload": {
+ "shareReceiveFailed": "Couldn't finish receiving the shared files. Free up storage, then reopen this screen to retry.",
"emptyFile": "This file is empty and can't be sent as an attachment.",
"fileTooLarge": "The file exceeds {{size}} MB and can't be sent as an attachment for now.",
"cancelled": "Attachment upload cancelled.",
diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.json
index aa4dae295e..47048d02ca 100644
--- a/apps/mobile/src/i18n/locales/ja/composer.json
+++ b/apps/mobile/src/i18n/locales/ja/composer.json
@@ -42,6 +42,7 @@
}
},
"upload": {
+ "shareReceiveFailed": "共有ファイルの受信を完了できませんでした。ストレージの空き容量を確認し、この画面を開き直して再試行してください。",
"emptyFile": "このファイルは空のため、添付ファイルとして送信できません。",
"fileTooLarge": "ファイルが {{size}} MB を超えているため、現在は添付ファイルとして送信できません。",
"cancelled": "添付ファイルのアップロードをキャンセルしました。",
diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.json
index 0dc903524b..22b329a8ce 100644
--- a/apps/mobile/src/i18n/locales/ko/composer.json
+++ b/apps/mobile/src/i18n/locales/ko/composer.json
@@ -42,6 +42,7 @@
}
},
"upload": {
+ "shareReceiveFailed": "공유 파일 수신을 완료하지 못했습니다. 저장 공간을 확인한 후 이 화면을 다시 열어 재시도해 주세요.",
"emptyFile": "이 파일은 비어 있어 첨부 파일로 보낼 수 없습니다.",
"fileTooLarge": "파일이 {{size}} MB를 초과하여 지금은 첨부 파일로 보낼 수 없습니다.",
"cancelled": "첨부 파일 업로드를 취소했습니다.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.json
index c3e03f9f7f..51ac0359da 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@ -42,6 +42,7 @@
}
},
"upload": {
+ "shareReceiveFailed": "未能完成分享文件的接收。请检查存储空间,然后重新打开此页面重试。",
"emptyFile": "这个文件为空,不能作为附件发送。",
"fileTooLarge": "文件超过 {{size}} MB,暂不能作为附件发送。",
"cancelled": "附件上传已取消。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/composer.json b/apps/mobile/src/i18n/locales/zh-TW/composer.json
index 603a65304b..48869c158d 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json
@@ -42,6 +42,7 @@
}
},
"upload": {
+ "shareReceiveFailed": "未能完成分享檔案的接收。請檢查儲存空間,然後重新開啟此頁面重試。",
"emptyFile": "這個檔案為空,不能作為附件傳送。",
"fileTooLarge": "檔案超過 {{size}} MB,暫不能作為附件傳送。",
"cancelled": "附件上傳已取消。",
diff --git a/apps/mobile/src/session/IncomingShareBridge.tsx b/apps/mobile/src/session/IncomingShareBridge.tsx
index 19b82ead26..85b93ff06c 100644
--- a/apps/mobile/src/session/IncomingShareBridge.tsx
+++ b/apps/mobile/src/session/IncomingShareBridge.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from 'react';
+import { useEffect, useRef } 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 presentedBatchId = useRef<string | null>(null);
useEffect(() => {
if (Platform.OS !== 'ios') return;
let active = true;
@@ -35,8 +36,8 @@ export function IncomingShareBridge() {
.then(() => {
if (!active) return;
// Sweep before staging, so an expired native copy cannot start a new
- // upload concurrently with deletion. Missing copies use the existing
- // upload error path; the user can share the original again.
+ // upload concurrently with deletion. The native adapter filters missing
+ // and already-consumed copies before they can trigger navigation.
try {
receiveIncomingShare(sharing);
} catch {
@@ -61,15 +62,25 @@ export function IncomingShareBridge() {
}, []);
useEffect(() => {
+ if (!batch) {
+ presentedBatchId.current = null;
+ return;
+ }
if (
- !batch
- || !auth.initialized
+ !auth.initialized
|| !auth.isAuthenticated
|| segments[0] === '(auth)'
- || segments.join('/') === 'sessions/new'
+ || presentedBatchId.current === batch.id
) {
return;
}
+ if (segments.join('/') === 'sessions/new') {
+ 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');
}, [auth.initialized, auth.isAuthenticated, batch, router, segments]);
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index 03324bf10e..b8a57b9a74 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -42,13 +42,14 @@ let unsubscribeOwner: (() => void) | undefined;
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) => (
- FileSystem.deleteAsync(
- // Each native input owns one UUID directory; converted images are files.
- uri.match(/^(file:\/\/.*\/cindy-share-[\da-f-]{36})\/[^/]+$/i)?.[1] ?? uri,
- { idempotent: true },
- ).catch(() => undefined)
- )));
+ await Promise.all([...new Set(uris)].filter((uri) => uri.startsWith('file://')).map(async (uri) => {
+ try {
+ // Delete the copy first. A failed deletion must retain its consumption receipt.
+ await FileSystem.deleteAsync(uri, { idempotent: true });
+ const directory = uri.match(/^(file:\/\/.*\/cindy-share-[\da-f-]{36})\/[^/]+$/i)?.[1];
+ if (directory) await FileSystem.deleteAsync(directory, { idempotent: true });
+ } catch { /* The existing expiry sweep reclaims orphan copies later. */ }
+ }));
}
function acknowledgeBatch(batch: IncomingShareBatch): void {
@@ -183,10 +184,12 @@ export function consumeIncomingShareBatch(id: string): boolean {
if (getMobileAuthOwner().switching || !currentBatch || currentBatch.id !== id
|| !currentBatch.owner.accountKey || !isMobileAuthOwnerCurrent(currentBatch.owner)) return false;
const consumed = currentBatch;
+ // Do not expose a removable attachment until consumption is durable. On failure
+ // keep the mailbox entry so focusing the screen again can retry the handoff.
+ consumed.acknowledge();
pendingBatches.shift();
currentBatch = pendingBatches[0] ?? null;
emit();
- acknowledgeBatch(consumed);
return true;
}
diff --git a/apps/mobile/src/session/incomingShareCleanup.ts b/apps/mobile/src/session/incomingShareCleanup.ts
index 3632ffa812..adaf9eff29 100644
--- a/apps/mobile/src/session/incomingShareCleanup.ts
+++ b/apps/mobile/src/session/incomingShareCleanup.ts
@@ -20,6 +20,11 @@ export async function cleanupExpiredIncomingShares(now = Date.now()): Promise<vo
const created = entry.info().creationTime;
if (typeof created !== 'number' || !Number.isFinite(created) || created <= 0
|| now - created < SHARE_COPY_RETENTION_MS) continue;
+ // Remove files before any receipt directories: a failed sweep must not
+ // resurrect a consumed share whose original copy remains readable.
+ for (const child of entry.list()) {
+ if (!(child instanceof Directory)) await deleteAsync(child.uri, { idempotent: true });
+ }
await deleteAsync(entry.uri, { idempotent: true });
} catch {
// Best effort: inaccessible or concurrently removed entries retry on foreground.
diff --git a/apps/mobile/src/session/incomingShareNative.ts b/apps/mobile/src/session/incomingShareNative.ts
index 5c307139ec..6e6e282b31 100644
--- a/apps/mobile/src/session/incomingShareNative.ts
+++ b/apps/mobile/src/session/incomingShareNative.ts
@@ -1,23 +1,86 @@
import { requireOptionalNativeModule } from 'expo-modules-core';
+import { Directory } from 'expo-file-system';
import type { SharePayload } from 'expo-sharing';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
const native = requireOptionalNativeModule<{
readSnapshot(): string | null;
clearSnapshot(expected: string): boolean;
}>('CindyIncomingShare');
const snapshots = new WeakMap<SharePayload[], string>();
+const CONSUMED_DIRECTORY = '.cindy-share-consumed';
+
+type ShareCopyState = { handled: true } | { handled: false; directory?: Directory };
+
+/** Only discard a managed copy when a successful directory listing proves it is gone.
+ * File.exists alone also returns false for inaccessible files (e.g. device protection).
+ */
+function inspectShareCopy(uri: string): ShareCopyState {
+ const match = /^(file:\/\/.*)\/(cindy-share-[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})\/([^/]+)$/i.exec(uri);
+ if (!match) return { handled: false };
+ try {
+ const root = new Directory(match[1]!);
+ const directory = root.list().find((entry) => entry.name === match[2]);
+ if (!directory) return { handled: true };
+ if (!(directory instanceof Directory)) return { handled: false };
+ const entries = directory.list();
+ if (entries.some((entry) => entry instanceof Directory && entry.name === CONSUMED_DIRECTORY)) {
+ return { handled: true };
+ }
+ const decodedUri = decodeURIComponent(uri);
+ return entries.some((entry) => decodeURIComponent(entry.uri) === decodedUri)
+ ? { handled: false, directory } : { handled: true };
+ } catch {
+ // An unreadable container is not proof of deletion; preserve the share.
+ return { handled: false };
+ }
+}
export function getSharedPayloads(): SharePayload[] {
const snapshot = native?.readSnapshot();
if (!snapshot) return [];
- const payloads: SharePayload[] = JSON.parse(snapshot).map((item: { value: string; type: SharePayload['shareType']; mimeType?: string }) => ({
+ 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) => !inspectShareCopy(payload.value).handled);
snapshots.set(payloads, snapshot);
+ if (raw.length > 0 && payloads.length === 0) {
+ // Do not navigate to an empty draft, even when native acknowledgement fails.
+ // The next foreground/start checks again without retaining a JS-only tombstone.
+ try { clearSharedPayloads(payloads); } catch { /* Diagnosed by the adapter below. */ }
+ }
return payloads;
}
export function clearSharedPayloads(expected: SharePayload[]): void {
const snapshot = snapshots.get(expected);
- if (snapshot !== undefined) native?.clearSnapshot(snapshot);
+ if (snapshot === undefined) return;
+ try {
+ if (native?.clearSnapshot(snapshot)) return;
+ // False normally means a newer share replaced this one. Never clear it.
+ if (native?.readSnapshot() !== snapshot) return;
+ } catch {
+ mobileDebugLog('warn', 'files', 'Incoming share acknowledgement failed');
+ }
+ // Reuse the lifetime of the existing UUID-owned copies as the fallback receipt.
+ // mkdir is synchronous: once the composer receives a file, cancelling it cannot
+ // replay it after process death even if native-slot or file deletion failed.
+ // A new share gets new UUID directories, including when sharing the same file.
+ const pending = expected.map((payload) => inspectShareCopy(payload.value));
+ if (pending.some((state) => !state.handled && !state.directory)) {
+ throw new Error('INCOMING_SHARE_ACK_FAILED');
+ }
+ const created: Directory[] = [];
+ try {
+ for (const state of pending) {
+ if (state.handled) continue;
+ const marker = new Directory(state.directory!, CONSUMED_DIRECTORY);
+ marker.create();
+ created.push(marker);
+ }
+ } catch (error) {
+ // No composer handoff has happened. Undo only receipts created by this call.
+ for (const marker of created) { try { marker.delete(); } catch { /* Best effort. */ } }
+ throw error;
+ }
}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 6d23742893..d6a20ac745 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -139,6 +139,24 @@ pnpm --filter mobile test:smoke
- 模拟器与真机排错:
[`simulator-debugging.md`](../../apps/mobile/docs/simulator-debugging.md)。
+## iOS 入站分享的消费与取消
+
+- 分享副本使用每次分享独立的 `cindy-share-<UUID>` 目录。新建页领取前保留原生
+ 记录;领取必须先完成持久确认,之后才把附件交给上传管线。
+- 原生记录清除失败时,在该批自有副本目录创建 `.cindy-share-consumed` 空目录作为
+ 处理标记。它不包含文件名、正文或账号信息,随原副本回收,不另建全局账本。
+ 已处理或经可读目录列表确认不存在的副本不再进入信箱,文件仍存在也不重复导入;
+ 主动重新分享同一文件产生新的 UUID,不受旧标记影响。
+- 标记也无法写入时,保留待接收批次并在既有附件错误行说明失败,不能显示可移除附件后
+ 又在重启时恢复。取消、正常清理和七天过期清理都先删除文件,再删除包含标记的目录;
+ 文件删除失败时必须保留标记。目录暂不可读不能视为文件已删除。
+- 冷启动分享链接先进入首页,由信箱确认待接收内容后跳转,旧启动链接本身不能再次打开
+ 新建页。原生异常的具体原因只写无文件内容的诊断状态,不把路径或文件名写入日志。
+
+实现:`src/session/incomingShareNative.ts`、`incomingShare.ts`、`incomingShareCleanup.ts`
+与 `IncomingShareBridge.tsx`。回归:`src/__tests__/incomingShare*.test.ts` 和
+`nativeIntent.test.ts`。上述 TS 层修复不修改原生配置或模块,不需要为此改变 runtime fingerprint。
+
## 原生配置与 runtime fingerprint(冷更边界)
Mobile 用 `runtimeVersion.policy: "fingerprint"`:OTA 热更只在**指纹一致**的装机上生效,