@devries-cameron20 / t3code-1 / commits / 0af8be3bb1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): pasted images over the size limit attach instead of vanishing (#35845)

Julius Marminge committed Nov 12, 2026 at 22:21 UTC 0af8be3bb1ebde73e6f71aa05b0bfaa59a0728c2
7 files changed +161 -28
apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
+5 -3
@@ -3,6 +3,7 @@ import { TextInputWrapper } from "expo-paste-input";
3 import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4 import { useMemo, useState } from "react";
5 import { ScrollView, View, useWindowDimensions } from "react-native";
6 +import * as Dialog from "../../components/ui/Dialog";
7 import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
8
9 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
@@ -86,13 +87,14 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
87 const handleNativePaste = useNativePaste((uris) => {
88 void (async () => {
89 try {
89 - const images = await convertPastedImagesToAttachments({
90 + const result = await convertPastedImagesToAttachments({
91 uris,
92 existingCount: attachments.length,
93 });
93 - if (images.length > 0) {
94 - setAttachments((current) => [...current, ...images]);
94 + if (result.attachments.length > 0) {
95 + setAttachments((current) => [...current, ...result.attachments]);
96 }
97 + if (result.error) Dialog.alert("Could not paste image", result.error);
98 } catch (error) {
99 console.error("[review comment] error converting pasted images", error);
100 }
apps/mobile/src/features/threads/QuestionAttachments.tsx
+7 -4
@@ -109,14 +109,17 @@ export function QuestionAttachments(props: {
109 uris,
110 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
111 })
112 - .then(async (images) => {
112 + .then(async (result) => {
113 if (
114 scope.active &&
115 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
116 ) {
117 - if (append(key, images) > 0)
118 - Dialog.alert("Could not paste image", "Too many attachments.");
119 - } else await releaseUnusedComposerAttachmentFiles(images);
117 + const problems = [
118 + ...(result.error ? [result.error] : []),
119 + ...(append(key, result.attachments) > 0 ? ["Too many attachments."] : []),
120 + ];
121 + if (problems.length) Dialog.alert("Could not paste image", problems.join("\n\n"));
122 + } else await releaseUnusedComposerAttachmentFiles(result.attachments);
123 })
124 .catch((error) =>
125 Dialog.alert(
apps/mobile/src/lib/composerImagePreview.test.ts
+29 -1
@@ -32,7 +32,7 @@ vi.mock("expo-file-system", () => ({
32 return mocks.write(content, options);
33 }
34 async move(destination: { uri: string }) {
35 - mocks.files.delete(this.uri);
35 + if (!mocks.files.delete(this.uri)) throw new Error("source missing");
36 mocks.files.add(destination.uri);
37 this.uri = destination.uri;
38 }
@@ -103,4 +103,32 @@ describe("materializedPreviewAtom", () => {
103 expect(await materialize()).toBe("file:///cache/t3-composer-previews/image-failed.png");
104 expect(mocks.write).toHaveBeenCalledTimes(2);
105 });
106 +
107 + it("shares one write when the atom is rebuilt while its preview is still being written", async () => {
108 + const attachment: DraftComposerImageAttachment = {
109 + id: "image-rebuilt",
110 + type: "image",
111 + name: "pasted.jpeg",
112 + mimeType: "image/jpeg",
113 + sizeBytes: 3,
114 + previewUri: "data:image/jpeg;base64,AAAA",
115 + };
116 + const read = () => {
117 + const registry = AtomRegistry.make();
118 + const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));
119 + const unmount = registry.mount(atom);
120 + return vi
121 + .waitFor(() => {
122 + const result = registry.get(atom);
123 + expect(AsyncResult.isSuccess(result)).toBe(true);
124 + return AsyncResult.isSuccess(result) ? result.value : undefined;
125 + })
126 + .finally(unmount);
127 + };
128 +
129 + expect(await Promise.all([read(), read()])).toEqual([
130 + "file:///cache/t3-composer-previews/image-rebuilt.jpg",
131 + "file:///cache/t3-composer-previews/image-rebuilt.jpg",
132 + ]);
133 + });
134 });
apps/mobile/src/lib/composerImagePreview.ts
+13 -1
@@ -32,6 +32,18 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<s
32 return file.uri;
33 }
34
35 +const inFlightPreviews = new Map<string, Promise<string | null>>();
36 +
37 +// A render reads the atom before its effect subscribes, so the registry can drop and rebuild it
38 +// mid-write; a second writer would delete the first one's partial file and fail its own move.
39 +function materializePreviewOnce(id: string, dataUrl: string): Promise<string | null> {
40 + const pending = inFlightPreviews.get(id);
41 + if (pending) return pending;
42 + const next = materializeDataUrlPreview(id, dataUrl).finally(() => inFlightPreviews.delete(id));
43 + inFlightPreviews.set(id, next);
44 + return next;
45 +}
46 +
47 class ImagePreviewCacheError extends Schema.TaggedError<ImagePreviewCacheError>()(
48 "ImagePreviewCacheError",
49 { cause: Schema.Defect() },
@@ -59,7 +71,7 @@ export class MaterializedPreviewKey implements Equal.Equal {
71 export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>
72 Atom.make(
73 Effect.tryPromise({
62 - try: () => materializeDataUrlPreview(attachment.id, attachment.previewUri),
74 + try: () => materializePreviewOnce(attachment.id, attachment.previewUri),
75 catch: (cause) => new ImagePreviewCacheError({ cause }),
76 }).pipe(
77 Effect.catch((error) =>
apps/mobile/src/lib/composerImages.test.ts
+69 -4
@@ -121,6 +121,15 @@ vi.mock("./uuid", () => ({
121
122 import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages";
123
124 +function oversizedPng(): string {
125 + const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1);
126 + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
127 + png.write("IHDR", 12);
128 + png.writeUInt32BE(2000, 16);
129 + png.writeUInt32BE(2000, 20);
130 + return png.toString("base64");
131 +}
132 +
133 describe("native pasted image cleanup", () => {
134 beforeEach(() => {
135 files.clear();
@@ -131,7 +140,10 @@ describe("native pasted image cleanup", () => {
140 const uri = "content://media/external/images/media/42";
141 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
142
134 - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
143 + const { attachments } = await convertPastedImagesToAttachments({
144 + uris: [uri],
145 + existingCount: 0,
146 + });
147
148 expect(attachments).toEqual([
149 expect.objectContaining({
@@ -149,7 +161,10 @@ describe("native pasted image cleanup", () => {
161 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
162 manipulator.state.sourceSize = { width: 100, height: 100 };
163
152 - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
164 + const { attachments } = await convertPastedImagesToAttachments({
165 + uris: [uri],
166 + existingCount: 0,
167 + });
168
169 expect(attachments).toEqual([
170 expect.objectContaining({
@@ -171,7 +186,10 @@ describe("native pasted image cleanup", () => {
186 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
187 );
188
174 - const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
189 + const { attachments } = await convertPastedImagesToAttachments({
190 + uris: [uri],
191 + existingCount: 0,
192 + });
193
194 expect(attachments).toEqual([]);
195 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
@@ -183,7 +201,7 @@ describe("native pasted image cleanup", () => {
201 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
202 files.set(uri, { base64: "aGVsbG8=", deleted: false });
203
186 - const attachments = await convertPastedImagesToAttachments({
204 + const { attachments } = await convertPastedImagesToAttachments({
205 uris: [uri],
206 existingCount: 0,
207 });
@@ -216,6 +234,53 @@ describe("native pasted image cleanup", () => {
234 expect(files.get(overflow)?.deleted).toBe(true);
235 expect(files.get(userOwned)?.deleted).toBe(false);
236 });
237 +
238 + it("re-renders an over-limit paste whose dimensions already fit, like the photo picker", async () => {
239 + const uri =
240 + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/photo.png";
241 + files.set(uri, { base64: oversizedPng(), deleted: false });
242 + manipulator.state.sourceSize = { width: 2000, height: 2000 };
243 +
244 + const { attachments } = await convertPastedImagesToAttachments({
245 + uris: [uri],
246 + existingCount: 0,
247 + });
248 +
249 + expect(attachments).toHaveLength(1);
250 + expect(attachments[0]?.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
251 + expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
252 + });
253 +
254 + it("keeps the readable images of a paste and still reports the one it dropped", async () => {
255 + const gone =
256 + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/gone.png";
257 + const kept =
258 + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/kept.png";
259 + files.set(kept, { base64: "aGVsbG8=", deleted: false });
260 +
261 + const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 });
262 +
263 + expect(result.attachments).toEqual([
264 + expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }),
265 + ]);
266 + expect(result.error).toBe("Could not read a pasted image.");
267 + });
268 +
269 + it("reports the size limit when even the JPEG re-render is too large", async () => {
270 + const uri =
271 + "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/huge.png";
272 + files.set(uri, { base64: oversizedPng(), deleted: false });
273 + manipulator.state.sourceSize = { width: 2000, height: 2000 };
274 + manipulator.state.renderedBase64 = oversizedPng();
275 +
276 + const result = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
277 +
278 + expect(result).toEqual({
279 + attachments: [],
280 + error: "A pasted image exceeds the 10 MB attachment limit.",
281 + });
282 + expect(files.get(uri)?.deleted).toBe(true);
283 + });
284 });
285
286 describe("persistComposerAttachmentFile", () => {
apps/mobile/src/lib/composerImages.ts
+32 -13
@@ -572,10 +572,14 @@ function isOwnedPastedImageUri(uri: string): boolean {
572 export async function convertPastedImagesToAttachments(input: {
573 readonly uris: ReadonlyArray<string>;
574 readonly existingCount: number;
575 -}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
575 +}): Promise<{
576 + readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
577 + readonly error: string | null;
578 +}> {
579 const { File } = await import("expo-file-system");
580 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
578 - const results: DraftComposerImageAttachment[] = [];
581 + const attachments: DraftComposerImageAttachment[] = [];
582 + let error: string | null = null;
583
584 for (const [index, uri] of input.uris.entries()) {
585 const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : [];
@@ -588,31 +592,46 @@ export async function convertPastedImagesToAttachments(input: {
592 const sourceMimeType = reportedMimeType?.startsWith("image/")
593 ? reportedMimeType
594 : mimeTypeFromUri(uri);
591 - const mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType)
595 + let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType)
596 ? sourceMimeType
597 : "image/jpeg";
598 const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri);
595 - if (rendered !== null) {
596 - temporaryUris.push(rendered.uri);
597 - }
599 const pastedBase64 = rendered?.base64 ?? (await file.base64());
600 const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 }));
600 - const base64 = fitted?.base64 ?? pastedBase64;
601 + if (fitted !== null) {
602 + temporaryUris.push(fitted.uri);
603 + }
604 + let base64 = fitted?.base64 ?? pastedBase64;
605 + if (
606 + rendered === null &&
607 + estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
608 + ) {
609 + const jpeg = await renderPhoto(uri);
610 + temporaryUris.push(jpeg.uri);
611 + mimeType = "image/jpeg";
612 + base64 = jpeg.base64;
613 + }
614 const sizeBytes = estimateBase64ByteSize(base64);
615 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
616 + error =
617 + sizeBytes > 0
618 + ? "A pasted image exceeds the 10 MB attachment limit."
619 + : "Could not read a pasted image.";
620 continue;
621 }
605 - results.push({
622 + const dataUrl = `data:${mimeType};base64,${base64}`;
623 + attachments.push({
624 id: uuidv4(),
625 type: "image",
626 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
627 mimeType,
628 sizeBytes,
611 - dataUrl: `data:${mimeType};base64,${base64}`,
612 - previewUri: `data:${mimeType};base64,${base64}`,
629 + dataUrl,
630 + previewUri: dataUrl,
631 });
614 - } catch (error) {
615 - console.warn("Failed to read pasted image", uri, error);
632 + } catch (cause) {
633 + console.warn("Failed to read pasted image", uri, cause);
634 + error = "Could not read a pasted image.";
635 } finally {
636 for (const temporaryUri of temporaryUris) {
637 try {
@@ -627,5 +646,5 @@ export async function convertPastedImagesToAttachments(input: {
646 }
647 }
648
630 - return results;
649 + return { attachments, error };
650 }
apps/mobile/src/state/use-composer-attachment-actions.ts
+6 -2
@@ -101,11 +101,15 @@ export function useComposerAttachmentActions(props: {
101 const insertion = captureComposerDraftInsertion(key);
102 await withDraftOperation(key, async (signal) => {
103 try {
104 - const images = await convertPastedImagesToAttachments({
104 + const result = await convertPastedImagesToAttachments({
105 uris,
106 existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
107 });
108 - report("Could not paste images", null, await append(key, signal, images, insertion));
108 + report(
109 + "Could not paste images",
110 + result.error,
111 + await append(key, signal, result.attachments, insertion),
112 + );
113 } catch (error) {
114 Dialog.alert(
115 "Could not paste images",