Open History to see the last commit
1/**
2 * Downscale + re-encode for image attachments that are too big for where
3 * they're headed. Two consumers share the same pipeline:
4 *
5 * - The prompt stash persists images as base64 in localStorage (~5MB origin
6 * quota), so `compressImageForStash` targets a per-image character budget.
7 * - The composer accepts pasted/dropped images larger than the provider's
8 * `PROVIDER_SEND_TURN_MAX_IMAGE_BYTES` wire cap and shrinks them to fit
9 * via `compressImageToByteLimit` instead of rejecting the paste.
10 *
11 * Supported images already within budget pass through untouched. HEIC/HEIF
12 * photos are decoded to JPEG first because providers cannot consume them.
13 */
14
15/**
16 * Longest edge kept when an image has to be re-encoded. Sized so a typical
17 * retina screenshot (3024px wide) stays legible rather than being halved.
18 */
19const MAX_DIMENSION = 2048;
20/** Base64 budget for a single stashed image (~975KB of binary). */
21export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
22/**
23 * Ceiling on the *source* file handed to the re-encoder. File size is a
24 * proxy for pixel count, and decoding hundreds of megapixels into an
25 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
26 */
27export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
28const MAX_HEIC_DECODE_PIXELS = 64_000_000;
29const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
30/**
31 * Quality ladder tried in order until the encoded image fits the budget.
32 * The floor stays high enough to avoid visible blocking on UI screenshots;
33 * if even that overflows we drop resolution instead of quality.
34 */
35const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
36/** Extra downscale passes applied when even the lowest quality overflows. */
37const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
38const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
39const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
40
41type ImageSize = { width: number; height: number };
42
43export interface CompressedStashImage {
44 imageSize?: ImageSize;
45 dataUrl: string;
46 mimeType: string;
47 sizeBytes: number;
48 /** True when the payload was re-encoded rather than stored verbatim. */
49 recompressed: boolean;
50}
51
52/**
53 * Why an image could not be compressed. Callers report these differently:
54 * "too large" is a budget outcome, "unreadable" is a decode failure.
55 */
56export type ImageCompressionFailureReason = "too-large" | "unreadable";
57
58export type CompressStashImageResult =
59 | { ok: true; image: CompressedStashImage }
60 | { ok: false; reason: ImageCompressionFailureReason };
61
62export type CompressImageFileResult =
63 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
64 | { ok: false; reason: ImageCompressionFailureReason };
65
66/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
67export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
68 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
69 return true;
70 }
71 return (
72 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
73 HEIC_IMAGE_EXTENSION.test(file.name)
74 );
75}
76
77interface HeicMetadataBox {
78 payloadOffset: number;
79 endOffset: number;
80}
81
82function findHeicMetadataBox(
83 view: DataView,
84 startOffset: number,
85 endOffset: number,
86 type: number,
87): HeicMetadataBox | null {
88 let offset = startOffset;
89 while (offset + 8 <= endOffset) {
90 let size = view.getUint32(offset);
91 let headerSize = 8;
92 if (size === 1) {
93 if (offset + 16 > endOffset) return null;
94 const extendedSize = view.getBigUint64(offset + 8);
95 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
96 size = Number(extendedSize);
97 headerSize = 16;
98 } else if (size === 0) {
99 size = endOffset - offset;
100 }
101 if (size < headerSize || size > endOffset - offset) return null;
102
103 const nextOffset = offset + size;
104 if (view.getUint32(offset + 4) === type) {
105 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
106 }
107 offset = nextOffset;
108 }
109 return null;
110}
111
112/** Read HEIC image dimensions before the decoder allocates full RGBA buffers. */
113async function validateHeicImageDimensions(
114 file: File,
115): Promise<ImageCompressionFailureReason | null> {
116 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
117 const view = new DataView(metadata);
118 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
119 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
120 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
121 if (!properties) return "unreadable";
122 const containers = findHeicMetadataBox(
123 view,
124 properties.payloadOffset,
125 properties.endOffset,
126 0x6970636f,
127 );
128 if (!containers) return "unreadable";
129
130 let offset = containers.payloadOffset;
131 let foundImageDimensions = false;
132 while (offset < containers.endOffset) {
133 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
134 if (!image) break;
135 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
136 const width = view.getUint32(image.payloadOffset + 4);
137 const height = view.getUint32(image.payloadOffset + 8);
138 if (width === 0 || height === 0) return "unreadable";
139 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
140 foundImageDimensions = true;
141 offset = image.endOffset;
142 }
143 return foundImageDimensions ? null : "unreadable";
144}
145
146/** Chunked so a large image can't blow the argument limit of `fromCharCode`. */
147const BASE64_CHUNK_SIZE = 0x8000;
148
149function bytesToBase64(bytes: Uint8Array): string {
150 let binary = "";
151 for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
152 binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
153 }
154 return btoa(binary);
155}
156
157/**
158 * Blob → base64 data URL. Uses `arrayBuffer()` rather than `FileReader` so
159 * the module works anywhere `Blob` does (including non-DOM test runners).
160 */
161async function blobToDataUrl(blob: File | Blob, mimeTypeOverride?: string): Promise<string> {
162 const buffer = await blob.arrayBuffer();
163 const mimeType = mimeTypeOverride || blob.type || "application/octet-stream";
164 return `data:${mimeType};base64,${bytesToBase64(new Uint8Array(buffer))}`;
165}
166
167/** Approximate decoded byte count for a base64 data URL. */
168function dataUrlByteLength(dataUrl: string): number {
169 const commaIndex = dataUrl.indexOf(",");
170 const payload = commaIndex === -1 ? dataUrl : dataUrl.slice(commaIndex + 1);
171 const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
172 return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);
173}
174
175/** Base64 payload of a data URL decoded back into a `File`. */
176export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
177 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
178 const binary = atob(payload);
179 const bytes = new Uint8Array(binary.length);
180 for (let index = 0; index < binary.length; index += 1) {
181 bytes[index] = binary.charCodeAt(index);
182 }
183 return new File([bytes], name, { type: mimeType });
184}
185
186/**
187 * Re-encoding changes the container, so a name like `shot.png` would lie
188 * about its contents. Swap the extension to match the encoded mime type.
189 */
190function fileNameForMimeType(name: string, mimeType: string): string {
191 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
192 const dotIndex = name.lastIndexOf(".");
193 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
194 return `${base}${extension}`;
195}
196
197function canRecompress(): boolean {
198 return (
199 typeof createImageBitmap === "function" &&
200 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
201 );
202}
203
204interface Canvas2D {
205 canvas: OffscreenCanvas | HTMLCanvasElement;
206 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
207}
208
209function createCanvas(width: number, height: number): Canvas2D | null {
210 if (typeof OffscreenCanvas === "function") {
211 const canvas = new OffscreenCanvas(width, height);
212 const context = canvas.getContext("2d");
213 if (!context) return null;
214 return { canvas, context };
215 }
216 if (typeof document === "undefined") return null;
217 const canvas = document.createElement("canvas");
218 canvas.width = width;
219 canvas.height = height;
220 const context = canvas.getContext("2d");
221 if (!context) return null;
222 return { canvas, context };
223}
224
225/**
226 * WebP is preferred: at matched visual quality it lands roughly 25-35%
227 * smaller than JPEG, so the same budget buys more resolution and detail —
228 * and it keeps alpha, so screenshots with transparency survive intact.
229 * Browsers that can't encode it silently fall back to JPEG.
230 */
231async function encodeCanvas(
232 canvas: OffscreenCanvas | HTMLCanvasElement,
233 quality: number,
234 mimeType: string,
235 budgetChars: number,
236): Promise<{ dataUrl: string | null; mimeType: string } | null> {
237 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
238 const dataUrl = canvas.toDataURL(mimeType, quality);
239 // toDataURL silently returns a PNG when the requested type is unsupported.
240 if (!dataUrl.startsWith(`data:${mimeType}`)) return null;
241 return { dataUrl: dataUrl.length <= budgetChars ? dataUrl : null, mimeType };
242 }
243 const blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
244 if (blob.type && blob.type !== mimeType) return null;
245 const dataUrlLength = `data:${mimeType};base64,`.length + 4 * Math.ceil(blob.size / 3);
246 if (dataUrlLength > budgetChars) return { dataUrl: null, mimeType };
247 return { dataUrl: await blobToDataUrl(blob, mimeType), mimeType };
248}
249
250const composerThumbnails = new WeakMap<File, Promise<string | null>>();
251
252/** Cache a centered square crop for the composer's object-cover image tiles. */
253export function createComposerImageThumbnail(file: File): Promise<string | null> {
254 const cached = composerThumbnails.get(file);
255 if (cached) return cached;
256 const thumbnail = (async () => {
257 if (!canRecompress()) return null;
258 let bitmap: ImageBitmap | undefined;
259 try {
260 bitmap = await createImageBitmap(file);
261 const side = Math.min(bitmap.width, bitmap.height);
262 if (side <= 0) return null;
263 const dimension = Math.min(256, side);
264 const surface = createCanvas(dimension, dimension);
265 if (!surface) return null;
266 surface.context.drawImage(
267 bitmap,
268 (bitmap.width - side) / 2,
269 (bitmap.height - side) / 2,
270 side,
271 side,
272 0,
273 0,
274 dimension,
275 dimension,
276 );
277 return (
278 (await encodeCanvas(surface.canvas, 1, "image/png", Number.POSITIVE_INFINITY))?.dataUrl ??
279 null
280 );
281 } catch {
282 return null;
283 } finally {
284 bitmap?.close();
285 }
286 })();
287 composerThumbnails.set(file, thumbnail);
288 return thumbnail;
289}
290
291/**
292 * Draws `bitmap` scaled to fit `maxDimension` and encodes it, stepping
293 * quality down until the data URL fits `budgetChars`.
294 */
295async function encodeWithinBudget(
296 bitmap: ImageBitmap,
297 maxDimension: number,
298 budgetChars: number,
299 preferredMimeType?: "image/jpeg",
300): Promise<{ dataUrl: string; mimeType: string; imageSize: ImageSize } | null> {
301 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
302 const width = Math.max(1, Math.round(bitmap.width * scale));
303 const height = Math.max(1, Math.round(bitmap.height * scale));
304 const target = createCanvas(width, height);
305 if (!target) return null;
306
307 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
308 // happen before drawing and depends on which codec we end up using.
309 const mimeType =
310 preferredMimeType ??
311 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp", 0))
312 ? "image/webp"
313 : "image/jpeg");
314
315 if (mimeType === "image/jpeg") {
316 target.context.fillStyle = "#ffffff";
317 target.context.fillRect(0, 0, width, height);
318 }
319 target.context.drawImage(bitmap, 0, 0, width, height);
320
321 for (const quality of QUALITY_STEPS) {
322 const encoded = await encodeCanvas(target.canvas, quality, mimeType, budgetChars);
323 if (!encoded) break;
324 if (encoded.dataUrl !== null) {
325 return { dataUrl: encoded.dataUrl, mimeType: encoded.mimeType, imageSize: { width, height } };
326 }
327 }
328 return null;
329}
330
331type ReencodeResult =
332 | { ok: true; dataUrl: string; mimeType: string; imageSize: ImageSize }
333 | { ok: false; reason: ImageCompressionFailureReason };
334
335/**
336 * Shared re-encode loop: decodes `file`, then walks the quality ladder and
337 * fallback downscale passes until an encoding fits `budgetChars`.
338 */
339async function reencodeWithinBudget(
340 file: File,
341 budgetChars: number,
342 preferredMimeType?: "image/jpeg",
343): Promise<ReencodeResult> {
344 if (!canRecompress()) {
345 return { ok: false, reason: "too-large" };
346 }
347
348 let bitmap: ImageBitmap;
349 try {
350 bitmap = await createImageBitmap(file);
351 } catch {
352 return { ok: false, reason: "unreadable" };
353 }
354
355 try {
356 // Each pass shrinks relative to the *previous target*, capped by
357 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
358 // images already smaller than that ceiling — the fallback passes would
359 // all resolve to the source size and never actually reduce resolution.
360 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
361 // Tracks whether the *last* attempt threw, so a run of encoder failures
362 // is reported as unreadable while a run of merely-too-big results is
363 // reported as too-large.
364 let encodeFailed = false;
365 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
366 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
367 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
368 try {
369 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
370 } catch {
371 // Canvas allocation, drawing, or the codec itself can throw — often
372 // precisely *because* the target is too big (OOM on a large bitmap).
373 // Keep trying the smaller fallback scales rather than giving up: a
374 // reduced pass may well succeed. The exception must never escape,
375 // though, since callers finalize state after this returns and a
376 // throw would strand it (e.g. a stash entry stuck "still saving").
377 encodeFailed = true;
378 continue;
379 }
380 encodeFailed = false;
381 if (encoded && encoded.dataUrl.length <= budgetChars) {
382 return {
383 ok: true,
384 dataUrl: encoded.dataUrl,
385 mimeType: encoded.mimeType,
386 imageSize: encoded.imageSize,
387 };
388 }
389 }
390 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
391 } finally {
392 bitmap.close();
393 }
394}
395
396/**
397 * Produces the payload to persist for a stashed image.
398 *
399 * Small images are stored verbatim (preserving PNG transparency and exact
400 * pixels). Anything over budget is downscaled and re-encoded; if it still
401 * doesn't fit after the fallback passes, reports a failure so the caller
402 * can record it as dropped.
403 */
404export async function compressImageForStash(
405 file: File,
406 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
407): Promise<CompressStashImageResult> {
408 let originalDataUrl: string;
409 try {
410 originalDataUrl = await blobToDataUrl(file);
411 } catch {
412 return { ok: false, reason: "unreadable" };
413 }
414 if (originalDataUrl.length <= budgetChars) {
415 return {
416 ok: true,
417 image: {
418 dataUrl: originalDataUrl,
419 mimeType: file.type,
420 sizeBytes: file.size,
421 recompressed: false,
422 },
423 };
424 }
425 const reencoded = await reencodeWithinBudget(file, budgetChars);
426 if (!reencoded.ok) {
427 return reencoded;
428 }
429 return {
430 ok: true,
431 image: {
432 dataUrl: reencoded.dataUrl,
433 mimeType: reencoded.mimeType,
434 sizeBytes: dataUrlByteLength(reencoded.dataUrl),
435 recompressed: true,
436 imageSize: reencoded.imageSize,
437 },
438 };
439}
440
441/**
442 * Shrinks `file` until its binary size fits `maxBytes`, returning a new
443 * `File` (WebP or JPEG). Files already within the limit pass through
444 * untouched, preserving their exact bytes and format. Sources above
445 * `MAX_COMPRESSIBLE_SOURCE_BYTES` are refused outright — decoding them is
446 * the risk, so no amount of output budget makes them safe. An internally
447 * converted image can provide its original source size when the intermediate
448 * format expands beyond that ceiling.
449 */
450export async function compressImageToByteLimit(
451 file: File,
452 maxBytes: number,
453 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
454): Promise<CompressImageFileResult> {
455 if (file.size <= maxBytes) {
456 return { ok: true, file, recompressed: false };
457 }
458 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
459 return { ok: false, reason: "too-large" };
460 }
461 // The re-encode loop budgets in data-URL characters. Base64 turns 3 bytes
462 // into 4 chars; flooring keeps the budget a hair conservative instead of
463 // admitting an encoding right at the byte cap.
464 const budgetChars = Math.floor(maxBytes / 3) * 4;
465 const reencoded = await reencodeWithinBudget(file, budgetChars, options?.preferredMimeType);
466 if (!reencoded.ok) {
467 return reencoded;
468 }
469 return {
470 ok: true,
471 file: dataUrlToFile(
472 reencoded.dataUrl,
473 fileNameForMimeType(file.name || "image", reencoded.mimeType),
474 reencoded.mimeType,
475 ),
476 recompressed: true,
477 imageSize: reencoded.imageSize,
478 };
479}
480
481/**
482 * Converts HEIC/HEIF photos to provider-compatible JPEG before applying the
483 * attachment size limit. The decoder is loaded only when such a photo arrives.
484 */
485export async function prepareImageForAttachment(
486 file: File,
487 maxBytes: number,
488): Promise<CompressImageFileResult> {
489 if (!isHeicImageFile(file)) {
490 return compressImageToByteLimit(file, maxBytes);
491 }
492
493 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
494 return { ok: false, reason: "too-large" };
495 }
496
497 let converted: Blob;
498 try {
499 const dimensionError = await validateHeicImageDimensions(file);
500 if (dimensionError) {
501 return { ok: false, reason: dimensionError };
502 }
503 const { heicTo } = await import("heic-to/csp");
504 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
505 } catch {
506 return { ok: false, reason: "unreadable" };
507 }
508
509 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
510 type: "image/jpeg",
511 lastModified: file.lastModified,
512 });
513 const result = await compressImageToByteLimit(jpeg, maxBytes, {
514 preferredMimeType: "image/jpeg",
515 sourceSizeBytes: file.size,
516 });
517
518 return result.ok ? { ...result, recompressed: true } : result;
519}