Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): fence shared content and preserve original exports
Chrisaab48b5454a8
diff --git a/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift b/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swiftindex c7f7375596..37ddea9b1c 100644--- a/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift+++ b/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift@@ -13,7 +13,9 @@ public final class CindyIncomingShareModule: Module {Name("CindyIncomingShare")Function("readSnapshot") { () throws -> String? intry IncomingShareSlot.withDefaults(group: self.group) { defaults in- defaults.data(forKey: IncomingShareSlot.key).flatMap { String(data: $0, encoding: .utf8) }+ IncomingShareSlot.read(defaults.data(forKey: IncomingShareSlot.key)) {+ try IncomingShareSlot.clear($0, from: defaults)+ }.flatMap { String(data: $0, encoding: .utf8) }}}Function("clearSnapshot") { (expected: String) throws -> Bool in@@ -21,5 +23,13 @@ public final class CindyIncomingShareModule: Module {try IncomingShareSlot.clear(Data(expected.utf8), from: defaults)}}+ Function("discardSnapshot") { (expected: String) throws -> Bool in+ let bytes = Data(expected.utf8)+ return try IncomingShareSlot.discard(bytes) { expected in+ try IncomingShareSlot.withDefaults(group: self.group) { defaults in+ try IncomingShareSlot.clear(expected, from: defaults)+ }+ }+ }}}diff --git a/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift b/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swiftindex 6291a02e3c..c6044eec54 100644--- a/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift+++ b/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift@@ -5,6 +5,37 @@ import Darwin// the lock file: all processes must continue locking the same inode.enum IncomingShareSlot {static let key = "expo-sharing"+ static let rejectedKey = "cindy-rejected-incoming-share"++ // Main-app storage is independent of the App Group lock/synchronization that+ // may be unavailable during logout. Persist before attempting that cleanup.+ static func reject(_ expected: Data, in defaults: UserDefaults = .standard) throws {+ defaults.set(expected, forKey: rejectedKey)+ guard defaults.synchronize() else { throw POSIXError(.EIO) }+ }++ static func discard(_ expected: Data, rejections: UserDefaults = .standard,+ clear: (Data) throws -> Bool) throws -> Bool {+ try reject(expected, in: rejections)+ let cleared = try clear(expected)+ if cleared {+ rejections.removeObject(forKey: rejectedKey)+ rejections.synchronize()+ }+ return cleared+ }++ static func read(_ snapshot: Data?, rejections: UserDefaults = .standard,+ clear: (Data) throws -> Bool) -> Data? {+ guard let rejected = rejections.data(forKey: rejectedKey) else { return snapshot }+ if let snapshot, snapshot == rejected {+ // Retry clearing, but never return rejected bytes even if it still fails.+ guard (try? clear(snapshot)) == true else { return nil }+ }+ rejections.removeObject(forKey: rejectedKey)+ rejections.synchronize()+ return snapshot == rejected ? nil : snapshot+ }static func withLock<T>(at url: URL, _ operation: () throws -> T) throws -> T {let fd = open(url.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)diff --git a/apps/mobile/plugins/incoming-share-formats.swift b/apps/mobile/plugins/incoming-share-formats.swiftindex 82ea9f1434..102ae4a768 100644--- a/apps/mobile/plugins/incoming-share-formats.swift+++ b/apps/mobile/plugins/incoming-share-formats.swift@@ -11,17 +11,16 @@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 }+ if let file = await loadSharePayload(provider, identifier: UTType.fileURL.identifier) { return file }}- let formats: [(UTType, ShareType)] = [(.image, .image), (.movie, .video), (.audio, .audio), (.directory, .file)]+ let formats: [(UTType, ShareType)] = [(.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 }+ // Concrete exports win over thumbnails as well as text/link previews.+ if let file = await loadShareFile(provider, format: .data, kind: .file, excludePlainText: true, excludeImages: true) { return file }+ if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier),+ let image = await loadShareFile(provider, format: .image, kind: .image) { return image }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:))@@ -49,7 +48,7 @@}}- private func loadShareFile(_ provider: NSItemProvider, format: UTType, kind: ShareType, excludePlainText: Bool = false) async -> SharePayload? {+ private func loadShareFile(_ provider: NSItemProvider, format: UTType, kind: ShareType, excludePlainText: Bool = false, excludeImages: Bool = false) async -> SharePayload? {// These exact representations are text previews. Concrete subtypes such as// Markdown and source code also conform to plainText, but remain files.let textPreviews = [UTType.plainText, .utf8PlainText, .utf16PlainText, .utf16ExternalPlainText]@@ -58,6 +57,7 @@let type = UTType($0)return type?.conforms(to: format) == true && type?.conforms(to: .url) != true&& (!excludePlainText || (!textPreviews.contains($0) && type?.conforms(to: .propertyList) != true))+ && (!excludeImages || ($0 != UTType.data.identifier && type?.conforms(to: .image) != true))}for identifier in identifiers {// Copy inside the callback: provider-owned URLs expire when it returns.@@ -72,10 +72,25 @@}}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 {+ if let file = await loadSharePayload(provider, identifier: identifier, kind: kind) { return file }+ }+ return nil+ }++ private func loadSharePayload(_ provider: NSItemProvider, identifier: String, kind: ShareType? = nil) async -> SharePayload? {+ await withCheckedContinuation { continuation in+ provider.loadItem(forTypeIdentifier: identifier, options: nil) { value, _ in+ // URL lifetime belongs to this callback, including loadItem fallbacks.+ if let url = value as? URL {+ let image = UTType(filenameExtension: url.pathExtension)?.conforms(to: .image)+ ?? provider.hasItemConformingToTypeIdentifier(UTType.image.identifier)+ continuation.resume(returning: self.copyAndProcessFile(url: url, type: kind ?? (image ? .image : .file)))+ return+ }+ guard let kind, let data = (value as? Data) ?? (value as? UIImage)?.pngData() else {+ continuation.resume(returning: nil)+ return+ }let isRenderedImage = value is UIImagelet type = isRenderedImage ? UTType.png : UTType(identifier)let ext = type?.preferredFilenameExtension ?? "bin"@@ -83,8 +98,7 @@let name = suggested.isEmpty || suggested == "." || suggested == ".." ? UUID().uuidString : suggestedlet 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 }+ continuation.resume(returning: self.saveDataToAppGroup(data: data, fileName: filename, type: kind, mimeType: type?.preferredMIMEType))}}- return nil}diff --git a/apps/mobile/scripts/test-incoming-share-formats.mjs b/apps/mobile/scripts/test-incoming-share-formats.mjsindex 31fb5c3af6..c7d81b7b5a 100644--- a/apps/mobile/scripts/test-incoming-share-formats.mjs+++ b/apps/mobile/scripts/test-incoming-share-formats.mjs@@ -17,11 +17,22 @@ import UniformTypeIdentifierslet testRoot = URL(fileURLWithPath: CommandLine.arguments[1])let NSExtensionJavaScriptPreprocessingResultsKey = "NSExtensionJavaScriptPreprocessingResultsKey"class UIImage: NSObject { func pngData() -> Data? { nil } }+final class EphemeralProvider: NSItemProvider {+ var url: URL!+ override func loadItem(forTypeIdentifier identifier: String, options: [AnyHashable: Any]? = nil, completionHandler: NSItemProvider.CompletionHandler? = nil) {+ Thread.current.threadDictionary["owning-provider-callback"] = true+ completionHandler?(url as NSURL, nil)+ Thread.current.threadDictionary.removeObject(forKey: "owning-provider-callback")+ try? FileManager.default.removeItem(at: url)+ }+}enum ShareType { case text, url, image, video, audio, file }struct SharePayload { let type: ShareType; let value: String; let mimeType: String?; let metadata: String? }final class Adapter {+ var requireProviderCallback = falsefunc parse(_ provider: NSItemProvider) async -> SharePayload? { await parseProvider(provider) }func copyAndProcessFile(url: URL, type: ShareType) -> SharePayload? {+ precondition(!requireProviderCallback || Thread.current.threadDictionary["owning-provider-callback"] as? Bool == true, "URL escaped provider callback")guard url.isFileURL, let bytes = try? Data(contentsOf: url) else { return nil }return saveDataToAppGroup(data: bytes, fileName: url.lastPathComponent, type: type, mimeType: UTType(filenameExtension: url.pathExtension)?.preferredMIMEType)}@@ -70,6 +81,48 @@ final class Adapter {guard let payload = await adapter.parse(provider) else { fatalError("Missing text preview") }precondition(payload.type == .text && payload.value == "shared passage")}+ let selected = CommandLine.arguments[2]+ if selected != "file-url" {+ for type in [UTType.pdf, .mpeg4Movie] {+ let provider = NSItemProvider()+ let name = "original." + type.preferredFilenameExtension!+ let bytes = Data("original document or movie".utf8)+ provider.suggestedName = name+ // Advertise the thumbnail first, as real source apps may do.+ provider.registerDataRepresentation(forTypeIdentifier: UTType.image.identifier, visibility: .all) { done in+ done(Data("thumbnail".utf8), nil); return nil+ }+ provider.registerDataRepresentation(forTypeIdentifier: type.identifier, visibility: .all) { done in+ done(bytes, nil); return nil+ }+ guard let payload = await adapter.parse(provider),+ payload.type == (type.conforms(to: .movie) ? .video : .file),+ let url = URL(string: payload.value) else { fatalError("Thumbnail replaced original export") }+ precondition(url.lastPathComponent == name && payload.mimeType == type.preferredMIMEType)+ precondition(try! Data(contentsOf: url) == bytes)+ }+ let image = NSItemProvider()+ image.suggestedName = "original.png"+ image.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { done in+ done(Data("image bytes".utf8), nil); return nil+ }+ guard let payload = await adapter.parse(image) else { fatalError("Missing image") }+ precondition(payload.type == .image && payload.mimeType == UTType.png.preferredMIMEType)+ print("PASS: original documents/videos beat thumbnails; real images remain images")+ }+ if selected != "thumbnails" {+ let url = root.appendingPathComponent("ephemeral.pdf")+ let bytes = Data("ephemeral bytes".utf8)+ try! bytes.write(to: url)+ let provider = EphemeralProvider()+ provider.url = url+ provider.registerItem(forTypeIdentifier: UTType.fileURL.identifier, loadHandler: { _, _, _ in })+ adapter.requireProviderCallback = true+ guard let payload = await adapter.parse(provider), let result = URL(string: payload.value) else { fatalError("Missing ephemeral file") }+ precondition(try! Data(contentsOf: result) == bytes)+ precondition(!FileManager.default.fileExists(atPath: url.path))+ print("PASS: temporary file URL copied inside provider callback")+ }print("PASS: concrete Markdown/source files and plain text previews")}}@@ -80,8 +133,14 @@ try {const binary = join(dir, 'formats');writeFileSync(file, harness);for (const [command, args, timeout] of [- ['swiftc', ['-parse-as-library', file, '-o', binary], 120_000],- [binary, [dir], 15_000],+ ['swiftc', ['-parse-as-library', file, '-o', binary], 60_000],+ [binary, [dir, process.argv[2] ?? "all"], 15_000],+ ['swiftc', [+ join(dirname(fileURLToPath(import.meta.url)), '../modules/cindy-incoming-share/ios/IncomingShareSlot.swift'),+ join(dirname(fileURLToPath(import.meta.url)), 'test-incoming-share-slot.swift'),+ '-o', join(dir, 'slot'),+ ], 30_000],+ [join(dir, 'slot'), [], 15_000],]) {const result = spawnSync(command, args, { stdio: 'inherit', timeout, killSignal: 'SIGKILL' });if (result.error?.code === 'ENOENT' && command === 'swiftc') process.exitCode = 77;diff --git a/apps/mobile/scripts/test-incoming-share-slot.swift b/apps/mobile/scripts/test-incoming-share-slot.swiftindex bb5542f319..51e44630fa 100644--- a/apps/mobile/scripts/test-incoming-share-slot.swift+++ b/apps/mobile/scripts/test-incoming-share-slot.swift@@ -6,6 +6,12 @@ import Darwinenum IncomingShareSlotTest {static func main() throws {let arguments = CommandLine.arguments+ if arguments.count > 1 && arguments[1] == "--rejected" {+ let persisted = UserDefaults(suiteName: arguments[2])!+ precondition(persisted.synchronize())+ precondition(IncomingShareSlot.read(Data("A".utf8), rejections: persisted) { _ in throw POSIXError(.EIO) } == nil)+ return+ }if arguments.count > 1 {let lock = URL(fileURLWithPath: arguments[1])// Prove that the other process cannot enter the compare/clear window.@@ -62,6 +68,33 @@ enum IncomingShareSlotTest {// An error must release the lock as well.do { try IncomingShareSlot.withLock(at: lock) { throw POSIXError(.EIO) } } catch {}try IncomingShareSlot.withLock(at: lock) {}+ let rejectionSuite = suite + "-rejections"+ let rejections = UserDefaults(suiteName: rejectionSuite)!+ defer { rejections.removePersistentDomain(forName: rejectionSuite); rejections.synchronize() }+ do {+ _ = try IncomingShareSlot.discard(a, rejections: rejections) { _ in throw POSIXError(.EIO) }+ fatalError("Expected failed App Group cleanup")+ } catch {}+ let reader = Process()+ reader.executableURL = URL(fileURLWithPath: arguments[0])+ reader.arguments = ["--rejected", rejectionSuite]+ try reader.run()+ reader.waitUntilExit()+ precondition(reader.terminationStatus == 0)+ // A fresh instance models restart after account A's App Group clear failed.+ let restarted = UserDefaults(suiteName: rejectionSuite)!+ for _ in 0..<2 {+ precondition(IncomingShareSlot.read(a, rejections: restarted) { _ in throw POSIXError(.EIO) } == nil)+ }+ precondition(IncomingShareSlot.read(a, rejections: restarted) { _ in true } == nil)+ // Clearing succeeded: a deliberate identical share is eligible again.+ precondition(IncomingShareSlot.read(a, rejections: restarted) { _ in fatalError("Not rejected") } == a)+ try IncomingShareSlot.reject(a, in: rejections)+ precondition(IncomingShareSlot.read(b, rejections: restarted) { _ in fatalError("Never clear newer bytes") } == b)+ let discarded = try IncomingShareSlot.discard(a, rejections: rejections) { _ in true }+ precondition(discarded)+ precondition(IncomingShareSlot.read(a, rejections: restarted) { _ in fatalError("Already cleared") } == a)+ print("PASS: durable exact-snapshot rejection, retry and replacement")print("PASS: cross-process exclusion, stale/current/duplicate acknowledgement, error unlock")}}diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.tsindex 3e78a6665e..edfe7006d0 100644--- a/apps/mobile/src/__tests__/incomingShare.test.ts+++ b/apps/mobile/src/__tests__/incomingShare.test.ts@@ -272,6 +272,33 @@ describe('incoming Share Extension payloads', () => {expect(consumeIncomingShareBatch(loggedOutBatch.id)).toBe(false);});+ it.each(['text', 'url'] as const)('fences uncleared %s from the next account until retry succeeds', (shareType) => {+ let raw = [{ value: shareType === 'text' ? 'account A private text' : 'https://private.example/a', shareType }];+ const native = {+ getSharedPayloads: () => raw.map(item => ({ ...item })),+ clearSharedPayloads: vi.fn((): void => { throw new Error('App Group unavailable'); }),+ };+ const stop = watchIncomingShareAccount(native);+ setMobileAuthOwner('account-b');+ // Foreground refresh must not relabel the surviving native snapshot as B.+ receiveIncomingShare(native);+ const next = stageIncomingShareBatch([payload({ value: 'file:///new.pdf', contentUri: 'file:///new.pdf' })], vi.fn())!;+ expect(consumeIncomingShareBatch(next.id)).toBe(true);+ native.clearSharedPayloads.mockImplementation(() => { raw = []; });+ receiveIncomingShare(native);+ // Once clearing has succeeded, a deliberate identical share belongs to B.+ raw = [{ value: shareType === 'text' ? 'account A private text' : 'https://private.example/a', shareType }];+ receiveIncomingShare(native);+ const id = incomingShareBatchId([payload({+ ...(shareType === 'text'+ ? { value: raw[0]!.value, shareType, contentUri: null, contentType: 'text', originalName: raw[0]!.value }+ : { value: raw[0]!.value, shareType, contentUri: raw[0]!.value, contentType: 'website', originalName: 'a' }),+ contentSize: null, contentMimeType: null, mimeType: undefined,+ })]);+ expect(consumeIncomingShareBatch(id)).toBe(true);+ stop();+ });+it('clears an unobserved native slot on switch and allows new shares for the new account', () => {let raw = [{ value: 'file:///shared/report.pdf', shareType: 'file' as const }];const native = { getSharedPayloads: () => raw, clearSharedPayloads: vi.fn(() => { raw = []; }) };diff --git a/apps/mobile/src/__tests__/incomingShareNative.test.ts b/apps/mobile/src/__tests__/incomingShareNative.test.tsindex 8e6c85e585..11169b366d 100644--- a/apps/mobile/src/__tests__/incomingShareNative.test.ts+++ b/apps/mobile/src/__tests__/incomingShareNative.test.ts@@ -1,6 +1,6 @@import { beforeEach, expect, it, vi } from 'vitest';-const native = vi.hoisted(() => ({ readSnapshot: vi.fn(), clearSnapshot: vi.fn() }));+const native = vi.hoisted(() => ({ readSnapshot: vi.fn(), clearSnapshot: vi.fn(), discardSnapshot: vi.fn() }));const fs = vi.hoisted(() => {const listings = new Map<string, Array<{ uri: string; name: string }> | Error>();class Directory {@@ -20,10 +20,13 @@ const fs = vi.hoisted(() => {});vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => native }));vi.mock('expo-file-system', () => ({ Directory: fs.Directory }));-import { getSharedPayloads, clearSharedPayloads } from '@/session/incomingShareNative';+import { getSharedPayloads, clearSharedPayloads, discardSharedPayloads } from '@/session/incomingShareNative';beforeEach(() => {vi.resetAllMocks();+ native.readSnapshot.mockReturnValue(null);+ getSharedPayloads();+ native.readSnapshot.mockReset();fs.listings.clear();native.clearSnapshot.mockReturnValue(true);});@@ -164,3 +167,34 @@ it('preserves literal file-URL text without consulting or deleting the filesysteexpect(getSharedPayloads()).toEqual([{ shareType: 'text', value: uri, mimeType: undefined }]);expect(native.clearSnapshot).not.toHaveBeenCalled();});++// Only account-boundary discards tombstone; normal failed consumption stays retryable.+it('discards the exact captured snapshot through the durable rejection API', () => {+ const snapshot = '[ { "type":"text", "value":"account A private text" } ]';+ native.readSnapshot.mockReturnValue(snapshot);+ const raw = getSharedPayloads();+ native.discardSnapshot.mockImplementation(() => { throw new Error('App Group locked'); });+ expect(() => discardSharedPayloads(raw)).toThrow('App Group locked');+ expect(native.discardSnapshot).toHaveBeenCalledExactlyOnceWith(snapshot);+ expect(native.clearSnapshot).not.toHaveBeenCalled();+});++it('fences old text before filtering files that account cleanup deleted', () => {+ fs.listings.set(root, [directory]);+ fs.listings.set(directory.uri, [{ uri, name: 'report.pdf' }]);+ const mixed = JSON.stringify([{ type: 'file', value: uri }, { type: 'text', value: 'private A text' }]);+ native.readSnapshot.mockReturnValue(mixed);+ const raw = getSharedPayloads();+ native.discardSnapshot.mockImplementation(() => { throw new Error('storage unavailable'); });+ expect(() => discardSharedPayloads(raw)).toThrow();+ fs.listings.set(root, []);+ native.clearSnapshot.mockReturnValue(false);+ expect(getSharedPayloads()).toEqual([]);+ expect(getSharedPayloads()).toEqual([]);+ native.clearSnapshot.mockReturnValue(true);+ expect(getSharedPayloads()).toEqual([]);+ native.readSnapshot.mockReturnValue(null);+ expect(getSharedPayloads()).toEqual([]);+ native.readSnapshot.mockReturnValue('[{"type":"text","value":"private A text"}]');+ expect(getSharedPayloads()).toEqual([{ shareType: 'text', value: 'private A text', mimeType: undefined }]);+});diff --git a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.tsindex 5ee7e03f12..bd9beac819 100644--- a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts+++ b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts@@ -144,7 +144,7 @@ describe("incoming share native file ownership", () => {});});-it("preserves concrete text exports ahead of their plain-text previews", ({ skip }) => {+it("preserves original exports ahead of previews and copies temporary URLs within callbacks", ({ skip }) => {const script = join(dirname(fileURLToPath(import.meta.url)), "../../scripts/test-incoming-share-formats.mjs");const result = spawnSync(process.execPath, [script], {encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], timeout: 150_000, killSignal: "SIGKILL",@@ -153,4 +153,7 @@ it("preserves concrete text exports ahead of their plain-text previews", ({ skipif (result.status === 77) return skip();expect(result.status).toBe(0);expect(result.stdout).toContain("PASS: concrete Markdown/source files and plain text previews");+ expect(result.stdout).toContain("PASS: original documents/videos beat thumbnails; real images remain images");+ expect(result.stdout).toContain("PASS: temporary file URL copied inside provider callback");+ expect(result.stdout).toContain("PASS: durable exact-snapshot rejection, retry and replacement");}, 180_000);diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.tsindex 763882993f..4a738bc849 100644--- a/apps/mobile/src/session/incomingShare.ts+++ b/apps/mobile/src/session/incomingShare.ts@@ -40,6 +40,7 @@ let currentBatch: IncomingShareBatch | null = null;const pendingBatches: IncomingShareBatch[] = [];const listeners = new Set<() => void>();let unsubscribeOwner: (() => void) | undefined;+let rejectedNativeSnapshots = new WeakMap<IncomingShareNative, string | null>();function isFilePayload(payload: Pick<SharePayload, 'shareType'>): boolean {return payload.shareType !== 'text' && payload.shareType !== 'url';@@ -120,8 +121,14 @@ function updateIncomingShareOwner(type IncomingShareNative = {getSharedPayloads(): SharePayload[];clearSharedPayloads(expected: SharePayload[]): void;+ discardSharedPayloads?(expected: SharePayload[]): void;};+function discardNativeShare(native: IncomingShareNative, raw: SharePayload[]): void {+ if (native.discardSharedPayloads) native.discardSharedPayloads(raw);+ else native.clearSharedPayloads(raw);+}+/** Also clear a native payload not yet observed by the JS mailbox on logout/switch. */export function watchIncomingShareAccount(native: IncomingShareNative,@@ -129,11 +136,17 @@ export function watchIncomingShareAccount(): () => void {return observeIncomingShareOwner((previous, current, restored) => {if (!canRetainShareOwner(previous, current, restored)) {+ let raw: SharePayload[] | undefined;try {- const raw = native.getSharedPayloads();- native.clearSharedPayloads(raw);+ raw = native.getSharedPayloads();+ discardNativeShare(native, raw);+ rejectedNativeSnapshots.delete(native);void deleteIncomingSharedFiles(raw.filter(isFilePayload).map((payload) => payload.value)).catch(() => undefined);- } catch { /* Sharing is unavailable in older native binaries. */ }+ } catch {+ // Also fence older binaries, or a failure to persist the native tombstone.+ // null means the slot was unreadable: its first readable batch must clear.+ rejectedNativeSnapshots.set(native, raw ? JSON.stringify(raw) : null);+ }}}, previous);}@@ -237,6 +250,16 @@ export function leaveIncomingShareChooser(cancelBatchId: string | null, leave: (export function receiveIncomingShare(native: IncomingShareNative): void {if (getMobileAuthOwner().switching) return;const raw = native.getSharedPayloads();+ if (rejectedNativeSnapshots.has(native)) {+ const rejected = rejectedNativeSnapshots.get(native);+ if (rejected === null || rejected === JSON.stringify(raw)) {+ try { discardNativeShare(native, raw); } catch { return; }+ rejectedNativeSnapshots.delete(native);+ return;+ }+ // A different snapshot (or a durably empty slot) cannot expose old content.+ rejectedNativeSnapshots.delete(native);+ }if (raw.length === 0) return;const payloads = raw.map((payload): ResolvedSharePayload => {const common = { ...payload, contentMimeType: payload.mimeType ?? null,@@ -347,4 +370,5 @@ export function __resetIncomingShareForTest(): void {currentBatch = null;pendingBatches.length = 0;listeners.clear();+ rejectedNativeSnapshots = new WeakMap();}diff --git a/apps/mobile/src/session/incomingShareNative.ts b/apps/mobile/src/session/incomingShareNative.tsindex 298b0ddee3..8c4ef806b4 100644--- a/apps/mobile/src/session/incomingShareNative.ts+++ b/apps/mobile/src/session/incomingShareNative.ts@@ -6,8 +6,24 @@ import { mobileDebugLog } from '@/debug/mobileDebugLog';const native = requireOptionalNativeModule<{readSnapshot(): string | null;clearSnapshot(expected: string): boolean;+ discardSnapshot?(expected: string): boolean;}>('CindyIncomingShare');const snapshots = new WeakMap<SharePayload[], string>();+let rejectedSnapshot: string | null = null;++/** Account-boundary discard persists an exact tombstone before App Group I/O. */+export function discardSharedPayloads(expected: SharePayload[]): void {+ const snapshot = snapshots.get(expected);+ if (snapshot === undefined) return;+ rejectedSnapshot = snapshot;+ if (native?.discardSnapshot) {+ native.discardSnapshot(snapshot);+ rejectedSnapshot = null;+ return;+ }+ clearSharedPayloads(expected);+ rejectedSnapshot = null;+}/** 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).@@ -31,7 +47,13 @@ function isMissingShareCopy(uri: string): boolean {export function getSharedPayloads(): SharePayload[] {const snapshot = native?.readSnapshot();- if (!snapshot) return [];+ if (!snapshot) { rejectedSnapshot = null; return []; }+ if (snapshot === rejectedSnapshot) {+ // Fence before filtering deleted files: surviving text is still old content.+ try { if (native?.clearSnapshot(snapshot)) rejectedSnapshot = null; } catch { /* Retry on refresh. */ }+ return [];+ }+ rejectedSnapshot = null;const raw: SharePayload[] = JSON.parse(snapshot).map((item: { value: string; type: SharePayload['shareType']; mimeType?: string }) => ({value: item.value, shareType: item.type, mimeType: item.mimeType,}));