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): persist unreadable share fences and retain image exports

Chris993df6e57672
diff --git a/apps/mobile/docs/incoming-sharing.md b/apps/mobile/docs/incoming-sharing.md
index 0a367a9d98..f8449de65c 100644
--- a/apps/mobile/docs/incoming-sharing.md
+++ b/apps/mobile/docs/incoming-sharing.md
@@ -60,13 +60,16 @@ new sending privileges: normal conversation hydration and authorization still ap
duplicated in the task section.
Provider temporary URLs are copied **inside** the `loadFileRepresentation` or
-`loadItem` callback. Web URLs precede image previews but follow concrete file exports.
+`loadItem` callback. Concrete image subtypes (PNG/JPEG/HEIC etc.) precede source
+URLs; web URLs precede abstract `public.image` previews but follow concrete file exports.
Security-scoped access is balanced; directories use `NSFileCoordinator.forUploading`.
Each input owns a unique App Group directory, so equal filenames cannot overwrite.
The native slot is acknowledged only by the selected, focused, hydrated composer;
account changes and upload cleanup use the existing ownership fences. Rejection-marker
removal is acknowledged only after a successful durable flush; failures retain the
-marker for retry, including when the App Group slot has already been cleared. The existing
+marker for retry, including when the App Group slot has already been cleared. If an
+account transition cannot read the slot, an independent durable unknown-slot fence
+rejects its first recovered snapshot, then pins those exact bytes for cleanup retries. The existing
native inbox is a single persistent slot, with an in-process JS queue; this change does
not promise a durable history of multiple shares received before Cindy opens.
diff --git a/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift b/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift
index 37ddea9b1c..eecbbba02d 100644
--- a/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift
+++ b/apps/mobile/modules/cindy-incoming-share/ios/CindyIncomingShareModule.swift
@@ -23,6 +23,10 @@ public final class CindyIncomingShareModule: Module {
try IncomingShareSlot.clear(Data(expected.utf8), from: defaults)
}
}
+ Function("rejectUnreadableSnapshot") { () throws -> Void in
+ // Deliberately independent of self.group / App Group locks and I/O.
+ try IncomingShareSlot.rejectUnreadable()
+ }
Function("discardSnapshot") { (expected: String) throws -> Bool in
let bytes = Data(expected.utf8)
return try IncomingShareSlot.discard(bytes) { expected in
diff --git a/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift b/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift
index e9aa4041a0..679a389372 100644
--- a/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift
+++ b/apps/mobile/modules/cindy-incoming-share/ios/IncomingShareSlot.swift
@@ -14,6 +14,12 @@ enum IncomingShareSlot {
guard defaults.synchronize() else { throw POSIXError(.EIO) }
}
+ // An empty marker cannot be a JSON payload. It rejects the first readable
+ // slot after an account transition whose App Group read failed, across restart.
+ static func rejectUnreadable(in defaults: UserDefaults = .standard) throws {
+ try reject(Data(), in: defaults)
+ }
+
static func discard(_ expected: Data, rejections: UserDefaults = .standard,
clear: (Data) throws -> Bool) throws -> Bool {
try reject(expected, in: rejections)
@@ -26,7 +32,13 @@ enum IncomingShareSlot {
static func read(_ snapshot: Data?, rejections: UserDefaults = .standard,
clear: (Data) throws -> Bool) -> Data? {
- guard let rejected = rejections.data(forKey: rejectedKey) else { return snapshot }
+ guard var rejected = rejections.data(forKey: rejectedKey) else { return snapshot }
+ if rejected.isEmpty, let snapshot {
+ // Pin the recovered bytes before cleanup. Later, different shares remain
+ // eligible even if clearing this old slot fails again.
+ do { try reject(snapshot, in: rejections) } catch { return nil }
+ rejected = snapshot
+ }
if let snapshot, snapshot == rejected {
// Retry clearing, but never return rejected bytes even if it still fails.
do { _ = try clear(snapshot) } catch { return nil }
diff --git a/apps/mobile/plugins/incoming-share-formats.swift b/apps/mobile/plugins/incoming-share-formats.swift
index a2876d6abd..76f57931fa 100644
--- a/apps/mobile/plugins/incoming-share-formats.swift
+++ b/apps/mobile/plugins/incoming-share-formats.swift
@@ -20,6 +20,9 @@
// Concrete exports (including ordinary property lists) win over previews.
// Only the positively identified Safari envelope above is composer text.
if let file = await loadShareFile(provider, format: .data, kind: .file, excludePlainText: true, excludeImages: true) { return file }
+ // Concrete image files are primary exports; only abstract public.image
+ // remains behind a source URL, where it commonly represents a thumbnail.
+ if let image = await loadShareFile(provider, format: .image, kind: .image, includeAbstract: false) { return image }
// Web links may also advertise a thumbnail; retain the actionable URL.
if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier),
let value = await loadShareItem(provider, identifier: UTType.url.identifier) {
@@ -51,7 +54,7 @@
}
}
- private func loadShareFile(_ provider: NSItemProvider, format: UTType, kind: ShareType, excludePlainText: Bool = false, excludeImages: Bool = false) async -> SharePayload? {
+ private func loadShareFile(_ provider: NSItemProvider, format: UTType, kind: ShareType, excludePlainText: Bool = false, excludeImages: Bool = false, includeAbstract: Bool = true) 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]
@@ -59,6 +62,7 @@
let identifiers = provider.registeredTypeIdentifiers.filter {
let type = UTType($0)
return type?.conforms(to: format) == true && type?.conforms(to: .url) != true
+ && (includeAbstract || $0 != format.identifier)
&& (!excludePlainText || !textPreviews.contains($0))
&& (!excludeImages || ($0 != UTType.data.identifier && type?.conforms(to: .image) != true))
}
diff --git a/apps/mobile/scripts/test-incoming-share-formats.mjs b/apps/mobile/scripts/test-incoming-share-formats.mjs
index 18bc4e37bc..b4894b6fa7 100644
--- a/apps/mobile/scripts/test-incoming-share-formats.mjs
+++ b/apps/mobile/scripts/test-incoming-share-formats.mjs
@@ -104,6 +104,22 @@ final class Adapter {
guard let page = await adapter.parse(safari) else { fatalError("Missing Safari page") }
precondition(page.type == .text && page.value == "Page title\\n\\nhttps://example.com/page\\n\\nSelected text")
print("PASS: concrete property lists beat previews; Safari preprocessing remains text")
+ // A concrete image export is the primary content even with a source URL.
+ for type in [UTType.png, .jpeg, .heic] {
+ let provider = NSItemProvider()
+ let name = "original." + type.preferredFilenameExtension!
+ let bytes = Data("original image export".utf8)
+ provider.suggestedName = name
+ provider.registerItem(forTypeIdentifier: UTType.url.identifier, loadHandler: { done, _, _ in
+ done?(NSURL(string: "https://example.com/image-source")!, nil)
+ })
+ provider.registerDataRepresentation(forTypeIdentifier: type.identifier, visibility: .all) { done in done(bytes, nil); return nil }
+ guard let payload = await adapter.parse(provider), payload.type == .image,
+ let result = URL(string: payload.value) else { fatalError("Source URL replaced concrete image: " + type.identifier) }
+ precondition(result.lastPathComponent == name && payload.mimeType == type.preferredMIMEType)
+ precondition(try! Data(contentsOf: result) == bytes)
+ }
+ print("PASS: concrete images beat source URLs; abstract thumbnails remain previews")
let selected = CommandLine.arguments[2]
let link = NSItemProvider()
let sharedURL = URL(string: "https://example.com/shared-page?source=provider")!
diff --git a/apps/mobile/scripts/test-incoming-share-slot.swift b/apps/mobile/scripts/test-incoming-share-slot.swift
index 36d57c627d..7136e70535 100644
--- a/apps/mobile/scripts/test-incoming-share-slot.swift
+++ b/apps/mobile/scripts/test-incoming-share-slot.swift
@@ -23,10 +23,11 @@ final class RejectionDefaults: UserDefaults {
enum IncomingShareSlotTest {
static func main() throws {
let arguments = CommandLine.arguments
- if arguments.count > 1 && arguments[1] == "--rejected" {
+ if arguments.count > 1 && ["--rejected", "--unknown"].contains(arguments[1]) {
let persisted = UserDefaults(suiteName: arguments[2])!
precondition(persisted.synchronize())
precondition(IncomingShareSlot.read(Data("A".utf8), rejections: persisted) { _ in throw POSIXError(.EIO) } == nil)
+ precondition(persisted.data(forKey: IncomingShareSlot.rejectedKey) == Data("A".utf8))
return
}
if arguments.count > 1 {
@@ -151,6 +152,28 @@ enum IncomingShareSlotTest {
newer.failRemoval = false
precondition(IncomingShareSlot.read(b, rejections: newer) { _ in fatalError("Never clear newer bytes") } == b)
precondition(newer.durable == nil)
+ // Read failure cannot capture exact bytes: persist unknown before App Group
+ // recovery, then verify a new process rejects and pins the recovered bytes.
+ try IncomingShareSlot.rejectUnreadable(in: rejections)
+ let unknownReader = Process()
+ unknownReader.executableURL = URL(fileURLWithPath: arguments[0])
+ unknownReader.arguments = ["--unknown", rejectionSuite]
+ try unknownReader.run()
+ unknownReader.waitUntilExit()
+ precondition(unknownReader.terminationStatus == 0)
+ precondition(rejections.synchronize())
+ precondition(IncomingShareSlot.read(a, rejections: rejections) { _ in throw POSIXError(.EIO) } == nil)
+ precondition(IncomingShareSlot.read(b, rejections: rejections) { _ in fatalError("New bytes remain eligible") } == b)
+ try IncomingShareSlot.rejectUnreadable(in: rejections)
+ precondition(IncomingShareSlot.read(a, rejections: rejections) { _ in true } == nil)
+ precondition(IncomingShareSlot.read(a, rejections: rejections) { _ in fatalError("New identical share after recovery") } == a)
+ let unknownEmpty = RejectionDefaults(Data())
+ precondition(IncomingShareSlot.read(nil, rejections: unknownEmpty) { _ in fatalError("Empty slot") } == nil)
+ precondition(unknownEmpty.cached == Data() && unknownEmpty.durable == Data())
+ unknownEmpty.failRemoval = false
+ precondition(IncomingShareSlot.read(nil, rejections: unknownEmpty) { _ in fatalError("Empty slot") } == nil)
+ precondition(unknownEmpty.durable == nil)
+ print("PASS: unreadable account-boundary fence survives process restart and recovery")
print("PASS: failed rejection removal retains retry state until durable recovery")
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.ts
index edfe7006d0..61196397f5 100644
--- a/apps/mobile/src/__tests__/incomingShare.test.ts
+++ b/apps/mobile/src/__tests__/incomingShare.test.ts
@@ -299,6 +299,19 @@ describe('incoming Share Extension payloads', () => {
stop();
});
+ it('persists an unknown-slot fence when the account transition cannot read native storage', () => {
+ const native = {
+ getSharedPayloads: vi.fn(() => { throw new Error('App Group unavailable'); }),
+ clearSharedPayloads: vi.fn(),
+ rejectUnreadableSharedPayloads: vi.fn(),
+ };
+ const stop = watchIncomingShareAccount(native);
+ setMobileAuthOwner('account-b');
+ expect(native.rejectUnreadableSharedPayloads).toHaveBeenCalledOnce();
+ expect(native.clearSharedPayloads).not.toHaveBeenCalled();
+ 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.ts
index 11169b366d..7ccdec89c5 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(), discardSnapshot: vi.fn() }));
+const native = vi.hoisted(() => ({ readSnapshot: vi.fn(), clearSnapshot: vi.fn(), discardSnapshot: vi.fn(), rejectUnreadableSnapshot: vi.fn() }));
const fs = vi.hoisted(() => {
const listings = new Map<string, Array<{ uri: string; name: string }> | Error>();
class Directory {
@@ -20,7 +20,7 @@ const fs = vi.hoisted(() => {
});
vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => native }));
vi.mock('expo-file-system', () => ({ Directory: fs.Directory }));
-import { getSharedPayloads, clearSharedPayloads, discardSharedPayloads } from '@/session/incomingShareNative';
+import { getSharedPayloads, clearSharedPayloads, discardSharedPayloads, rejectUnreadableSharedPayloads } from '@/session/incomingShareNative';
beforeEach(() => {
vi.resetAllMocks();
@@ -198,3 +198,13 @@ it('fences old text before filtering files that account cleanup deleted', () =>
native.readSnapshot.mockReturnValue('[{"type":"text","value":"private A text"}]');
expect(getSharedPayloads()).toEqual([{ shareType: 'text', value: 'private A text', mimeType: undefined }]);
});
+
+// The boundary must be persisted without a second read of the unavailable slot.
+it('persists unknown snapshot rejection without App Group reads', () => {
+ native.readSnapshot.mockImplementation(() => { throw new Error('App Group I/O'); });
+ rejectUnreadableSharedPayloads();
+ expect(native.rejectUnreadableSnapshot).toHaveBeenCalledOnce();
+ expect(native.readSnapshot).not.toHaveBeenCalled();
+ native.rejectUnreadableSnapshot.mockImplementation(() => { throw new Error('rejection flush failed'); });
+ expect(() => rejectUnreadableSharedPayloads()).toThrow('rejection flush failed');
+});
diff --git a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
index aa5df0ac2a..28bc5c4c27 100644
--- a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
@@ -156,6 +156,8 @@ it("preserves original exports ahead of previews and copies temporary URLs withi
expect(result.stdout).toContain("PASS: original documents/videos beat thumbnails; real images remain images");
expect(result.stdout).toContain("PASS: web URL survives its image thumbnail");
expect(result.stdout).toContain("PASS: concrete property lists beat previews; Safari preprocessing remains text");
+ expect(result.stdout).toContain("PASS: concrete images beat source URLs; abstract thumbnails remain previews");
+ expect(result.stdout).toContain("PASS: unreadable account-boundary fence survives process restart and recovery");
expect(result.stdout).toContain("PASS: failed rejection removal retains retry state until durable recovery");
expect(result.stdout).toContain("PASS: temporary file URL copied inside provider callback");
expect(result.stdout).toContain("PASS: durable exact-snapshot rejection, retry and replacement");
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index 4a738bc849..3d3d20f9a3 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -122,6 +122,7 @@ type IncomingShareNative = {
getSharedPayloads(): SharePayload[];
clearSharedPayloads(expected: SharePayload[]): void;
discardSharedPayloads?(expected: SharePayload[]): void;
+ rejectUnreadableSharedPayloads?(): void;
};
function discardNativeShare(native: IncomingShareNative, raw: SharePayload[]): void {
@@ -146,6 +147,11 @@ export function watchIncomingShareAccount(
// 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);
+ if (raw === undefined) {
+ // Persist without touching the unavailable App Group. A fresh process
+ // must reject its first readable slot before the new owner can see it.
+ try { native.rejectUnreadableSharedPayloads?.(); } catch { /* Keep the in-process fence too. */ }
+ }
}
}
}, previous);
diff --git a/apps/mobile/src/session/incomingShareNative.ts b/apps/mobile/src/session/incomingShareNative.ts
index 8c4ef806b4..81f2d229d8 100644
--- a/apps/mobile/src/session/incomingShareNative.ts
+++ b/apps/mobile/src/session/incomingShareNative.ts
@@ -7,6 +7,7 @@ const native = requireOptionalNativeModule<{
readSnapshot(): string | null;
clearSnapshot(expected: string): boolean;
discardSnapshot?(expected: string): boolean;
+ rejectUnreadableSnapshot?(): void;
}>('CindyIncomingShare');
const snapshots = new WeakMap<SharePayload[], string>();
let rejectedSnapshot: string | null = null;
@@ -25,6 +26,11 @@ export function discardSharedPayloads(expected: SharePayload[]): void {
rejectedSnapshot = null;
}
+/** Account changed while the App Group was unreadable: fence its next snapshot. */
+export function rejectUnreadableSharedPayloads(): void {
+ native?.rejectUnreadableSnapshot?.();
+}
+
/** 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).
*/