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 * Images already within budget pass through untouched.
12 */
13
14/**
15 * Longest edge kept when an image has to be re-encoded. Sized so a typical
16 * retina screenshot (3024px wide) stays legible rather than being halved.
17 */
18const MAX_DIMENSION = 2048;
19/** Base64 budget for a single stashed image (~975KB of binary). */
20export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
21/**
22 * Ceiling on the *source* file handed to the re-encoder. File size is a
23 * proxy for pixel count, and decoding hundreds of megapixels into an
24 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
25 */
26export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
27/**
28 * Quality ladder tried in order until the encoded image fits the budget.
29 * The floor stays high enough to avoid visible blocking on UI screenshots;
30 * if even that overflows we drop resolution instead of quality.
31 */
32const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
33/** Extra downscale passes applied when even the lowest quality overflows. */
34const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
35
36export interface CompressedStashImage {
37 dataUrl: string;
38 mimeType: string;
39 sizeBytes: number;
40 /** True when the payload was re-encoded rather than stored verbatim. */
41 recompressed: boolean;
42}
43
44/**
45 * Why an image could not be compressed. Callers report these differently:
46 * "too large" is a budget outcome, "unreadable" is a decode failure.
47 */
48export type ImageCompressionFailureReason = "too-large" | "unreadable";
49
50export type CompressStashImageResult =
51 | { ok: true; image: CompressedStashImage }
52 | { ok: false; reason: ImageCompressionFailureReason };
53
54export type CompressImageFileResult =
55 | { ok: true; file: File; recompressed: boolean }
56 | { ok: false; reason: ImageCompressionFailureReason };
57
58/** Chunked so a large image can't blow the argument limit of `fromCharCode`. */
59const BASE64_CHUNK_SIZE = 0x8000;
60
61function bytesToBase64(bytes: Uint8Array): string {
62 let binary = "";
63 for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
64 binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
65 }
66 return btoa(binary);
67}
68
69/**
70 * Blob → base64 data URL. Uses `arrayBuffer()` rather than `FileReader` so
71 * the module works anywhere `Blob` does (including non-DOM test runners).
72 */
73async function blobToDataUrl(blob: File | Blob, mimeTypeOverride?: string): Promise<string> {
74 const buffer = await blob.arrayBuffer();
75 const mimeType = mimeTypeOverride || blob.type || "application/octet-stream";
76 return `data:${mimeType};base64,${bytesToBase64(new Uint8Array(buffer))}`;
77}
78
79/** Approximate decoded byte count for a base64 data URL. */
80function dataUrlByteLength(dataUrl: string): number {
81 const commaIndex = dataUrl.indexOf(",");
82 const payload = commaIndex === -1 ? dataUrl : dataUrl.slice(commaIndex + 1);
83 const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
84 return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);
85}
86
87/** Base64 payload of a data URL decoded back into a `File`. */
88function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
89 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
90 const binary = atob(payload);
91 const bytes = new Uint8Array(binary.length);
92 for (let index = 0; index < binary.length; index += 1) {
93 bytes[index] = binary.charCodeAt(index);
94 }
95 return new File([bytes], name, { type: mimeType });
96}
97
98/**
99 * Re-encoding changes the container, so a name like `shot.png` would lie
100 * about its contents. Swap the extension to match the encoded mime type.
101 */
102function fileNameForMimeType(name: string, mimeType: string): string {
103 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
104 const dotIndex = name.lastIndexOf(".");
105 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
106 return `${base}${extension}`;
107}
108
109function canRecompress(): boolean {
110 return (
111 typeof createImageBitmap === "function" &&
112 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
113 );
114}
115
116interface Canvas2D {
117 canvas: OffscreenCanvas | HTMLCanvasElement;
118 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
119}
120
121function createCanvas(width: number, height: number): Canvas2D | null {
122 if (typeof OffscreenCanvas === "function") {
123 const canvas = new OffscreenCanvas(width, height);
124 const context = canvas.getContext("2d");
125 if (!context) return null;
126 return { canvas, context };
127 }
128 if (typeof document === "undefined") return null;
129 const canvas = document.createElement("canvas");
130 canvas.width = width;
131 canvas.height = height;
132 const context = canvas.getContext("2d");
133 if (!context) return null;
134 return { canvas, context };
135}
136
137/**
138 * WebP is preferred: at matched visual quality it lands roughly 25-35%
139 * smaller than JPEG, so the same budget buys more resolution and detail —
140 * and it keeps alpha, so screenshots with transparency survive intact.
141 * Browsers that can't encode it silently fall back to JPEG.
142 */
143async function encodeToDataUrl(
144 canvas: OffscreenCanvas | HTMLCanvasElement,
145 quality: number,
146 mimeType: string,
147): Promise<{ dataUrl: string; mimeType: string } | null> {
148 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
149 const dataUrl = canvas.toDataURL(mimeType, quality);
150 // toDataURL silently returns a PNG when the requested type is unsupported.
151 if (!dataUrl.startsWith(`data:${mimeType}`)) return null;
152 return { dataUrl, mimeType };
153 }
154 const blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
155 if (blob.type && blob.type !== mimeType) return null;
156 return { dataUrl: await blobToDataUrl(blob, mimeType), mimeType };
157}
158
159/**
160 * Draws `bitmap` scaled to fit `maxDimension` and encodes it, stepping
161 * quality down until the data URL fits `budgetChars`. Returns the smallest
162 * encoding produced, even if it still exceeds the budget, so the caller can
163 * decide whether to keep or drop it.
164 */
165async function encodeWithinBudget(
166 bitmap: ImageBitmap,
167 maxDimension: number,
168 budgetChars: number,
169): Promise<{ dataUrl: string; mimeType: string } | null> {
170 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
171 const width = Math.max(1, Math.round(bitmap.width * scale));
172 const height = Math.max(1, Math.round(bitmap.height * scale));
173 const target = createCanvas(width, height);
174 if (!target) return null;
175
176 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
177 // happen before drawing and depends on which codec we end up using.
178 const probe = await encodeToDataUrl(target.canvas, QUALITY_STEPS[0], "image/webp");
179 const mimeType = probe ? "image/webp" : "image/jpeg";
180
181 if (mimeType === "image/jpeg") {
182 target.context.fillStyle = "#ffffff";
183 target.context.fillRect(0, 0, width, height);
184 }
185 target.context.drawImage(bitmap, 0, 0, width, height);
186
187 let smallest: { dataUrl: string; mimeType: string } | null = null;
188 for (const quality of QUALITY_STEPS) {
189 const encoded = await encodeToDataUrl(target.canvas, quality, mimeType);
190 if (!encoded) break;
191 if (smallest === null || encoded.dataUrl.length < smallest.dataUrl.length) {
192 smallest = encoded;
193 }
194 if (encoded.dataUrl.length <= budgetChars) {
195 return encoded;
196 }
197 }
198 return smallest;
199}
200
201type ReencodeResult =
202 | { ok: true; dataUrl: string; mimeType: string }
203 | { ok: false; reason: ImageCompressionFailureReason };
204
205/**
206 * Shared re-encode loop: decodes `file`, then walks the quality ladder and
207 * fallback downscale passes until an encoding fits `budgetChars`.
208 */
209async function reencodeWithinBudget(file: File, budgetChars: number): Promise<ReencodeResult> {
210 if (!canRecompress()) {
211 return { ok: false, reason: "too-large" };
212 }
213
214 let bitmap: ImageBitmap;
215 try {
216 bitmap = await createImageBitmap(file);
217 } catch {
218 return { ok: false, reason: "unreadable" };
219 }
220
221 try {
222 // Each pass shrinks relative to the *previous target*, capped by
223 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
224 // images already smaller than that ceiling — the fallback passes would
225 // all resolve to the source size and never actually reduce resolution.
226 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
227 // Tracks whether the *last* attempt threw, so a run of encoder failures
228 // is reported as unreadable while a run of merely-too-big results is
229 // reported as too-large.
230 let encodeFailed = false;
231 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
232 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
233 let encoded: { dataUrl: string; mimeType: string } | null;
234 try {
235 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars);
236 } catch {
237 // Canvas allocation, drawing, or the codec itself can throw — often
238 // precisely *because* the target is too big (OOM on a large bitmap).
239 // Keep trying the smaller fallback scales rather than giving up: a
240 // reduced pass may well succeed. The exception must never escape,
241 // though, since callers finalize state after this returns and a
242 // throw would strand it (e.g. a stash entry stuck "still saving").
243 encodeFailed = true;
244 continue;
245 }
246 encodeFailed = false;
247 if (encoded && encoded.dataUrl.length <= budgetChars) {
248 return { ok: true, dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
249 }
250 }
251 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
252 } finally {
253 bitmap.close();
254 }
255}
256
257/**
258 * Produces the payload to persist for a stashed image.
259 *
260 * Small images are stored verbatim (preserving PNG transparency and exact
261 * pixels). Anything over budget is downscaled and re-encoded; if it still
262 * doesn't fit after the fallback passes, reports a failure so the caller
263 * can record it as dropped.
264 */
265export async function compressImageForStash(
266 file: File,
267 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
268): Promise<CompressStashImageResult> {
269 let originalDataUrl: string;
270 try {
271 originalDataUrl = await blobToDataUrl(file);
272 } catch {
273 return { ok: false, reason: "unreadable" };
274 }
275 if (originalDataUrl.length <= budgetChars) {
276 return {
277 ok: true,
278 image: {
279 dataUrl: originalDataUrl,
280 mimeType: file.type,
281 sizeBytes: file.size,
282 recompressed: false,
283 },
284 };
285 }
286 const reencoded = await reencodeWithinBudget(file, budgetChars);
287 if (!reencoded.ok) {
288 return reencoded;
289 }
290 return {
291 ok: true,
292 image: {
293 dataUrl: reencoded.dataUrl,
294 mimeType: reencoded.mimeType,
295 sizeBytes: dataUrlByteLength(reencoded.dataUrl),
296 recompressed: true,
297 },
298 };
299}
300
301/**
302 * Shrinks `file` until its binary size fits `maxBytes`, returning a new
303 * `File` (WebP or JPEG). Files already within the limit pass through
304 * untouched, preserving their exact bytes and format. Sources above
305 * `MAX_COMPRESSIBLE_SOURCE_BYTES` are refused outright — decoding them is
306 * the risk, so no amount of output budget makes them safe.
307 */
308export async function compressImageToByteLimit(
309 file: File,
310 maxBytes: number,
311): Promise<CompressImageFileResult> {
312 if (file.size <= maxBytes) {
313 return { ok: true, file, recompressed: false };
314 }
315 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
316 return { ok: false, reason: "too-large" };
317 }
318 // The re-encode loop budgets in data-URL characters. Base64 turns 3 bytes
319 // into 4 chars; flooring keeps the budget a hair conservative instead of
320 // admitting an encoding right at the byte cap.
321 const budgetChars = Math.floor(maxBytes / 3) * 4;
322 const reencoded = await reencodeWithinBudget(file, budgetChars);
323 if (!reencoded.ok) {
324 return reencoded;
325 }
326 return {
327 ok: true,
328 file: dataUrlToFile(
329 reencoded.dataUrl,
330 fileNameForMimeType(file.name || "image", reencoded.mimeType),
331 reencoded.mimeType,
332 ),
333 recompressed: true,
334 };
335}