Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): preserve inline images and clean cancelled writes
DavidShend69df29567d1
diff --git a/apps/mobile/src/__tests__/useConversationShareImages.test.ts b/apps/mobile/src/__tests__/useConversationShareImages.test.tsindex d51abcca55..ffc80047d2 100644--- a/apps/mobile/src/__tests__/useConversationShareImages.test.ts+++ b/apps/mobile/src/__tests__/useConversationShareImages.test.ts@@ -106,7 +106,7 @@ afterEach(async () => {thumbs.entries.clear();thumbs.reads.mockClear();thumbs.writes.mockReset();- thumbs.deletes.mockClear();+ thumbs.deletes.mockReset();vi.mocked(withDownloadedRemoteMediaFile).mockReset();root = createRoot(container);});@@ -142,6 +142,78 @@ describe("share image readiness", () => {expect(thumbs.reads).not.toHaveBeenCalled();});+ it.each([+ "data:image/png;charset=utf-8;base64,aGVsbG8=",+ "data:image/png;charset=utf-8;name=photo;BASE64,aGVsbG8%3D",+ ])("preserves MIME parameters and escaped Base64 in %s", async (uri) => {+ const resolve = vi.fn<ResolveRemoteMediaFn>(async () => ({ ...media, url: uri }));+ await act(async () => root.render(createElement(Probe, { messages: [source], resolve })));+ await startShare();+ expect((await ready)[0]?.images?.get("cindy-media://paste")).toEqual({+ uri, width: 40, height: 20,+ });+ const tempUri = vi.mocked(Image.getSize).mock.calls[0]![0];+ expect(tempUri).toMatch(/^file:\/\/\/app\/cache\/conversation-share-images\/image-.*\.png$/);+ expect(thumbs.writes).toHaveBeenCalledWith(tempUri, "aGVsbG8=", { encoding: "base64" });+ expect(thumbs.deletes).toHaveBeenCalledExactlyOnceWith(tempUri);+ });++ it.each([true, false])("preserves non-Base64 data images when native sizing supports them: %s", async (supported) => {+ const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBvkAAAAASUVORK5CYII=";+ const encoded = Array.from(atob(png), (byte) => `%${byte.charCodeAt(0).toString(16).padStart(2, "0")}`).join("");+ const uri = `data:image/png,${encoded}`;+ if (supported) vi.mocked(Image.getSize).mockImplementationOnce(async () => ({ width: 1, height: 1 }));+ const message = { ...source, attachments: [{ kind: "image" as const, name: "pixel", uri }] };+ const resolve = vi.fn<ResolveRemoteMediaFn>();+ await act(async () => root.render(createElement(Probe, { messages: [message], resolve })));+ await startShare();+ expect((await ready)[0]?.images?.get(uri)).toEqual(supported ? { uri, width: 1, height: 1 } : undefined);+ expect(Image.getSize).toHaveBeenCalledWith(uri);+ expect(thumbs.writes).not.toHaveBeenCalled();+ expect(thumbs.deletes).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it.each([+ ["cancel", "resolve"], ["cancel", "reject"],+ ["timeout", "resolve"], ["timeout", "reject"],+ ])("cleans a pending write on %s and again after its late %s", async (event, outcome) => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const files = new Set<string>();+ let finish!: () => void;+ let tempUri!: string;+ thumbs.deletes.mockImplementation((uri: string) => { files.delete(uri); });+ thumbs.writes.mockImplementationOnce((...args: unknown[]) => {+ tempUri = args[0] as string;+ files.add(tempUri);+ return new Promise<undefined>((resolve, reject) => {+ finish = () => {+ // The native writer can create or finish a partial file after cancellation.+ files.add(tempUri);+ if (outcome === "resolve") resolve(undefined);+ else reject(new Error("late write failed"));+ };+ });+ });+ const resolve = vi.fn<ResolveRemoteMediaFn>(async () => media);+ await act(async () => root.render(createElement(Probe, { messages: [source], resolve })));+ await startShare();+ expect(files.has(tempUri)).toBe(true);+ await act(async () => {+ if (event === "cancel") current.cancel();+ else await vi.advanceTimersByTimeAsync(20_000);+ });+ const result = await ready;+ expect(event === "cancel" ? result.length : result[0]?.images?.size).toBe(0);+ expect(files.size).toBe(0);+ expect(thumbs.deletes).toHaveBeenCalledExactlyOnceWith(tempUri);+ await act(async () => finish());+ expect(files.size).toBe(0);+ expect(thumbs.deletes).toHaveBeenCalledTimes(2);+ expect(Image.getSize).not.toHaveBeenCalled();+ expect(thumbs.reads).not.toHaveBeenCalled();+ });+it.each(["error", "cancel", "timeout"])("cleans inline sizing files on %s", async (event) => {vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });let finish!: (size: { width: number; height: number }) => void;diff --git a/apps/mobile/src/session/useConversationShareImages.ts b/apps/mobile/src/session/useConversationShareImages.tsindex d3b656970c..dc8d71da02 100644--- a/apps/mobile/src/session/useConversationShareImages.ts+++ b/apps/mobile/src/session/useConversationShareImages.ts@@ -22,7 +22,10 @@ import {const MAX_IMAGE_BYTES = 8 * 1024 * 1024;-async function readShareImageSize(uri: string, signal: AbortSignal) {+async function readWithShareImageCancellation<T>(+ read: () => Promise<T>,+ signal: AbortSignal,+) {if (signal.aborted) throw new Error("conversation share image cancelled");let onAbort!: () => void;const cancelled = new Promise<never>((_, reject) => {@@ -30,9 +33,8 @@ async function readShareImageSize(uri: string, signal: AbortSignal) {signal.addEventListener("abort", onAbort, { once: true });});try {- // Android's encoded-image size reader accepts file:// but rejects data:.- // Racing cancellation also releases temporary files if native IO stalls.- return await Promise.race([Image.getSize(uri), cancelled]);+ // Native IO may outlive this export; let its owner clean up on cancellation.+ return await Promise.race([read(), cancelled]);} finally {signal.removeEventListener("abort", onAbort);}@@ -49,38 +51,59 @@ async function readShareImageFile(const file = new File(uri);if (!file.exists || file.size <= 0 || file.size > MAX_IMAGE_BYTES)return null;- const size = await readShareImageSize(uri, signal);+ // Android's encoded-image size reader accepts file:// but rejects data:.+ const size = await readWithShareImageCancellation(() => Image.getSize(uri), signal);if (!canRead()) return null;const dataUri = embeddedUri ?? `data:${mimeType};base64,${await file.base64()}`;return canRead() ? { uri: dataUri, ...size } : null;}-/** Inline sources need a file only for sizing; exports keep their embedded bytes. */+/** Stage Base64 only for sizing; retain other inline formats supported natively. */async function readShareImageDataUri(uri: string,canRead: () => boolean,signal: AbortSignal,): Promise<ConversationShareImage | null> {- const header = /^data:(image\/[^;,]+);base64,/.exec(uri);- if (!header || uri.length === header[0].length || !canRead()) return null;+ if (!canRead()) return null;+ const header = /^data:(image\/[^;,]+)(?:;[^,]*)?;base64,/i.exec(uri);+ if (!header) {+ // iOS can size other data-image encodings. Preserve that existing support;+ // an unsupported native format still follows the usual placeholder path.+ const size = await readWithShareImageCancellation(() => Image.getSize(uri), signal);+ return canRead() ? { uri, ...size } : null;+ }+ if (uri.length === header[0].length) return null;+ const mimeType = header[1]!.toLowerCase();+ const base64 = decodeURIComponent(uri.slice(header[0].length));const directory = new Directory(Paths.cache, "conversation-share-images");let file: File | null = null;+ const cleanup = () => {+ try {+ file?.delete();+ } catch {+ // Best-effort cleanup within the OS cache, including partial writes.+ }+ };try {directory.create({ intermediates: true, idempotent: true });const unique = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;- file = new File(directory, `image-${unique}.${extOfMime(header[1]!)}`);+ file = new File(directory, `image-${unique}.${extOfMime(mimeType)}`);const FileSystem = await import("expo-file-system/legacy");if (!canRead()) return null;- await FileSystem.writeAsStringAsync(file.uri, uri.slice(header[0].length), {- encoding: FileSystem.EncodingType.Base64,- });- return await readShareImageFile(file.uri, header[1]!, canRead, signal, uri);+ const targetUri = file.uri;+ await readWithShareImageCancellation(() => {+ const write = FileSystem.writeAsStringAsync(targetUri, base64, {+ encoding: FileSystem.EncodingType.Base64,+ });+ // Cancellation cannot stop this native write. Clean up again if a late+ // completion recreates the file after the immediate finally cleanup.+ const cleanupLateWrite = () => { if (signal.aborted) cleanup(); };+ void write.then(cleanupLateWrite, cleanupLateWrite);+ return write;+ }, signal);+ return await readShareImageFile(file.uri, mimeType, canRead, signal, uri);} finally {- try {- file?.delete();- } catch {- // Best-effort cleanup within the OS cache, including partial writes.- }+ cleanup();}}