@devries-cameron20 / t3code-1 / commits / 6f8144b5c4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): overlapping image pastes keep their prompt order (#37010)

Co-authored-by: Grok 4.7 <noreply@x.ai> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 15, 2026 at 03:01 UTC 6f8144b5c46736b1860422e5549b36c62f319254
5 files changed +153 -14
apps/web/src/components/composerAttachmentInsertion.test.ts
+33
@@ -144,3 +144,36 @@ it("keeps a pending image reference as text inside a code block", () => {
144 editor.destroy();
145 }
146 });
147 +
148 +it.each([
149 + { finishesFirst: "first", before: "Before ", after: "" },
150 + { finishesFirst: "second", before: "Before ", after: "" },
151 + { finishesFirst: "first", before: "Compare", after: " screenshots" },
152 +])(
153 + "keeps two pastes at $before|$after in paste order when the $finishesFirst image prepares first",
154 + ({ finishesFirst, before, after }) => {
155 + const editor = createEditor({
156 + type: "doc",
157 + content: [{ type: "paragraph", content: [{ type: "text", text: before + after }] }],
158 + });
159 + try {
160 + using _alive = vi.spyOn(editor, "isDestroyed", "get").mockReturnValue(false);
161 + editor.view.dispatch(
162 + editor.state.tr.setSelection(TextSelection.create(editor.state.doc, before.length + 1)),
163 + );
164 + const firstImage = { ...image, contextId: "image_first", label: "first.png" };
165 + const secondImage = { ...image, contextId: "image_second", label: "second.png" };
166 + const first = captureComposerAttachmentInsertion(editor);
167 + const second = captureComposerAttachmentInsertion(editor);
168 + if (finishesFirst === "second") expect(second.insert([secondImage])).toBe(true);
169 + expect(first.insert([firstImage])).toBe(true);
170 + if (finishesFirst === "first") expect(second.insert([secondImage])).toBe(true);
171 +
172 + expect(serializeEditorDoc(editor.state.doc).value).toBe(
173 + `${before.trimEnd()} ${formatInlineContextReference(firstImage)} ${formatInlineContextReference(secondImage)} ${after.trimStart()}`,
174 + );
175 + } finally {
176 + editor.destroy();
177 + }
178 + },
179 +);
apps/web/src/components/composerAttachmentInsertion.ts
+23 -8
@@ -13,14 +13,26 @@ import {
13 } from "../lib/composerContextReferences";
14 import { markAsClipboardEdit } from "../composer-undo-grouping";
15
16 +const INSERTION_ORDER_META = "composerAttachmentInsertionOrder";
17 +let nextInsertionOrder = 0;
18 +
19 export function captureComposerAttachmentInsertion(editor: Editor) {
20 + const order = nextInsertionOrder++;
21 let { from, to } = editor.state.selection;
22 let lost = false;
23 const track = ({ transaction, appendedTransactions }: EditorEvents["transaction"]) => {
20 - // Keep the attachment before text typed at the paste point while its image is preparing.
24 for (const tr of [transaction, ...appendedTransactions]) {
22 - const start = tr.mapping.mapResult(from, -1);
23 - const end = tr.mapping.mapResult(to, -1);
25 + // Stay before text typed at the paste point, but after an earlier capture's references.
26 + const insertion: { order: number; from: number; end: number } | undefined =
27 + tr.getMeta(INSERTION_ORDER_META);
28 + const followsEarlier = insertion !== undefined && insertion.order < order;
29 + const start = tr.mapping.mapResult(from, followsEarlier ? 1 : -1);
30 + const end = tr.mapping.mapResult(to, followsEarlier ? 1 : -1);
31 + // Replacing the following space maps its start left regardless of association.
32 + if (followsEarlier && from === to && from === insertion.from) {
33 + from = to = insertion.end;
34 + continue;
35 + }
36 // A replacement spanning the paste point (such as a controlled setContent) leaves no
37 // position to keep, so the caller falls back to the current caret.
38 lost ||= start.deletedAcross || end.deletedAcross;
@@ -56,12 +68,15 @@ export function captureComposerAttachmentInsertion(editor: Editor) {
68 ])
69 : [editor.schema.text(edit.text)];
70 if (acceptsReference && edit.text.startsWith(" ")) content.unshift(editor.schema.text(" "));
59 - const tr = editor.state.tr.replaceWith(
60 - from,
61 - flatToPm(map, markdownToFlat(map, edit.end)),
62 - content,
71 + const replaceEnd = flatToPm(map, markdownToFlat(map, edit.end));
72 + const tr = editor.state.tr.replaceWith(from, replaceEnd, content);
73 + editor.view.dispatch(
74 + markAsClipboardEdit(tr, "paste").setMeta(INSERTION_ORDER_META, {
75 + order,
76 + from,
77 + end: tr.mapping.map(replaceEnd, 1),
78 + }),
79 );
64 - editor.view.dispatch(markAsClipboardEdit(tr, "paste"));
80 return true;
81 },
82 dispose,
scripts/e2e.config.ts
+2
@@ -155,6 +155,8 @@ export default {
155 engine: web({ viewport: { width: 1280, height: 800 } }),
156 app: {
157 url: `http://${LOOPBACK}:0`,
158 + // Lets a scenario put an image on the clipboard for a real keyboard paste.
159 + permissions: { "clipboard-write": "grant" },
160 // Vite answers before the server does; this path is proxied to the server.
161 readyUrl: `http://${LOOPBACK}:{port}/.well-known/t3/environment`,
162 command: {
scripts/scenarios/image-compression-hold.ts
+33 -6
@@ -6,7 +6,10 @@ import type { Browser } from "@e2e-dev/web";
6
7 interface CompressionHold {
8 readonly release: () => void;
9 + readonly releaseNext: () => void;
10 + readonly held: Array<() => void>;
11 released: boolean;
12 + releasedDecodes: number;
13 compressionDecodes: number;
14 inFlight: number;
15 }
@@ -20,16 +23,18 @@ declare global {
23 /** Installs the hold before the app loads; call before `t3.open`. */
24 export const holdImageCompression = (browser: Browser) =>
25 browser.addInitScript(() => {
23 - let release!: () => void;
24 - const released = new Promise<void>((resolve) => {
25 - release = resolve;
26 - });
26 const hold: CompressionHold = {
27 release: () => {
28 hold.released = true;
30 - release();
29 + for (const resume of hold.held.splice(0)) resume();
30 + },
31 + releaseNext: () => {
32 + hold.releasedDecodes++;
33 + hold.held.shift()?.();
34 },
35 + held: [],
36 released: false,
37 + releasedDecodes: 0,
38 compressionDecodes: 0,
39 inFlight: 0,
40 };
@@ -48,7 +53,7 @@ export const holdImageCompression = (browser: Browser) =>
53 track(async () => {
54 // Only attachment compression decodes with an orientation; placeholder thumbnails do not.
55 if (rest[0]?.imageOrientation === undefined) return decode(source, ...rest);
51 - await released;
56 + if (!hold.released) await new Promise<void>((resume) => hold.held.push(resume));
57 const bitmap = await decode(source, ...rest);
58 hold.compressionDecodes++;
59 return bitmap;
@@ -101,3 +106,25 @@ export const finishImageCompression = async (browser: Browser) => {
106 )
107 .toBe(true);
108 };
109 +
110 +/** Waits until `count` compressions are held, in the order their images were pasted. */
111 +export const expectHeldImageCompressions = (browser: Browser, count: number) =>
112 + expect.poll(() => browser.evaluate(() => window.compressionHold!.held.length)).toBe(count);
113 +
114 +/** Lets the oldest held compression finish, keeping the rest held, and waits until it has. */
115 +export const finishNextImageCompression = async (browser: Browser) => {
116 + await browser.evaluate(() => {
117 + window.compressionHold!.releaseNext();
118 + return null;
119 + });
120 + await expect
121 + .poll(() =>
122 + browser.evaluate(() => {
123 + const hold = window.compressionHold!;
124 + return (
125 + hold.compressionDecodes === hold.releasedDecodes && hold.inFlight === hold.held.length
126 + );
127 + }),
128 + )
129 + .toBe(true);
130 +};
scripts/scenarios/overlapping-image-pastes-keep-order.e2e.ts new
+62
@@ -0,0 +1,62 @@
1 +import { expect } from "e2e";
2 +import type { Browser } from "@e2e-dev/web";
3 +
4 +import {
5 + expectHeldImageCompressions,
6 + finishNextImageCompression,
7 + holdImageCompression,
8 +} from "./image-compression-hold.ts";
9 +import { test, WEB } from "./t3.ts";
10 +
11 +/** Copies a PNG over the 2000 px limit, so pasting it compresses; noise keeps it large. */
12 +const copyWidePng = (browser: Browser, noise: boolean) =>
13 + browser.evaluate(async (noisy: boolean) => {
14 + const canvas = new OffscreenCanvas(2200, noisy ? 200 : 20);
15 + const context = canvas.getContext("2d")!;
16 + const pixels = context.createImageData(canvas.width, canvas.height);
17 + let seed = 1;
18 + for (let index = 0; index < pixels.data.length; index++) {
19 + seed ^= seed << 13;
20 + seed ^= seed >>> 17;
21 + seed ^= seed << 5;
22 + pixels.data[index] = index % 4 === 3 ? 255 : noisy ? seed & 255 : 40;
23 + }
24 + context.putImageData(pixels, 0, 0);
25 + const png = await canvas.convertToBlob({ type: "image/png" });
26 + await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);
27 + return png.size;
28 + }, noise);
29 +
30 +test(
31 + "An image pasted while an earlier pasted image prepares lands after it before a space in the prompt",
32 + WEB,
33 + async ({ t3, app, browser, screen }) => {
34 + await holdImageCompression(browser);
35 + const project = await t3.project("demo");
36 + const thread = await t3.thread({ project, title: "Screenshots", messages: ["first"] });
37 + await t3.open(thread);
38 + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
39 +
40 + const composer = screen.getByRole("textbox");
41 + await composer.fill("Compare screenshots");
42 + await browser.keyboard.press("Home");
43 + for (let index = 0; index < "Compare".length; index++) {
44 + await browser.keyboard.press("ArrowRight");
45 + }
46 + await copyWidePng(browser, false);
47 + await browser.keyboard.press("ControlOrMeta+V");
48 + await expectHeldImageCompressions(browser, 1);
49 + await copyWidePng(browser, true);
50 + await browser.keyboard.press("ControlOrMeta+V");
51 + await expectHeldImageCompressions(browser, 2);
52 +
53 + await finishNextImageCompression(browser);
54 + await finishNextImageCompression(browser);
55 + const chips = composer.getByRole("button", "Image attachment", { exact: false });
56 + await expect(chips).toHaveCount(2);
57 + await app.screenshot("both-images-prepared");
58 + // The solid image, pasted first, is the 1 KB one.
59 + await expect(chips.first()).toHaveAccessibleName("Image attachment, image.png, 1 KB");
60 + await expect(chips.nth(1)).not.toHaveAccessibleName("Image attachment, image.png, 1 KB");
61 + },
62 +);