Skip to content
TypeScript

fix(mobile): images picked with choose files reach the agent as images (#21352)

maria140de68f25c5
diff --git a/apps/mobile/src/lib/attachmentUpload.test.ts b/apps/mobile/src/lib/attachmentUpload.test.ts
index 70d933805d9..77ae7cc8654 100644
--- a/apps/mobile/src/lib/attachmentUpload.test.ts
+++ b/apps/mobile/src/lib/attachmentUpload.test.ts
@@ -1,4 +1,4 @@
-import { EnvironmentId } from "@t3tools/contracts";
+import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -410,6 +410,41 @@ describe("prepareTurnAttachments", () => {
});
});
+ it("uploads an oversized document-picked image as a file", async () => {
+ const largeImage = {
+ ...documentPickedImage,
+ mimeType: "image/png",
+ sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
+ };
+ const prepared = await prepareTurnAttachments({ environmentId, attachments: [largeImage] });
+
+ expect(mocks.runAtomCommand).toHaveBeenCalledWith(
+ expect.anything(),
+ mocks.createUploadUrl,
+ expect.objectContaining({
+ input: {
+ type: "file",
+ name: largeImage.name,
+ mimeType: "image/png",
+ sizeBytes: largeImage.sizeBytes,
+ },
+ }),
+ expect.anything(),
+ );
+ expect(prepared.status).toBe("ready");
+ if (prepared.status !== "ready") return;
+ expect(prepared.attachments).toEqual([
+ {
+ type: "file",
+ id: MINTED_ID,
+ name: largeImage.name,
+ mimeType: "image/png",
+ sizeBytes: largeImage.sizeBytes,
+ },
+ ]);
+ expect(mocks.readBase64).not.toHaveBeenCalled();
+ });
+
it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
const pastedFile = {
...file,
diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts
index 14d1d630439..546c28f408f 100644
--- a/apps/mobile/src/lib/composerFiles.test.ts
+++ b/apps/mobile/src/lib/composerFiles.test.ts
@@ -90,6 +90,7 @@ vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));
import {
persistComposerAttachmentFile,
+ isComposerImageAttachment,
pickComposerFiles,
pickComposerImages,
pickComposerMedia,
@@ -108,6 +109,7 @@ describe("composer file attachments", () => {
mocks.open.mockReset();
mocks.size.mockReset();
mocks.readBase64.mockReset();
+ mocks.manipulate.mockReset();
mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42));
});
@@ -442,6 +444,169 @@ describe("composer file attachments", () => {
});
});
+ describe("images chosen through the file picker", () => {
+ it.each([
+ { name: "photo.bin", mimeType: "image/jpeg", expected: "image/jpeg" },
+ { name: "photo.png", mimeType: "image/png", expected: "image/png" },
+ { name: "photo.gif", mimeType: "image/gif", expected: "image/gif" },
+ { name: "photo.webp", mimeType: "image/webp", expected: "image/webp" },
+ { name: "photo.JPG", mimeType: undefined, expected: "image/jpeg" },
+ { name: "photo.PNG", mimeType: "application/octet-stream", expected: "image/png" },
+ { name: "photo.gif", mimeType: "binary/octet-stream", expected: "image/gif" },
+ { name: "photo.webp", mimeType: "application/unknown", expected: "image/webp" },
+ { name: "photo.jpg", mimeType: "IMAGE/PNG; charset=binary", expected: "image/png" },
+ ])("prepares $name ($mimeType) as $expected", async ({ name, mimeType, expected }) => {
+ mocks.pickFile.mockResolvedValue({
+ canceled: false,
+ assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }],
+ });
+ mocks.size.mockReturnValue(3);
+ mocks.readBase64.mockResolvedValue("YWJj");
+
+ const result = await pickComposerFiles({ existingCount: 0 });
+
+ expect(result).toEqual({
+ files: [
+ {
+ id: "attachment-id",
+ type: "image",
+ name,
+ mimeType: expected,
+ sizeBytes: 3,
+ dataUrl: `data:${expected};base64,YWJj`,
+ previewUri: `data:${expected};base64,YWJj`,
+ },
+ ],
+ error: null,
+ });
+ expect(mocks.manipulate).not.toHaveBeenCalled();
+ expect(mocks.delete).toHaveBeenCalledWith(
+ `file:///documents/t3-composer-attachments/attachment-id-${name}`,
+ );
+ });
+
+ it.each([
+ { name: "diagram.svg", mimeType: "image/svg+xml" },
+ { name: "photo.heic", mimeType: "image/heic" },
+ { name: "photo.tiff", mimeType: "image/tiff" },
+ { name: "photo.png", mimeType: "application/pdf" },
+ { name: "unknown.bin", mimeType: "application/octet-stream" },
+ ])("keeps $name ($mimeType) as a file", async ({ name, mimeType }) => {
+ mocks.pickFile.mockResolvedValue({
+ canceled: false,
+ assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 42 }],
+ });
+
+ const result = await pickComposerFiles({ existingCount: 0 });
+
+ expect(result.error).toBeNull();
+ expect(result.files).toEqual([expect.objectContaining({ type: "file", name, mimeType })]);
+ expect(mocks.readBase64).not.toHaveBeenCalled();
+ expect(mocks.manipulate).not.toHaveBeenCalled();
+ expect(mocks.delete).not.toHaveBeenCalled();
+ });
+
+ it.each([PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1])(
+ "classifies a measured %s byte PNG independently of picker metadata and file limit",
+ async (size) => {
+ mocks.pickFile.mockResolvedValue({
+ canceled: false,
+ assets: [
+ { uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png", size: 1 },
+ ],
+ });
+ mocks.size.mockReturnValue(size);
+ mocks.readBase64.mockResolvedValue("YWJj");
+
+ const result = await pickComposerFiles({
+ existingCount: 0,
+ maxBytes: size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? size : 1024,
+ });
+
+ expect(result.error).toBeNull();
+ expect(result.files[0]?.type).toBe(
+ size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? "file" : "image",
+ );
+ expect(isComposerImageAttachment(result.files[0]!)).toBe(
+ size <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
+ );
+ expect(mocks.readBase64).toHaveBeenCalledTimes(
+ size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? 0 : 1,
+ );
+ },
+ );
+
+ it.each([false, true])("fits a large PNG with oversized output: %s", async (oversized) => {
+ const header = Buffer.alloc(24);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);
+ header.write("IHDR", 12);
+ header.writeUInt32BE(4000, 16);
+ header.writeUInt32BE(3000, 20);
+ const original = header.toString("base64");
+ mocks.readBase64.mockResolvedValue(original);
+ const resize = vi.fn();
+ const renderAsync = vi.fn(async () => ({
+ width: 4000,
+ height: 3000,
+ release: vi.fn(),
+ saveAsync: vi.fn(async () => ({
+ uri: "file:///cache/fitted.png",
+ base64: oversized
+ ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64")
+ : "YWJj",
+ })),
+ }));
+ mocks.manipulate.mockImplementation(() => {
+ const context = {
+ resize: (size: unknown) => {
+ resize(size);
+ return context;
+ },
+ renderAsync,
+ };
+ return context;
+ });
+ mocks.pickFile.mockResolvedValue({
+ canceled: false,
+ assets: [{ uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png" }],
+ });
+
+ const result = await pickComposerFiles({ existingCount: 0 });
+
+ expect(resize).toHaveBeenCalledWith({ width: 2000, height: 1500 });
+ expect(result).toEqual({
+ files: [
+ expect.objectContaining({
+ type: "image",
+ mimeType: "image/png",
+ sizeBytes: oversized ? header.length : 3,
+ dataUrl: `data:image/png;base64,${oversized ? original : "YWJj"}`,
+ previewUri: oversized
+ ? `data:image/png;base64,${original}`
+ : "file:///cache/fitted.png",
+ }),
+ ],
+ error: null,
+ });
+ });
+
+ it("releases the owned copy when reading an image fails", async () => {
+ mocks.pickFile.mockResolvedValue({
+ canceled: false,
+ assets: [{ uri: "file:///picker/photo.png", name: "photo.png", mimeType: "image/png" }],
+ });
+ mocks.readBase64.mockRejectedValue(new Error("unreadable image"));
+
+ expect(await pickComposerFiles({ existingCount: 0 })).toEqual({
+ files: [],
+ error: "unreadable image",
+ });
+ expect(mocks.delete).toHaveBeenCalledWith(
+ "file:///documents/t3-composer-attachments/attachment-id-photo.png",
+ );
+ });
+ });
+
it("copies picked files into app-owned storage without loading their contents", async () => {
mocks.pickFile.mockResolvedValue({
canceled: false,
diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts
index 9804a6d0e58..7488b194ff9 100644
--- a/apps/mobile/src/lib/composerImages.test.ts
+++ b/apps/mobile/src/lib/composerImages.test.ts
@@ -1,5 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
+import {
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
+} from "@t3tools/contracts";
const files = new Map<string, { base64: string; deleted: boolean; text?: string }>();
@@ -263,4 +266,20 @@ describe("composerStripAttachments", () => {
"vid-1",
]);
});
+
+ it("keeps oversized document-picked images visible while sending them as files", async () => {
+ const { composerStripAttachments, isComposerImageAttachment } =
+ await import("./composerImages");
+ const oversizedImage = {
+ ...video,
+ id: "large-image",
+ name: "large.png",
+ mimeType: "image/png",
+ fileUri: "file:///large.png",
+ sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
+ };
+
+ expect(composerStripAttachments([oversizedImage])).toEqual([oversizedImage]);
+ expect(isComposerImageAttachment(oversizedImage)).toBe(false);
+ });
});
diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts
index 21cc272028f..4bf1d1623d0 100644
--- a/apps/mobile/src/lib/composerImages.ts
+++ b/apps/mobile/src/lib/composerImages.ts
@@ -82,15 +82,22 @@ export function composerStripAttachments(
attachments: ReadonlyArray<DraftComposerAttachment>,
): ReadonlyArray<DraftComposerAttachment> {
return attachments.filter(
- (attachment) => isComposerImageAttachment(attachment) || videoMimeType(attachment) !== null,
+ (attachment) =>
+ attachment.type === "image" ||
+ imageMimeType(attachment) !== null ||
+ videoMimeType(attachment) !== null,
);
}
-/** Detect from the attachment; the document picker labels images as plain files. */
+/** Promote legacy document-picked images only when their originals fit the image contract. */
export function isComposerImageAttachment(
attachment: DraftComposerAttachment,
): attachment is DraftComposerImageAttachment {
- return attachment.type === "image" || imageMimeType(attachment) !== null;
+ return (
+ attachment.type === "image" ||
+ (attachment.sizeBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES &&
+ imageMimeType(attachment) !== null)
+ );
}
export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
@@ -251,7 +258,7 @@ export async function pickComposerFiles(input: {
readonly existingCount: number;
readonly maxBytes?: number;
}): Promise<{
- readonly files: ReadonlyArray<DraftComposerFileAttachment>;
+ readonly files: ReadonlyArray<DraftComposerAttachment>;
readonly error: string | null;
}> {
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
@@ -283,7 +290,7 @@ export async function pickComposerFiles(input: {
const maxBytes = clampFileAttachmentUploadBytes(
input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
);
- const attachments: DraftComposerFileAttachment[] = [];
+ const attachments: DraftComposerAttachment[] = [];
let error: string | null = null;
let exceededAttachmentLimit = false;
for (const file of result.assets) {
@@ -294,15 +301,50 @@ export async function pickComposerFiles(input: {
// SAF can return blank display names, but the wire contract rejects them; fill before persisting.
const name = file.name.trim().length > 0 ? file.name : "file";
try {
- attachments.push(
- await createComposerFileAttachment({
- uri: file.uri,
+ const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" });
+ const attachment = await createComposerFileAttachment({
+ uri: file.uri,
+ name,
+ mimeType: file.mimeType || "application/octet-stream",
+ sizeBytes: file.size ?? null,
+ maxBytes:
+ mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
+ });
+ if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
+ attachments.push(attachment);
+ continue;
+ }
+ try {
+ const { File } = await import("expo-file-system");
+ const original = await new File(attachment.fileUri).base64();
+ const candidate = await fitComposerImage({
+ uri: attachment.fileUri,
+ mimeType,
+ base64: original,
+ });
+ const fitted =
+ candidate !== null &&
+ estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
+ ? candidate
+ : null;
+ const base64 = fitted?.base64 ?? original;
+ const sizeBytes = estimateBase64ByteSize(base64);
+ if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
+ throw new Error(`'${name}' exceeds the 10 MB attachment limit.`);
+ }
+ const dataUrl = `data:${mimeType};base64,${base64}`;
+ attachments.push({
+ id: attachment.id,
+ type: "image",
name,
- mimeType: file.mimeType || "application/octet-stream",
- sizeBytes: file.size ?? null,
- maxBytes,
- }),
- );
+ mimeType,
+ sizeBytes,
+ dataUrl,
+ previewUri: fitted?.uri ?? dataUrl,
+ });
+ } finally {
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
+ }
} catch (cause) {
error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
}