Open History to see the last commit
1import {
2 type EnvironmentId,
3 isProviderSendTurnSupportedImageMimeType,
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5} from "@t3tools/contracts";
6import {
7 clampFileAttachmentUploadBytes,
8 fileAttachmentTooLargeMessage,
9} from "@t3tools/client-runtime/state/attachments";
10
11import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
12import { isHeicImageFile } from "../../lib/imageCompression";
13import { isVideoAttachment, videoMimeType } from "../../types";
14import { isSvgAttachment } from "@t3tools/shared/image";
15import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview";
16
17type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
18
19interface FileAttachmentCapabilityState {
20 readonly attachmentUploadsCapabilityKnown: boolean;
21 readonly supportsAttachmentUploads: boolean;
22 readonly maxFileAttachmentBytes: number | null;
23}
24
25const IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
26 gif: "image/gif",
27 jpeg: "image/jpeg",
28 jpg: "image/jpeg",
29 png: "image/png",
30 webp: "image/webp",
31};
32
33/**
34 * Some sources (drags from other apps, files piped through a shell) hand over a
35 * `File` with an empty or generic MIME type.
36 */
37function inferImageMimeTypeFromName(name: string): string | null {
38 const dotIndex = name.lastIndexOf(".");
39 if (dotIndex <= 0) {
40 return null;
41 }
42 return IMAGE_MIME_TYPE_BY_EXTENSION[name.slice(dotIndex + 1).toLowerCase()] ?? null;
43}
44
45function inferImageMimeTypeForUnknownFile(file: Pick<File, "name" | "type">): string | null {
46 const mimeType = file.type.toLowerCase();
47 if (mimeType !== "" && mimeType !== "application/octet-stream") {
48 return null;
49 }
50 return inferImageMimeTypeFromName(file.name);
51}
52
53export function normalizeComposerImageFileMimeType(file: File): File {
54 const inferredMimeType = inferImageMimeTypeForUnknownFile(file);
55 if (!inferredMimeType) {
56 return file;
57 }
58 return new File([file], file.name, {
59 type: inferredMimeType,
60 lastModified: file.lastModified,
61 });
62}
63
64function 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.
72const composerImageFingerprints = new WeakMap<File, string>();
73let unreadComposerImageCount = 0;
74
75function 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. */
85export 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
101export 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 */
111export 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.
118const composerImageSourceKeys = new WeakMap<File, string>();
119
120/** A pasted image's name, type and size: a guess, before its bytes are read, that the draft has it. */
121export function composerImageSourceKey(file: File): string {
122 return (
123 composerImageSourceKeys.get(file) ??
124 composerImageSignature({
125 mimeType: file.type,
126 sizeBytes: file.size,
127 name: file.name || "image",
128 })
129 );
130}
131
132export function rememberComposerImageSource(source: File, prepared: File): void {
133 if (prepared !== source) composerImageSourceKeys.set(prepared, composerImageSourceKey(source));
134}
135
136function isDngFile(file: Pick<File, "name" | "type">): boolean {
137 const mimeType = file.type.split(";", 1)[0]?.trim().toLowerCase();
138 return (
139 file.name.toLowerCase().endsWith(".dng") ||
140 mimeType === "image/dng" ||
141 mimeType === "image/x-dng" ||
142 mimeType === "image/x-adobe-dng"
143 );
144}
145
146export function composerFileAttachmentMimeType(file: Pick<File, "name" | "type">): string {
147 // Downstream image detection uses MIME, even for attachments staged as files.
148 if (isDngFile(file)) return "image/x-adobe-dng";
149 if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "image/svg+xml";
150 return (
151 videoMimeType({ name: file.name, mimeType: file.type }) ??
152 (file.type || "application/octet-stream")
153 );
154}
155
156export function classifyComposerAttachmentFile(
157 file: Pick<File, "name" | "type">,
158): ComposerAttachmentFileKind {
159 if (isSvgAttachment({ name: file.name, mimeType: file.type })) return "file";
160 if (isDngFile(file)) return "file";
161 if (isHeicImageFile(file)) {
162 return "image";
163 }
164 if (inferImageMimeTypeForUnknownFile(file)) {
165 return "image";
166 }
167 if (!file.type.toLowerCase().startsWith("image/")) {
168 return "file";
169 }
170 if (isProviderSendTurnSupportedImageMimeType(file.type)) return "image";
171 // These can be previewed as files, but providers must not receive them as images.
172 return isWorkspaceImagePreviewPath(file.name) ? "file" : "unsupported-image";
173}
174
175export function isPreviewableComposerVideo(
176 file: ComposerFileAttachment,
177 environmentId: EnvironmentId,
178): boolean {
179 return (
180 isVideoAttachment(file) &&
181 (file.file !== null ||
182 (file.uploadedAttachmentId !== undefined && file.uploadEnvironmentId === environmentId))
183 );
184}
185
186export function composerOtherFilesForPresentation(
187 files: ReadonlyArray<ComposerFileAttachment>,
188 environmentId: EnvironmentId,
189 inlineFileIds: ReadonlySet<string>,
190): ComposerFileAttachment[] {
191 return files.filter(
192 (file) => !isPreviewableComposerVideo(file, environmentId) && !inlineFileIds.has(file.id),
193 );
194}
195
196export function fileAttachmentStagingLimit(input: FileAttachmentCapabilityState): number | null {
197 if (!input.attachmentUploadsCapabilityKnown) {
198 return PROVIDER_SEND_TURN_MAX_FILE_BYTES;
199 }
200 if (!input.supportsAttachmentUploads || input.maxFileAttachmentBytes === null) {
201 return null;
202 }
203 return clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
204}
205
206export function fileAttachmentCapabilityBlockReason(
207 input: FileAttachmentCapabilityState & {
208 readonly files: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
209 },
210): string | null {
211 if (input.files.length === 0) {
212 return null;
213 }
214 if (!input.attachmentUploadsCapabilityKnown) {
215 return "Waiting for the server before file attachments can send";
216 }
217 const maxFileAttachmentBytes = fileAttachmentStagingLimit(input);
218 if (maxFileAttachmentBytes === null) {
219 return "This server does not accept file attachments right now. Remove the files to send.";
220 }
221 const oversizedFile = input.files.find((file) => file.sizeBytes > maxFileAttachmentBytes);
222 if (oversizedFile) {
223 return fileAttachmentTooLargeMessage(oversizedFile.name, maxFileAttachmentBytes);
224 }
225 return null;
226}
227
228/** Release only unpersisted uploads; hydrated files still need their server copies. */
229export function attachmentsToReleaseOnUploadCapabilityLoss(
230 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
231): Array<ComposerImageAttachment | ComposerFileAttachment> {
232 return attachments.filter(
233 (attachment) => !(attachment.type === "file" && attachment.uploadedAttachmentId !== undefined),
234 );
235}
236
237export function shouldHandleComposerAttachmentPaste(input: {
238 readonly files: ReadonlyArray<File>;
239 readonly plainText: string;
240}): boolean {
241 if (
242 input.files.some((file) => {
243 if (isDngFile(file)) return true;
244 const classification = classifyComposerAttachmentFile(file);
245 return (
246 classification === "image" ||
247 classification === "unsupported-image" ||
248 isSvgAttachment({ name: file.name, mimeType: file.type })
249 );
250 })
251 ) {
252 return true;
253 }
254
255 if (input.plainText.length > 0) {
256 return false;
257 }
258
259 return input.files.some((file) => classifyComposerAttachmentFile(file) === "file");
260}