The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 11:00 UTC
fix(web): keep distinct images with matching attachment metadata (#37116)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 15, 2026 at 10:40 UTC
7d9c365e173f2fcbe9e47feadc98c565370520e0
14 files changed
+244
-51
apps/mobile/src/state/use-composer-drafts.test.ts
+20
@@ -1120,6 +1120,26 @@ describe("mobile composer drafts", () => {
1120
1121
appendComposerDraftAttachments(draftKey, [makeVideo("restored")], { restore: true });
1122
expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(2);
1123
+
1124
+ // Every native paste is named pasted-image.png, so only the bytes tell two pastes apart.
1125
+ const makePaste = (id: string, base64: string) => ({
1126
+ id,
1127
+ type: "image" as const,
1128
+ name: "pasted-image.png",
1129
+ mimeType: "image/png",
1130
+ sizeBytes: 3,
1131
+ dataUrl: `data:image/png;base64,${base64}`,
1132
+ previewUri: `data:image/png;base64,${base64}`,
1133
+ });
1134
+ const pasteKey = "new-task:environment-1:project-pastes";
1135
+ appendComposerDraftAttachments(pasteKey, [makePaste("red", "AQID")]);
1136
+ appendComposerDraftAttachments(pasteKey, [
1137
+ makePaste("blue", "BAUG"),
1138
+ makePaste("red-2", "AQID"),
1139
+ ]);
1140
+ expect(
1141
+ appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id),
1142
+ ).toEqual(["red", "blue"]);
1143
});
1144
1145
it("keeps shared attachment files until every draft releases them", async () => {
apps/mobile/src/state/use-composer-drafts.ts
+11
-6
@@ -1412,8 +1412,14 @@ export function appendComposerDraftText(draftKey: string, value: string): void {
1412
});
1413
}
1414
1415
-function attachmentDedupKey(attachment: DraftComposerAttachment): string {
1416
- return `${attachment.mimeType}\u0000${attachment.sizeBytes}\u0000${attachment.name}`;
1415
+// Pasted images all share one name, so an image's inline bytes decide whether it is a repeat.
1416
+function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment): boolean {
1417
+ return (
1418
+ a.mimeType === b.mimeType &&
1419
+ a.sizeBytes === b.sizeBytes &&
1420
+ a.name === b.name &&
1421
+ (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl)
1422
+ );
1423
}
1424
1425
/**
@@ -1441,13 +1447,12 @@ export function appendComposerDraftAttachments(
1447
const retained = options?.appendReference
1448
? draftWithoutInsertionSelection(draftKey, existing, options.insertion)
1449
: existing;
1444
- const keys = new Set(retained.attachments.map(attachmentDedupKey));
1450
+ const seen = [...retained.attachments];
1451
const attachments = options?.restore
1452
? incoming
1453
: incoming.filter((attachment) => {
1448
- const key = attachmentDedupKey(attachment);
1449
- if (keys.has(key)) return false;
1450
- keys.add(key);
1454
+ if (seen.some((other) => isSameAttachment(other, attachment))) return false;
1455
+ seen.push(attachment);
1456
return true;
1457
});
1458
duplicates = incoming.filter((attachment) => !attachments.includes(attachment));
apps/web/src/components/ChatView.logic.test.ts
+58
-1
@@ -1,4 +1,5 @@
1
import {
2
+ prepareRevertedMessageAttachments,
3
boundAttachmentIds,
4
buildExpiredTerminalContextToastCopy,
5
mergeDirectPreviewAnnotation,
@@ -40,11 +41,12 @@ import {
41
import * as DateTime from "effect/DateTime";
42
import * as Option from "effect/Option";
43
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
43
-import { Atom } from "effect/reactivity";
44
+import { AsyncResult, Atom } from "effect/reactivity";
45
import { appAtomRegistry } from "../rpc/atomRegistry";
46
import { environmentThreadDetails } from "../state/threads";
47
48
import type { Thread } from "../types";
49
+import { DraftId, hydrateImagesFromPersisted, useComposerDraftStore } from "../composerDraftStore";
50
import { derivePhase } from "../session-logic";
51
import { makeThreadFixture, makeThreadProjectionFixture } from "../test-fixtures";
52
import {
@@ -1499,3 +1501,58 @@ describe("deriveThreadPendingBackgroundTasks", () => {
1501
).toEqual([{ taskId: "task-1", kind: "background_task" }]);
1502
});
1503
});
1504
+
1505
+describe("prepareRevertedMessageAttachments", () => {
1506
+ it("suppresses a repeated image after restoring a rewound message", async () => {
1507
+ using _fetch = vi
1508
+ .spyOn(globalThis, "fetch")
1509
+ .mockResolvedValue(new Response(new Uint8Array([1, 2, 3])));
1510
+ const [file] = await prepareRevertedMessageAttachments({
1511
+ message: {
1512
+ id: MessageId.make("rewound"),
1513
+ role: "user",
1514
+ text: "",
1515
+ runId: null,
1516
+ streaming: false,
1517
+ createdAt: now,
1518
+ updatedAt: now,
1519
+ attachments: [
1520
+ { type: "image", id: "restored", name: "image.png", mimeType: "image/png", sizeBytes: 3 },
1521
+ ],
1522
+ },
1523
+ environmentId: EnvironmentId.make("rewind-images"),
1524
+ httpBaseUrl: "http://localhost",
1525
+ createAssetUrl: async () =>
1526
+ AsyncResult.success({ relativeUrl: "/attachment/image.png", expiresAt: 0 }),
1527
+ });
1528
+ const target = DraftId.make("rewind-image-repeat");
1529
+ const store = useComposerDraftStore.getState();
1530
+ using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
1531
+ store.addImages(
1532
+ target,
1533
+ [
1534
+ {
1535
+ type: "image",
1536
+ id: "restored",
1537
+ name: file!.name,
1538
+ mimeType: file!.type,
1539
+ sizeBytes: file!.size,
1540
+ file: file!,
1541
+ previewUrl: "data:image/png;base64,AQID",
1542
+ },
1543
+ ],
1544
+ { allowDuplicates: true },
1545
+ );
1546
+ const repeat = hydrateImagesFromPersisted([
1547
+ {
1548
+ id: "repeat",
1549
+ name: "image.png",
1550
+ mimeType: "image/png",
1551
+ sizeBytes: 3,
1552
+ dataUrl: "data:image/png;base64,AQID",
1553
+ },
1554
+ ]);
1555
+ expect(store.addImages(target, repeat)).toEqual([]);
1556
+ expect(store.getComposerDraft(target)?.images.map(({ id }) => id)).toEqual(["restored"]);
1557
+ });
1558
+});
apps/web/src/components/ChatView.logic.ts
+6
-1
@@ -52,6 +52,7 @@ import {
52
squashAtomCommandFailure,
53
type AtomCommandResult,
54
} from "@t3tools/client-runtime/state/runtime";
55
+import { readComposerImageBytes } from "./chat/composerAttachmentFiles";
56
import { videoMimeType } from "@t3tools/shared/video";
57
import {
58
appendCodexArtifactTemplateUsePrompt,
@@ -653,7 +654,11 @@ export async function prepareRevertedMessageAttachments(input: {
654
if (url === null) throw new Error("The environment returned an invalid attachment URL.");
655
const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
656
if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
656
- return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
657
+ const file = new File([await response.blob()], attachment.name, {
658
+ type: attachment.mimeType,
659
+ });
660
+ if (attachment.type === "image") await readComposerImageBytes(file);
661
+ return file;
662
}),
663
);
664
}
apps/web/src/components/chat/composerAttachmentFiles.ts
+53
-3
@@ -61,21 +61,71 @@ export function normalizeComposerImageFileMimeType(file: File): File {
61
});
62
}
63
64
-export function composerImageDedupKey(
64
+function composerImageSignature(
65
image: Pick<ComposerImageAttachment, "mimeType" | "sizeBytes" | "name">,
66
): string {
67
// Hydrated images get fresh lastModified values, so exclude it from dedupe.
68
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
69
}
70
71
+// Byte hashes by file; a file whose bytes were never read gets a key that matches only itself.
72
+const composerImageFingerprints = new WeakMap<File, string>();
73
+let unreadComposerImageCount = 0;
74
+
75
+function composerImageFingerprint(file: File): string {
76
+ let fingerprint = composerImageFingerprints.get(file);
77
+ if (fingerprint === undefined) {
78
+ fingerprint = `unread:${unreadComposerImageCount++}`;
79
+ composerImageFingerprints.set(file, fingerprint);
80
+ }
81
+ return fingerprint;
82
+}
83
+
84
+/** Records the bytes behind an image file, so a draft drops it only as a byte-for-byte repeat. */
85
+export function rememberComposerImageBytes(file: File, bytes: Uint8Array): void {
86
+ // cyrb53, synchronous: crypto.subtle is missing on plain-http remote origins.
87
+ let first = 0xdeadbeef;
88
+ let second = 0x41c6ce57;
89
+ for (let index = 0; index < bytes.length; index++) {
90
+ const byte = bytes[index]!;
91
+ first = Math.imul(first ^ byte, 2654435761);
92
+ second = Math.imul(second ^ byte, 1597334677);
93
+ }
94
+ first = Math.imul(first ^ (first >>> 16), 2246822507);
95
+ first ^= Math.imul(second ^ (second >>> 13), 3266489909);
96
+ second = Math.imul(second ^ (second >>> 16), 2246822507);
97
+ second ^= Math.imul(first ^ (first >>> 13), 3266489909);
98
+ composerImageFingerprints.set(file, `${second >>> 0}:${first >>> 0}`);
99
+}
100
+
101
+export async function readComposerImageBytes(file: File): Promise<void> {
102
+ // An unreadable file keeps matching only itself.
103
+ const bytes = await file.arrayBuffer().catch(() => null);
104
+ if (bytes) rememberComposerImageBytes(file, new Uint8Array(bytes));
105
+}
106
+
107
+/**
108
+ * Matches name, type, size and bytes; unread files match only themselves.
109
+ * Producers must await readComposerImageBytes before publishing images to the draft.
110
+ */
111
+export function composerImageDedupKey(
112
+ image: Pick<ComposerImageAttachment, "mimeType" | "sizeBytes" | "name" | "file">,
113
+): string {
114
+ return `${composerImageSignature(image)}\u0000${composerImageFingerprint(image.file)}`;
115
+}
116
+
117
// Compression changes an image's bytes, so a compressed image answers for the file it came from.
118
const composerImageSourceKeys = new WeakMap<File, string>();
119
74
-/** The draft store's image dedupe key, taken from the file as pasted rather than as compressed. */
120
+/** A pasted image's name, type and size: a guess, before its bytes are read, that the draft has it. */
121
export function composerImageSourceKey(file: File): string {
122
return (
123
composerImageSourceKeys.get(file) ??
78
- composerImageDedupKey({ mimeType: file.type, sizeBytes: file.size, name: file.name || "image" })
124
+ composerImageSignature({
125
+ mimeType: file.type,
126
+ sizeBytes: file.size,
127
+ name: file.name || "image",
128
+ })
129
);
130
}
131
apps/web/src/components/chat/useComposerAttachmentIntake.ts
+2
@@ -29,6 +29,7 @@ import {
29
classifyComposerAttachmentFile,
30
composerFileAttachmentMimeType,
31
composerImageSourceKey,
32
+ readComposerImageBytes,
33
normalizeComposerImageFileMimeType,
34
rememberComposerImageSource,
35
} from "./composerAttachmentFiles";
@@ -290,6 +291,7 @@ export function useComposerAttachmentIntake(input: {
291
continue;
292
}
293
await inheritComposerImageThumbnail(file, result.file);
294
+ await readComposerImageBytes(result.file);
295
rememberComposerImageSource(file, result.file);
296
compressed.push({ id, file: result.file });
297
}
apps/web/src/components/chat/useComposerContextImport.ts
+3
-1
@@ -43,6 +43,7 @@ import { collectInlineContextIds } from "../../lib/composerContextReferences";
43
import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
44
import { orchestrationEnvironment } from "~/state/orchestration";
45
import { pendingDraftWork } from "./pendingDraftWork";
46
+import { readComposerImageBytes } from "./composerAttachmentFiles";
47
import { randomUUID } from "~/lib/utils";
48
import { readPreparedConnection } from "~/state/session";
49
import { resolveAssetUrl } from "~/assets/assetUrls";
@@ -194,6 +195,8 @@ export function useComposerContextImport(input: {
195
fail("Downloading it from the source failed.");
196
return;
197
}
198
+ file = new File([blob], record.name, { type: record.mimeType || blob.type });
199
+ if (record.kind === "image") await readComposerImageBytes(file);
200
// Question attachments have no inline reference; annotations can own their screenshots.
201
const references = new Set(collectInlineContextIds(promptRef.current));
202
if (
@@ -208,7 +211,6 @@ export function useComposerContextImport(input: {
211
)
212
)
213
return;
211
- file = new File([blob], record.name, { type: record.mimeType || blob.type });
214
}
215
// The draft these bytes belong to may have been sent or switched away from while they
216
// downloaded. Dropping them here keeps them out of whatever draft is open now.
apps/web/src/components/chat/useComposerStash.ts
+10
-17
@@ -49,6 +49,7 @@ import {
49
verifyStashedAttachmentUpload,
50
} from "../../lib/attachmentUploadQueue";
51
import { remainingComposerAttachmentSlots } from "./composerThreadImport";
52
+import { composerImageDedupKey } from "./composerAttachmentFiles";
53
import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
54
import { resizeSnapShotSource } from "../../lib/snapShotSource";
55
import { registerCommands } from "../../shortcuts/dispatcher";
@@ -387,28 +388,20 @@ export function useComposerStash(input: {
388
if (entry.attachments.length > 0) {
389
const attachmentDraft = readAttachmentDraft();
390
const existingIds = new Set(attachmentDraft.images.map((image) => image.id));
390
- // The draft store also dedupes by mimeType+sizeBytes+name, so filter
391
- // on the same key here. Counting a duplicate against capacity would
392
- // burn a slot the store then refuses to fill, pushing a genuinely
393
- // unique image into the overflow list for nothing.
394
- const existingDedupKeys = new Set(
395
- attachmentDraft.images.map(
396
- (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
397
- ),
398
- );
391
+ // Filter on the draft store's dedupe key here. Counting a duplicate
392
+ // against capacity would burn a slot the store then refuses to fill,
393
+ // pushing a genuinely unique image into the overflow list for nothing.
394
+ const existingDedupKeys = new Set(attachmentDraft.images.map(composerImageDedupKey));
395
const capacity = remainingComposerAttachmentSlots(
396
attachmentDraft.images.length + attachmentDraft.files.length + restoredFileCount,
397
pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
398
);
403
- const pending = entry.attachments.filter(
404
- (attachment) =>
405
- !existingIds.has(attachment.id) &&
406
- !existingDedupKeys.has(
407
- `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
408
- ),
399
+ const pending = hydrateImagesFromPersisted(entry.attachments).filter(
400
+ (image) =>
401
+ !existingIds.has(image.id) && !existingDedupKeys.has(composerImageDedupKey(image)),
402
);
410
- unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
411
- const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
403
+ unrestoredImageNames = pending.slice(capacity).map((image) => image.name);
404
+ const restoredImages = pending.slice(0, capacity);
405
if (restoredImages.length > 0) {
406
addComposerDraftImages(composerDraftTarget, restoredImages);
407
}
apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
+8
-1
@@ -2,7 +2,11 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environ
2
import { type DesktopBridge, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3
import { describe, expect, it, vi } from "vite-plus/test";
4
5
-import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
5
+import {
6
+ DraftId,
7
+ hydrateImagesFromPersisted,
8
+ useComposerDraftStore,
9
+} from "../../composerDraftStore";
10
import * as imageCompression from "../../lib/imageCompression";
11
import {
12
questionAttachmentDraftId,
@@ -142,6 +146,9 @@ describe("open question delivery", () => {
146
expect(store.getComposerDraft(first)?.images.map(({ id }) => id)).toEqual([capture.id]);
147
expect(store.getComposerDraft(threadRef)?.images ?? []).toHaveLength(0);
148
expect(acknowledgeSnapShot).toHaveBeenCalledExactlyOnceWith(capture.id);
149
+ const repeat = hydrateImagesFromPersisted([{ ...capture, id: "repeat" }]);
150
+ expect(store.addImages(first, repeat)).toEqual([]);
151
+ expect(store.getComposerDraft(first)?.images.map(({ id }) => id)).toEqual([capture.id]);
152
} finally {
153
untrack();
154
}
apps/web/src/components/desktop/SnapShotCoordinator.tsx
+2
@@ -41,6 +41,7 @@ import {
41
openQuestionAttachmentDraft,
42
} from "../../questionAttachments";
43
import { stackedThreadToast, toastManager } from "../ui/toast";
44
+import { readComposerImageBytes } from "../chat/composerAttachmentFiles";
45
46
type CaptureTarget = DraftId | ScopedThreadRef;
47
type CaptureFailure = "missing-project" | "delivery";
@@ -173,6 +174,7 @@ export async function deliverSnapShot(
174
throw new Error("The captured window is too large to attach.");
175
}
176
const file = compressed.file;
177
+ await readComposerImageBytes(file);
178
const source = resizeSnapShotSource(capture.source, compressed.imageSize);
179
const dataUrl = compressed.recompressed ? await readFileAsDataUrl(file) : capture.dataUrl;
180
const target = resolveTarget();
apps/web/src/components/preview/PreviewView.tsx
+2
@@ -35,6 +35,7 @@ import {
35
} from "~/browserHistoryStore";
36
import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
37
import { capturePreviewAnnotationScreenshot } from "~/lib/previewAnnotation";
38
+import { readComposerImageBytes } from "../chat/composerAttachmentFiles";
39
import { ensureLocalApi } from "~/localApi";
40
import { getClientSettings } from "~/hooks/useSettings";
41
import {
@@ -859,6 +860,7 @@ export function PreviewView({
860
const capture = capturePreviewAnnotationScreenshot(picked);
861
const cropDropped = screenshotFailed || capture.status === "failed";
862
const annotation = capture.status === "failed" ? { ...picked, screenshot: null } : picked;
863
+ if (capture.status === "captured") await readComposerImageBytes(capture.file);
864
addPreviewAnnotation(threadRef, annotation);
865
if (cropDropped) {
866
toastManager.add(
apps/web/src/composerDraftStore.test.ts
+17
-19
@@ -92,6 +92,7 @@ import {
92
type ComposerFileAttachment,
93
type ComposerImageAttachment,
94
composerFileNeedsReattach,
95
+ hydrateImagesFromPersisted,
96
partializeComposerDraftStoreState,
97
useComposerDraftStore,
98
DraftId,
@@ -261,29 +262,28 @@ describe("composerDraftStore addImages", () => {
262
expect(revokeSpy).not.toHaveBeenCalled();
263
});
264
264
- it("deduplicates against existing images across calls by file signature", () => {
265
- const first = makeImage({
266
- id: "img-a",
267
- previewUrl: "blob:a",
265
+ it("deduplicates byte-identical images across calls and keeps distinct bytes", () => {
266
+ // Hydrated copies get fresh lastModified values, like a restored stash or draft.
267
+ const persisted = (id: string, fill: number) => ({
268
+ id,
269
name: "same.png",
270
mimeType: "image/png",
271
sizeBytes: 9,
271
- lastModified: 777,
272
- });
273
- const duplicateLater = makeImage({
274
- id: "img-b",
275
- previewUrl: "blob:b",
276
- name: "same.png",
277
- mimeType: "image/png",
278
- sizeBytes: 9,
279
- lastModified: 999,
272
+ dataUrl: `data:image/png;base64,${btoa(String.fromCharCode(...new Uint8Array(9).fill(fill)))}`,
273
});
274
+ const [first, repeat, different] = hydrateImagesFromPersisted([
275
+ persisted("img-a", 1),
276
+ persisted("img-b", 1),
277
+ persisted("img-c", 2),
278
+ ]);
279
+ const store = useComposerDraftStore.getState();
280
282
- expect(useComposerDraftStore.getState().addImage(threadRef, first)).toBe(true);
283
- expect(useComposerDraftStore.getState().addImage(threadRef, duplicateLater)).toBe(false);
281
+ expect(store.addImage(threadRef, first!)).toBe(true);
282
+ expect(store.addImage(threadRef, { ...repeat!, previewUrl: "blob:b" })).toBe(false);
283
+ expect(store.addImage(threadRef, different!)).toBe(true);
284
285
const draft = draftFor(threadId, TEST_ENVIRONMENT_ID);
286
- expect(draft?.images.map((image) => image.id)).toEqual(["img-a"]);
286
+ expect(draft?.images.map((image) => image.id)).toEqual(["img-a", "img-c"]);
287
expect(revokeSpy).toHaveBeenCalledWith("blob:b");
288
});
289
});
@@ -2674,9 +2674,7 @@ describe("composerDraftStore attachment references", () => {
2674
const image = makeImage({ id: "img-1", previewUrl: "blob:img-1", name: "shot.png" });
2675
expect(store.addImages(threadRef, [image])).toEqual(["img-1"]);
2676
expect(
2677
- store.addImages(threadRef, [
2678
- makeImage({ id: "img-2", previewUrl: "blob:img-2", name: "shot.png" }),
2679
- ]),
2677
+ store.addImages(threadRef, [{ ...image, id: "img-2", previewUrl: "blob:img-2" }]),
2678
).toEqual([]);
2679
});
2680
apps/web/src/composerDraftStore.ts
+8
-2
@@ -1,6 +1,7 @@
1
import {
2
composerFileAttachmentMimeType,
3
composerImageDedupKey,
4
+ rememberComposerImageBytes,
5
} from "./components/chat/composerAttachmentFiles";
6
import { elementContextToPreviewAnnotation } from "./lib/elementContext";
7
import {
@@ -2628,16 +2629,21 @@ function hydratePersistedComposerImageAttachment(
2629
header.startsWith("data:") && header.includes(";")
2630
? header.slice("data:".length, header.indexOf(";"))
2631
: attachment.mimeType;
2631
- return new File([decodedText], attachment.name, {
2632
+ const textBytes = new TextEncoder().encode(decodedText);
2633
+ const textFile = new File([textBytes], attachment.name, {
2634
type: inferredMimeType || attachment.mimeType,
2635
});
2636
+ rememberComposerImageBytes(textFile, textBytes);
2637
+ return textFile;
2638
}
2639
const binary = atob(payload);
2640
const bytes = new Uint8Array(binary.length);
2641
for (let index = 0; index < binary.length; index += 1) {
2642
bytes[index] = binary.charCodeAt(index);
2643
}
2640
- return new File([bytes], attachment.name, { type: attachment.mimeType });
2644
+ const file = new File([bytes], attachment.name, { type: attachment.mimeType });
2645
+ rememberComposerImageBytes(file, bytes);
2646
+ return file;
2647
} catch {
2648
return null;
2649
}
scripts/scenarios/distinct-same-size-pasted-images-both-attach.e2e.ts
new
+44
@@ -0,0 +1,44 @@
1
+import { expect } from "e2e";
2
+import type { Browser } from "@e2e-dev/web";
3
+
4
+import { test, WEB } from "./t3.ts";
5
+
6
+// Two 1x1 PNGs, one red and one blue, that encode to the same number of bytes.
7
+const RED_PIXEL =
8
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAD0lEQVR4AQEEAPv/AP8AAAMBAQCNHeWCAAAAAElFTkSuQmCC";
9
+const BLUE_PIXEL =
10
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAD0lEQVR4AQEEAPv/AAAA/wEDAQB8wnTbAAAAAElFTkSuQmCC";
11
+
12
+/** Pastes a PNG the way a clipboard image arrives: a new File named image.png. */
13
+const pastePng = (browser: Browser, base64: string) =>
14
+ browser.evaluate((payload: string) => {
15
+ const bytes = Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
16
+ const clipboardData = new DataTransfer();
17
+ clipboardData.items.add(new File([bytes], "image.png", { type: "image/png" }));
18
+ const editor = document.querySelector('[contenteditable="true"]');
19
+ if (!editor) throw new Error("No composer editor to paste into");
20
+ return editor.dispatchEvent(
21
+ new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
22
+ );
23
+ }, base64);
24
+
25
+test(
26
+ "Two different pasted images with the same name, type and size both attach",
27
+ WEB,
28
+ async ({ t3, app, browser, screen }) => {
29
+ const project = await t3.project("demo");
30
+ const thread = await t3.thread({ project, title: "Screenshots", messages: ["first"] });
31
+ await t3.open(thread);
32
+ await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
33
+
34
+ const composer = screen.getByRole("textbox");
35
+ await composer.fill("Compare ");
36
+ const chips = composer.getByRole("button", "Image attachment", { exact: false });
37
+
38
+ await pastePng(browser, RED_PIXEL);
39
+ await expect(chips).toHaveCount(1);
40
+ await pastePng(browser, BLUE_PIXEL);
41
+ await app.screenshot("after-second-paste");
42
+ await expect(chips).toHaveCount(2);
43
+ },
44
+);