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): 移除分享确认的逐文件标记与部分回滚

Dash53c45c9218fa
diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.ts
index a81b854d28..28bc7f494d 100644
--- a/apps/mobile/src/__tests__/incomingShare.test.ts
+++ b/apps/mobile/src/__tests__/incomingShare.test.ts
@@ -5,7 +5,6 @@ import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch, isMobileAuthOwn
import {
__resetIncomingShareForTest,
consumeIncomingShareBatch,
- deleteIncomingSharedFiles,
incomingShareBatchId,
selectIncomingShareUploadCandidates,
stageIncomingShareBatch,
@@ -203,17 +202,6 @@ describe('incoming Share Extension payloads', () => {
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 b517e07c6d..67b80e3f3f 100644
--- a/apps/mobile/src/__tests__/incomingShareCleanup.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareCleanup.test.ts
@@ -4,12 +4,10 @@ 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() };
});
@@ -60,17 +58,4 @@ 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 4a6b55f640..a031ee4231 100644
--- a/apps/mobile/src/__tests__/incomingShareNative.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareNative.test.ts
@@ -3,7 +3,6 @@ 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) {
@@ -15,21 +14,9 @@ const fs = vi.hoisted(() => {
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 };
+ return { Directory, listings };
});
vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => native }));
vi.mock('expo-file-system', () => ({ Directory: fs.Directory }));
@@ -38,7 +25,6 @@ import { getSharedPayloads, clearSharedPayloads } from '@/session/incomingShareN
beforeEach(() => {
vi.resetAllMocks();
fs.listings.clear();
- fs.failCreate.clear();
native.clearSnapshot.mockReturnValue(true);
});
@@ -141,53 +127,32 @@ it('leaves unmanaged paths and remote URLs to the existing share handling', () =
expect(native.clearSnapshot).not.toHaveBeenCalled();
});
-it.each(['throw', 'false'])('does not replay existing files after native acknowledgement returns %s', async (failure) => {
+it.each(['throw', 'false'])('preserves all mixed payloads after acknowledgement returns %s', async (failure) => {
fs.listings.set(root, [directory]);
- fs.listings.set(directory.uri, [{ uri, name: 'report.pdf' }]);
- native.readSnapshot.mockReturnValue(snapshot);
+ const entries = [{ uri, name: 'report.pdf' }, { uri: `${directory.uri}/second.pdf`, name: 'second.pdf' }];
+ fs.listings.set(directory.uri, entries);
+ let slot: string | null = JSON.stringify([
+ ...entries.map((entry) => ({ type: 'file', value: entry.uri })),
+ { type: 'url', value: 'https://example.com' },
+ { type: 'file', value: 'file:///unmanaged/report.pdf' },
+ ]);
+ native.readSnapshot.mockImplementation(() => slot);
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.
+ const payloads = getSharedPayloads();
+ expect(() => clearSharedPayloads(payloads)).toThrow('INCOMING_SHARE_ACK_FAILED');
+ expect(directory.list()).toEqual(entries);
vi.resetModules();
const restarted = await import('@/session/incomingShareNative');
+ expect(restarted.getSharedPayloads()).toEqual(payloads);
+ native.clearSnapshot.mockImplementation(() => { slot = null; return true; });
+ restarted.clearSharedPayloads(restarted.getSharedPayloads());
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' }]);
+ // File cleanup may fail, but acknowledged files cannot replay from the slot.
+ expect(directory.list()).toEqual(entries);
+ // A new explicit share of the same file remains receivable.
+ slot = snapshot;
+ expect(restarted.getSharedPayloads()).toHaveLength(1);
});
diff --git a/apps/mobile/src/session/IncomingShareBridge.tsx b/apps/mobile/src/session/IncomingShareBridge.tsx
index 85b93ff06c..3491a5adba 100644
--- a/apps/mobile/src/session/IncomingShareBridge.tsx
+++ b/apps/mobile/src/session/IncomingShareBridge.tsx
@@ -37,7 +37,7 @@ export function IncomingShareBridge() {
if (!active) return;
// Sweep before staging, so an expired native copy cannot start a new
// upload concurrently with deletion. The native adapter filters missing
- // and already-consumed copies before they can trigger navigation.
+ // copies before they can trigger navigation.
try {
receiveIncomingShare(sharing);
} catch {
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index b8a57b9a74..799c1cdafe 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -42,14 +42,13 @@ 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(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. */ }
- }));
+ 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)
+ )));
}
function acknowledgeBatch(batch: IncomingShareBatch): void {
diff --git a/apps/mobile/src/session/incomingShareCleanup.ts b/apps/mobile/src/session/incomingShareCleanup.ts
index adaf9eff29..3632ffa812 100644
--- a/apps/mobile/src/session/incomingShareCleanup.ts
+++ b/apps/mobile/src/session/incomingShareCleanup.ts
@@ -20,11 +20,6 @@ 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 6e6e282b31..0a2f845d80 100644
--- a/apps/mobile/src/session/incomingShareNative.ts
+++ b/apps/mobile/src/session/incomingShareNative.ts
@@ -8,31 +8,24 @@ const native = requireOptionalNativeModule<{
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 {
+function isMissingShareCopy(uri: string): boolean {
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 };
+ if (!match) return 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 };
+ if (!directory) return true;
+ if (!(directory instanceof Directory)) return 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 };
+ return !entries.some((entry) => decodeURIComponent(entry.uri) === decodedUri);
} catch {
// An unreadable container is not proof of deletion; preserve the share.
- return { handled: false };
+ return false;
}
}
@@ -42,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) => !inspectShareCopy(payload.value).handled);
+ const payloads = raw.filter((payload) => !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.
@@ -62,25 +55,7 @@ export function clearSharedPayloads(expected: SharePayload[]): void {
} 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;
- }
+ // Never hand off an unacknowledged batch or mutate individual copies: a partial
+ // filesystem fallback could hide unclaimed files after a failed rollback.
+ throw new Error('INCOMING_SHARE_ACK_FAILED');
}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index d6a20ac745..6046ccbb68 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -143,13 +143,11 @@ pnpm --filter mobile test:smoke
- 分享副本使用每次分享独立的 `cindy-share-<UUID>` 目录。新建页领取前保留原生
记录;领取必须先完成持久确认,之后才把附件交给上传管线。
-- 原生记录清除失败时,在该批自有副本目录创建 `.cindy-share-consumed` 空目录作为
- 处理标记。它不包含文件名、正文或账号信息,随原副本回收,不另建全局账本。
- 已处理或经可读目录列表确认不存在的副本不再进入信箱,文件仍存在也不重复导入;
- 主动重新分享同一文件产生新的 UUID,不受旧标记影响。
-- 标记也无法写入时,保留待接收批次并在既有附件错误行说明失败,不能显示可移除附件后
- 又在重启时恢复。取消、正常清理和七天过期清理都先删除文件,再删除包含标记的目录;
- 文件删除失败时必须保留标记。目录暂不可读不能视为文件已删除。
+- 原生记录清除失败时保留待接收批次,在既有附件错误行说明失败,重新进入页面可重试。
+ 不写每文件处理标记,不尝试部分领取,避免回滚失败隐藏尚未领取的附件。
+ 已领取附件的原生记录已清除,因此用户移除附件后,即使副本清理失败也不会重放。
+- 仅经可读目录列表确认不存在的副本才过滤;目录暂不可读不能视为文件已删除。
+ 主动重新分享同一文件仍可领取。临时副本沿用原有取消及七天过期回收流程。
- 冷启动分享链接先进入首页,由信箱确认待接收内容后跳转,旧启动链接本身不能再次打开
新建页。原生异常的具体原因只写无文件内容的诊断状态,不把路径或文件名写入日志。