Open History to see the last commit
1/**
2 * Re-encoding for stashed image attachments.
3 *
4 * The composer accepts images up to `PROVIDER_SEND_TURN_MAX_IMAGE_BYTES`
5 * (10MB), but the stash persists them as base64 in localStorage, where the
6 * whole origin shares a ~5MB quota. Rather than refuse large screenshots,
7 * downscale + re-encode them to JPEG so a stashed prompt keeps its images.
8 *
9 * Only the *stashed copy* is compressed; the live composer attachment is
10 * untouched, so sending without stashing still uploads the original file.
11 */
12
13/**
14 * Longest edge kept when an image has to be re-encoded. Sized so a typical
15 * retina screenshot (3024px wide) stays legible rather than being halved.
16 */
17const MAX_DIMENSION = 2048;
18/** Base64 budget for a single stashed image (~975KB of binary). */
19export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
20/**
21 * Quality ladder tried in order until the encoded image fits the budget.
22 * The floor stays high enough to avoid visible blocking on UI screenshots;
23 * if even that overflows we drop resolution instead of quality.
24 */
25const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
26/** Extra downscale passes applied when even the lowest quality overflows. */
27const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
28
29export interface CompressedStashImage {
30 dataUrl: string;
31 mimeType: string;
32 sizeBytes: number;
33 /** True when the payload was re-encoded rather than stored verbatim. */
34 recompressed: boolean;
35}
36
37/**
38 * Why an image could not be stashed. Callers report these differently:
39 * "too large" is a budget outcome, "unreadable" is a decode failure.
40 */
41export type StashImageFailureReason = "too-large" | "unreadable";
42
43export type CompressStashImageResult =
44 | { ok: true; image: CompressedStashImage }
45 | { ok: false; reason: StashImageFailureReason };
46
47/** Chunked so a large image can't blow the argument limit of `fromCharCode`. */
48const BASE64_CHUNK_SIZE = 0x8000;
49
50function bytesToBase64(bytes: Uint8Array): string {
51 let binary = "";
52 for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
53 binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
54 }
55 return btoa(binary);
56}
57
58/**
59 * Blob → base64 data URL. Uses `arrayBuffer()` rather than `FileReader` so
60 * the module works anywhere `Blob` does (including non-DOM test runners).
61 */
62async function blobToDataUrl(blob: File | Blob, mimeTypeOverride?: string): Promise<string> {
63 const buffer = await blob.arrayBuffer();
64 const mimeType = mimeTypeOverride || blob.type || "application/octet-stream";
65 return `data:${mimeType};base64,${bytesToBase64(new Uint8Array(buffer))}`;
66}
67
68/** Approximate decoded byte count for a base64 data URL. */
69function dataUrlByteLength(dataUrl: string): number {
70 const commaIndex = dataUrl.indexOf(",");
71 const payload = commaIndex === -1 ? dataUrl : dataUrl.slice(commaIndex + 1);
72 const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
73 return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);
74}
75
76function canRecompress(): boolean {
77 return (
78 typeof createImageBitmap === "function" &&
79 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
80 );
81}
82
83interface Canvas2D {
84 canvas: OffscreenCanvas | HTMLCanvasElement;
85 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
86}
87
88function createCanvas(width: number, height: number): Canvas2D | null {
89 if (typeof OffscreenCanvas === "function") {
90 const canvas = new OffscreenCanvas(width, height);
91 const context = canvas.getContext("2d");
92 if (!context) return null;
93 return { canvas, context };
94 }
95 if (typeof document === "undefined") return null;
96 const canvas = document.createElement("canvas");
97 canvas.width = width;
98 canvas.height = height;
99 const context = canvas.getContext("2d");
100 if (!context) return null;
101 return { canvas, context };
102}
103
104/**
105 * WebP is preferred: at matched visual quality it lands roughly 25-35%
106 * smaller than JPEG, so the same budget buys more resolution and detail —
107 * and it keeps alpha, so screenshots with transparency survive intact.
108 * Browsers that can't encode it silently fall back to JPEG.
109 */
110async function encodeToDataUrl(
111 canvas: OffscreenCanvas | HTMLCanvasElement,
112 quality: number,
113 mimeType: string,
114): Promise<{ dataUrl: string; mimeType: string } | null> {
115 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
116 const dataUrl = canvas.toDataURL(mimeType, quality);
117 // toDataURL silently returns a PNG when the requested type is unsupported.
118 if (!dataUrl.startsWith(`data:${mimeType}`)) return null;
119 return { dataUrl, mimeType };
120 }
121 const blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
122 if (blob.type && blob.type !== mimeType) return null;
123 return { dataUrl: await blobToDataUrl(blob, mimeType), mimeType };
124}
125
126/**
127 * Draws `bitmap` scaled to fit `maxDimension` and encodes it as JPEG,
128 * stepping quality down until the data URL fits `budgetChars`. Returns the
129 * smallest encoding produced, even if it still exceeds the budget, so the
130 * caller can decide whether to keep or drop it.
131 */
132async function encodeWithinBudget(
133 bitmap: ImageBitmap,
134 maxDimension: number,
135 budgetChars: number,
136): Promise<{ dataUrl: string; mimeType: string } | null> {
137 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
138 const width = Math.max(1, Math.round(bitmap.width * scale));
139 const height = Math.max(1, Math.round(bitmap.height * scale));
140 const target = createCanvas(width, height);
141 if (!target) return null;
142
143 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
144 // happen before drawing and depends on which codec we end up using.
145 const probe = await encodeToDataUrl(target.canvas, QUALITY_STEPS[0], "image/webp");
146 const mimeType = probe ? "image/webp" : "image/jpeg";
147
148 if (mimeType === "image/jpeg") {
149 target.context.fillStyle = "#ffffff";
150 target.context.fillRect(0, 0, width, height);
151 }
152 target.context.drawImage(bitmap, 0, 0, width, height);
153
154 let smallest: { dataUrl: string; mimeType: string } | null = null;
155 for (const quality of QUALITY_STEPS) {
156 const encoded = await encodeToDataUrl(target.canvas, quality, mimeType);
157 if (!encoded) break;
158 if (smallest === null || encoded.dataUrl.length < smallest.dataUrl.length) {
159 smallest = encoded;
160 }
161 if (encoded.dataUrl.length <= budgetChars) {
162 return encoded;
163 }
164 }
165 return smallest;
166}
167
168/**
169 * Produces the payload to persist for a stashed image.
170 *
171 * Small images are stored verbatim (preserving PNG transparency and exact
172 * pixels). Anything over budget is downscaled and JPEG-encoded; if it still
173 * doesn't fit after the fallback passes, returns `null` so the caller can
174 * record it as dropped.
175 */
176export async function compressImageForStash(
177 file: File,
178 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
179): Promise<CompressStashImageResult> {
180 let originalDataUrl: string;
181 try {
182 originalDataUrl = await blobToDataUrl(file);
183 } catch {
184 return { ok: false, reason: "unreadable" };
185 }
186 if (originalDataUrl.length <= budgetChars) {
187 return {
188 ok: true,
189 image: {
190 dataUrl: originalDataUrl,
191 mimeType: file.type,
192 sizeBytes: file.size,
193 recompressed: false,
194 },
195 };
196 }
197 if (!canRecompress()) {
198 return { ok: false, reason: "too-large" };
199 }
200
201 let bitmap: ImageBitmap;
202 try {
203 bitmap = await createImageBitmap(file);
204 } catch {
205 return { ok: false, reason: "unreadable" };
206 }
207
208 try {
209 // Each pass shrinks relative to the *previous target*, capped by
210 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
211 // images already smaller than that ceiling — the fallback passes would
212 // all resolve to the source size and never actually reduce resolution.
213 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
214 // Tracks whether the *last* attempt threw, so a run of encoder failures
215 // is reported as unreadable while a run of merely-too-big results is
216 // reported as too-large.
217 let encodeFailed = false;
218 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
219 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
220 let encoded: { dataUrl: string; mimeType: string } | null;
221 try {
222 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars);
223 } catch {
224 // Canvas allocation, drawing, or the codec itself can throw — often
225 // precisely *because* the target is too big (OOM on a large bitmap).
226 // Keep trying the smaller fallback scales rather than giving up: a
227 // reduced pass may well succeed. The exception must never escape,
228 // though, since the caller finalizes the entry after this returns and
229 // a throw would strand it as permanently "still saving".
230 encodeFailed = true;
231 continue;
232 }
233 encodeFailed = false;
234 if (encoded && encoded.dataUrl.length <= budgetChars) {
235 return {
236 ok: true,
237 image: {
238 dataUrl: encoded.dataUrl,
239 mimeType: encoded.mimeType,
240 sizeBytes: dataUrlByteLength(encoded.dataUrl),
241 recompressed: true,
242 },
243 };
244 }
245 }
246 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
247 } finally {
248 bitmap.close();
249 }
250}