The best way to control Claude Code, Codex and more from any computer or phone
feat(web): pasting a huge screenshot now compresses it instead of erroring (#4967)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Theo Browne committed
Jul 30, 2026 at 04:35 UTC
cbe8052020aa0c02c63fbe090e7f1f25603622d1
3 files changed
+282
-82
apps/web/src/components/chat/ChatComposer.tsx
+89
-29
@@ -64,7 +64,7 @@ import {
64
} from "../../promptStashStore";
65
import { ComposerStashBadge } from "./ComposerStashBadge";
66
import { ComposerStashMenu } from "./ComposerStashMenu";
67
-import { compressImageForStash } from "../../lib/stashImageCompression";
67
+import { compressImageForStash, compressImageToByteLimit } from "../../lib/imageCompression";
68
import { isCommandPaletteOpen } from "../../commandPaletteBus";
69
import { getTerminalFocusOwner } from "../../lib/terminalFocus";
70
import { resolveShortcutCommand } from "../../keybindings";
@@ -206,8 +206,6 @@ import { searchProviderSkills } from "../../providerSkillSearch";
206
import { useMediaQuery } from "../../hooks/useMediaQuery";
207
import type { ReviewCommentContext } from "../../reviewCommentContext";
208
209
-const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
210
-
209
const runtimeModeConfig: Record<
210
RuntimeMode,
211
{ label: string; description: string; icon: LucideIcon }
@@ -1006,6 +1004,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1004
* thread) can still be stashed while an earlier encode is running.
1005
*/
1006
const stashInFlightRef = useRef<Set<string>>(new Set());
1007
+ /**
1008
+ * Count of pasted images still being compressed, per thread. Reserved
1009
+ * against the attachment limit so concurrent pastes can't overshoot it,
1010
+ * and checked by `submitComposer` so a send can't race an image into the
1011
+ * next draft.
1012
+ */
1013
+ const pendingImageCompressionsRef = useRef<Map<ThreadId, number>>(new Map());
1014
1015
// ------------------------------------------------------------------
1016
// Derived: composer send state
@@ -1821,12 +1826,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1826
event?.preventDefault();
1827
return;
1828
}
1829
+ // A send while a pasted image is still compressing would strand that
1830
+ // image: the turn snapshot wouldn't include it, and it would surface
1831
+ // in the *next* draft instead. Only oversized images hit this — small
1832
+ // files clear the pending counter within a microtask.
1833
+ if (activeThreadId && (pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) {
1834
+ event?.preventDefault();
1835
+ toastManager.add({
1836
+ type: "info",
1837
+ title: "Still compressing a pasted image.",
1838
+ description: "Send again once its thumbnail appears.",
1839
+ });
1840
+ return;
1841
+ }
1842
onSend(event);
1843
if (shouldBlurMobileComposerOnSubmit()) {
1844
blurMobileComposerAfterSend();
1845
}
1846
},
1847
[
1848
+ activeThreadId,
1849
blurMobileComposerAfterSend,
1850
isSendDisabled,
1851
noProviderAvailable,
@@ -2273,7 +2292,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2292
// ------------------------------------------------------------------
2293
// Callbacks: images
2294
// ------------------------------------------------------------------
2276
- const addComposerImages = (files: File[]) => {
2295
+ const addComposerImages = async (files: File[]) => {
2296
if (!activeThreadId || files.length === 0) return;
2297
if (pendingUserInputs.length > 0) {
2298
toastManager.add({
@@ -2282,40 +2301,81 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2301
});
2302
return;
2303
}
2285
- const nextImages: ComposerImageAttachment[] = [];
2286
- let nextImageCount = composerImagesRef.current.length;
2304
+ // Captured before the awaits below: the user may switch threads while a
2305
+ // large image is being compressed, and the attachments and errors belong
2306
+ // to the thread the paste happened in.
2307
+ const threadId = activeThreadId;
2308
+
2309
+ // Validation happens synchronously so concurrent pastes see each other:
2310
+ // accepted files reserve their attachment slots (via the pending counter)
2311
+ // before the first await, keeping the total under the limit.
2312
+ const pendingCount = pendingImageCompressionsRef.current.get(threadId) ?? 0;
2313
+ let reservedCount = composerImagesRef.current.length + pendingCount;
2314
+ const acceptedFiles: File[] = [];
2315
let error: string | null = null;
2316
for (const file of files) {
2317
if (!file.type.startsWith("image/")) {
2318
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
2319
continue;
2320
}
2293
- if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
2294
- error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
2295
- continue;
2296
- }
2297
- if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
2321
+ if (reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
2322
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
2323
break;
2324
}
2301
- const previewUrl = URL.createObjectURL(file);
2302
- nextImages.push({
2303
- type: "image",
2304
- id: randomUUID(),
2305
- name: file.name || "image",
2306
- mimeType: file.type,
2307
- sizeBytes: file.size,
2308
- previewUrl,
2309
- file,
2310
- });
2311
- nextImageCount += 1;
2325
+ acceptedFiles.push(file);
2326
+ reservedCount += 1;
2327
}
2313
- if (nextImages.length === 1 && nextImages[0]) {
2314
- addComposerImage(nextImages[0]);
2315
- } else if (nextImages.length > 1) {
2316
- addComposerImagesToDraft(nextImages);
2328
+ setThreadError(threadId, error);
2329
+ if (acceptedFiles.length === 0) return;
2330
+
2331
+ pendingImageCompressionsRef.current.set(threadId, pendingCount + acceptedFiles.length);
2332
+ try {
2333
+ const nextImages: ComposerImageAttachment[] = [];
2334
+ let compressionError: string | null = null;
2335
+ for (const file of acceptedFiles) {
2336
+ // Images over the wire cap are downscaled to fit rather than
2337
+ // refused; files already within it pass through byte-for-byte.
2338
+ const compressed = await compressImageToByteLimit(file, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);
2339
+ if (!compressed.ok) {
2340
+ compressionError =
2341
+ compressed.reason === "unreadable"
2342
+ ? `'${file.name}' could not be read as an image.`
2343
+ : `'${file.name}' is too large to attach, even after compression.`;
2344
+ continue;
2345
+ }
2346
+ const attachmentFile = compressed.file;
2347
+ const previewUrl = URL.createObjectURL(attachmentFile);
2348
+ nextImages.push({
2349
+ type: "image",
2350
+ id: randomUUID(),
2351
+ name: attachmentFile.name || "image",
2352
+ mimeType: attachmentFile.type,
2353
+ sizeBytes: attachmentFile.size,
2354
+ previewUrl,
2355
+ file: attachmentFile,
2356
+ });
2357
+ }
2358
+ if (nextImages.length === 1 && nextImages[0]) {
2359
+ addComposerImage(nextImages[0]);
2360
+ } else if (nextImages.length > 1) {
2361
+ addComposerImagesToDraft(nextImages);
2362
+ }
2363
+ // Only failures are reported here. Success must not pass `null`: by
2364
+ // now other work (a failed send, an overlapping paste) may have set a
2365
+ // thread error this call knows nothing about, and clearing it would
2366
+ // swallow that message.
2367
+ if (compressionError !== null) {
2368
+ setThreadError(threadId, compressionError);
2369
+ }
2370
+ } finally {
2371
+ const remaining =
2372
+ (pendingImageCompressionsRef.current.get(threadId) ?? 0) - acceptedFiles.length;
2373
+ if (remaining > 0) {
2374
+ pendingImageCompressionsRef.current.set(threadId, remaining);
2375
+ } else {
2376
+ pendingImageCompressionsRef.current.delete(threadId);
2377
+ }
2378
}
2318
- setThreadError(activeThreadId, error);
2379
};
2380
2381
const removeComposerImage = (imageId: string) => {
@@ -2331,7 +2391,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2391
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
2392
if (imageFiles.length === 0) return;
2393
event.preventDefault();
2334
- addComposerImages(imageFiles);
2394
+ void addComposerImages(imageFiles);
2395
};
2396
2397
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
@@ -2365,7 +2425,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2425
dragDepthRef.current = 0;
2426
setIsDragOverComposer(false);
2427
const files = Array.from(event.dataTransfer.files);
2368
- addComposerImages(files);
2428
+ void addComposerImages(files);
2429
focusComposer();
2430
};
2431
apps/web/src/lib/imageCompression.test.ts
renamed
+56
-1
@@ -1,6 +1,11 @@
1
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3
-import { compressImageForStash, MAX_STASH_IMAGE_DATA_URL_CHARS } from "./stashImageCompression";
3
+import {
4
+ compressImageForStash,
5
+ compressImageToByteLimit,
6
+ MAX_COMPRESSIBLE_SOURCE_BYTES,
7
+ MAX_STASH_IMAGE_DATA_URL_CHARS,
8
+} from "./imageCompression";
9
10
/**
11
* jsdom has no real canvas/codec, so the re-encode path is exercised with
@@ -159,6 +164,56 @@ describe("compressImageForStash", () => {
164
});
165
});
166
167
+ it("compressImageToByteLimit passes small files through byte-for-byte", async () => {
168
+ const bitmapSpy = vi.fn();
169
+ vi.stubGlobal("createImageBitmap", bitmapSpy);
170
+
171
+ const original = makeFile(1024);
172
+ const result = await compressImageToByteLimit(original, 10 * 1024 * 1024);
173
+
174
+ expect(result.ok).toBe(true);
175
+ expect(result.ok && result.recompressed).toBe(false);
176
+ // Pass-through must be the same File object, not a copy.
177
+ expect(result.ok && result.file).toBe(original);
178
+ expect(bitmapSpy).not.toHaveBeenCalled();
179
+ });
180
+
181
+ it("compressImageToByteLimit re-encodes an oversized file under the byte cap", async () => {
182
+ stubCanvasPipeline(() => 200_000);
183
+
184
+ const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
185
+
186
+ expect(result.ok).toBe(true);
187
+ expect(result.ok && result.recompressed).toBe(true);
188
+ expect(result.ok && result.file.type).toBe("image/webp");
189
+ // The re-encoded name must match the new container format.
190
+ expect(result.ok && result.file.name).toBe("shot.webp");
191
+ expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
192
+ });
193
+
194
+ it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
195
+ const bitmapSpy = vi.fn();
196
+ vi.stubGlobal("createImageBitmap", bitmapSpy);
197
+
198
+ const result = await compressImageToByteLimit(
199
+ makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
200
+ 10 * 1024 * 1024,
201
+ );
202
+
203
+ expect(result).toEqual({ ok: false, reason: "too-large" });
204
+ // The whole point of the ceiling is to never decode such a file.
205
+ expect(bitmapSpy).not.toHaveBeenCalled();
206
+ });
207
+
208
+ it("compressImageToByteLimit reports too-large when no encoding fits", async () => {
209
+ const { close } = stubCanvasPipeline(() => 3_000_000);
210
+
211
+ const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
212
+
213
+ expect(result).toEqual({ ok: false, reason: "too-large" });
214
+ expect(close).toHaveBeenCalled();
215
+ });
216
+
217
it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
218
// A small-but-heavy source (e.g. a dense PNG): only a real downscale can
219
// get it under budget, since quality alone is stubbed to never suffice.
apps/web/src/lib/imageCompression.ts
renamed
+137
-52
@@ -1,13 +1,14 @@
1
/**
2
- * Re-encoding for stashed image attachments.
2
+ * Downscale + re-encode for image attachments that are too big for where
3
+ * they're headed. Two consumers share the same pipeline:
4
*
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.
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
*
9
- * Only the *stashed copy* is compressed; the live composer attachment is
10
- * untouched, so sending without stashing still uploads the original file.
11
+ * Images already within budget pass through untouched.
12
*/
13
14
/**
@@ -17,6 +18,12 @@
18
const MAX_DIMENSION = 2048;
19
/** Base64 budget for a single stashed image (~975KB of binary). */
20
export 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
+ */
26
+export 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;
@@ -35,14 +42,18 @@ export interface CompressedStashImage {
42
}
43
44
/**
38
- * Why an image could not be stashed. Callers report these differently:
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
*/
41
-export type StashImageFailureReason = "too-large" | "unreadable";
48
+export type ImageCompressionFailureReason = "too-large" | "unreadable";
49
50
export type CompressStashImageResult =
51
| { ok: true; image: CompressedStashImage }
45
- | { ok: false; reason: StashImageFailureReason };
52
+ | { ok: false; reason: ImageCompressionFailureReason };
53
+
54
+export 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`. */
59
const BASE64_CHUNK_SIZE = 0x8000;
@@ -73,6 +84,28 @@ function dataUrlByteLength(dataUrl: string): number {
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`. */
88
+function 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
+ */
102
+function 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
+
109
function canRecompress(): boolean {
110
return (
111
typeof createImageBitmap === "function" &&
@@ -124,10 +157,10 @@ async function encodeToDataUrl(
157
}
158
159
/**
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.
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
*/
165
async function encodeWithinBudget(
166
bitmap: ImageBitmap,
@@ -165,35 +198,15 @@ async function encodeWithinBudget(
198
return smallest;
199
}
200
201
+type ReencodeResult =
202
+ | { ok: true; dataUrl: string; mimeType: string }
203
+ | { ok: false; reason: ImageCompressionFailureReason };
204
+
205
/**
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.
206
+ * Shared re-encode loop: decodes `file`, then walks the quality ladder and
207
+ * fallback downscale passes until an encoding fits `budgetChars`.
208
*/
176
-export 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
- }
209
+async function reencodeWithinBudget(file: File, budgetChars: number): Promise<ReencodeResult> {
210
if (!canRecompress()) {
211
return { ok: false, reason: "too-large" };
212
}
@@ -225,22 +238,14 @@ export async function compressImageForStash(
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,
228
- // though, since the caller finalizes the entry after this returns and
229
- // a throw would strand it as permanently "still saving".
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) {
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
- };
248
+ return { ok: true, dataUrl: encoded.dataUrl, mimeType: encoded.mimeType };
249
}
250
}
251
return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
@@ -248,3 +253,83 @@ export async function compressImageForStash(
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
+ */
265
+export 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
+ */
308
+export 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
+}