Files
t3code/apps/mobile/src/lib/composerImages.ts
T
Theo BrowneandClaude Fable 5 f695b6f5bf feat: upload composer images on attach
Attachments used to ride the turn-start command as base64 data URLs:
send carried the bytes, the stash re-encoded them into localStorage,
and a 10MB image meant a 14M-char string in a single ws frame.

Images now upload the moment they are attached. A ws RPC mints a
pending-<uuid> id plus a signed, expiring upload URL (mirroring signed
asset GETs, so it works against any environment); the browser POSTs the
compressed bytes to it with progress and abort; the turn-start command
carries id references only. The Normalizer renames pending files to
their thread segment at send, resolving by uuid so retries after a
partial send are idempotent. Never-sent uploads are deleted on chip
removal and swept after 30 days.

Breaking: the dataUrl upload variant is deleted with no compatibility
path. RN mobile compiles with image attach gated off behind
IMAGE_ATTACH_ENABLED and tells the user an update is needed; drafts and
stash persist id references (v9/v3 storage, old payloads purged).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-13 17:51:12 -07:00

313 lines
8.7 KiB
TypeScript

import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { estimateBase64ByteSize } from "./base64";
import { uuidv4 } from "./uuid";
/**
* Local-only draft shape. It used to extend the contracts upload type, but
* `thread.turn.start` now carries id references to already-uploaded blobs, so
* `dataUrl` never reaches the wire and lives purely in mobile draft storage.
*/
export interface DraftComposerImageAttachment {
readonly id: string;
readonly previewUri: string;
readonly type: "image";
readonly name: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly dataUrl: string;
}
export const IMAGE_ATTACH_UNAVAILABLE_MESSAGE = "Image attach needs an app update.";
/**
* Copy for legacy draft/outbox images that predate the contract change and so
* cannot be sent. Returns null when there is nothing to warn about.
*/
export function droppedAttachmentsWarning(count: number): string | null {
if (count <= 0) {
return null;
}
const subject = count === 1 ? "1 image was" : `${count} images were`;
return `${subject} not sent. ${IMAGE_ATTACH_UNAVAILABLE_MESSAGE}`;
}
/**
* Mobile has no upload-on-attach implementation yet (web shipped first), and
* the old data-url path is gone from the contract. Capture stays disabled
* until the mobile port lands; flip this back on with that change.
*/
const IMAGE_ATTACH_ENABLED: boolean = false;
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
async function loadImagePicker() {
try {
return await import("expo-image-picker");
} catch (error) {
throw new Error("Image attachments are unavailable right now.", { cause: error });
}
}
async function loadClipboard() {
try {
return await import("expo-clipboard");
} catch (error) {
throw new Error("Clipboard paste is unavailable right now.", { cause: error });
}
}
export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly error: string | null;
}> {
if (!IMAGE_ATTACH_ENABLED) {
return { images: [], error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (remainingSlots <= 0) {
return {
images: [],
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
};
}
let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
try {
imagePicker = await loadImagePicker();
} catch (error) {
return {
images: [],
error:
error instanceof Error ? error.message : "Image attachments are unavailable right now.",
};
}
const result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
});
if (result.canceled) {
return {
images: [],
error: null,
};
}
const nextImages: DraftComposerImageAttachment[] = [];
let error: string | null = null;
for (const asset of result.assets) {
const mimeType = asset.mimeType?.toLowerCase();
if (!mimeType?.startsWith("image/")) {
error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
continue;
}
const base64 = asset.base64;
if (!base64) {
error = `Failed to read '${asset.fileName ?? "image"}'.`;
continue;
}
const sizeBytes = asset.fileSize ?? estimateBase64ByteSize(base64);
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
continue;
}
nextImages.push({
id: uuidv4(),
type: "image",
name: asset.fileName ?? "image",
mimeType,
sizeBytes,
dataUrl: `data:${mimeType};base64,${base64}`,
previewUri: asset.uri,
});
}
return {
images: nextImages,
error,
};
}
export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
readonly text: string | null;
readonly error: string | null;
}> {
let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
try {
clipboard = await loadClipboard();
} catch (error) {
return {
images: [],
text: null,
error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
};
}
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
if (await clipboard.hasImageAsync()) {
if (!IMAGE_ATTACH_ENABLED) {
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
}
if (remainingSlots <= 0) {
return {
images: [],
text: null,
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
};
}
const image = await clipboard.getImageAsync({ format: "png" });
if (!image) {
return {
images: [],
text: null,
error: "Clipboard image is unavailable.",
};
}
const base64 = image.data.split(",")[1] ?? "";
const sizeBytes = estimateBase64ByteSize(base64);
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return {
images: [],
text: null,
error: "Clipboard image exceeds the 10 MB attachment limit.",
};
}
return {
images: [
{
id: uuidv4(),
type: "image",
name: "pasted-image.png",
mimeType: "image/png",
sizeBytes,
dataUrl: image.data,
previewUri: image.data,
},
],
text: null,
error: null,
};
}
if (await clipboard.hasStringAsync()) {
const text = await clipboard.getStringAsync();
return {
images: [],
text: text.length > 0 ? text : null,
error: text.length > 0 ? null : "Clipboard is empty.",
};
}
return {
images: [],
text: null,
error: "Clipboard does not contain pasteable text or image content.",
};
}
function mimeTypeFromUri(uri: string): string {
const ext = uri.split(".").pop()?.toLowerCase();
switch (ext) {
case "png":
return "image/png";
case "jpg":
case "jpeg":
return "image/jpeg";
case "gif":
return "image/gif";
case "webp":
return "image/webp";
case "heic":
return "image/heic";
default:
return "image/png";
}
}
export function isOwnedPastedImageUri(uri: string): boolean {
try {
const url = new URL(uri);
if (url.protocol !== "file:") {
return false;
}
const segments = url.pathname.split("/").filter(Boolean);
return (
segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
);
} catch {
return false;
}
}
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray<string>;
readonly existingCount: number;
}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
const { File } = await import("expo-file-system");
// Zero slots while attach is disabled: the loop below still runs so owned
// temporary paste files are deleted, but nothing is decoded or attached.
const remainingSlots = IMAGE_ATTACH_ENABLED
? PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount
: 0;
if (!IMAGE_ATTACH_ENABLED && input.uris.length > 0) {
console.warn(IMAGE_ATTACH_UNAVAILABLE_MESSAGE, { droppedPastedImages: input.uris.length });
}
const results: DraftComposerImageAttachment[] = [];
for (const [index, uri] of input.uris.entries()) {
const ownedTemporaryFile = isOwnedPastedImageUri(uri);
try {
if (index >= Math.max(0, remainingSlots)) {
continue;
}
const file = new File(uri);
const base64 = await file.base64();
const sizeBytes = estimateBase64ByteSize(base64);
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
continue;
}
const mimeType = mimeTypeFromUri(uri);
results.push({
id: uuidv4(),
type: "image",
name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
mimeType,
sizeBytes,
dataUrl: `data:${mimeType};base64,${base64}`,
previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
});
} catch (error) {
console.warn("Failed to read pasted image", uri, error);
} finally {
if (ownedTemporaryFile) {
try {
const file = new File(uri);
if (file.exists) {
file.delete();
}
} catch (error) {
console.warn("Failed to remove temporary pasted image", uri, error);
}
}
}
}
return results;
}