Open History to see the last commit
1import {
2 isProviderSendTurnSupportedImageMimeType,
3 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
4} from "@t3tools/contracts";
5import {
6 clampFileAttachmentUploadBytes,
7 fileAttachmentTooLargeMessage,
8} from "@t3tools/client-runtime/state/attachments";
9
10import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
11import { isHeicImageFile } from "../../lib/imageCompression";
12
13type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
14
15interface FileAttachmentCapabilityState {
16 readonly attachmentUploadsCapabilityKnown: boolean;
17 readonly supportsAttachmentUploads: boolean;
18 readonly maxFileAttachmentBytes: number | null;
19}
20
21const IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
22 gif: "image/gif",
23 jpeg: "image/jpeg",
24 jpg: "image/jpeg",
25 png: "image/png",
26 webp: "image/webp",
27};
28
29/**
30 * Some sources (drags from other apps, files piped through a shell) hand over
31 * a `File` with an empty or generic MIME type. Maps the extension to a
32 * provider-supported image type so a plain `photo.jpg` still lands on the
33 * image path; anything unrecognized stays a generic file.
34 */
35export function inferImageMimeTypeFromName(name: string): string | null {
36 const dotIndex = name.lastIndexOf(".");
37 if (dotIndex <= 0) {
38 return null;
39 }
40 return IMAGE_MIME_TYPE_BY_EXTENSION[name.slice(dotIndex + 1).toLowerCase()] ?? null;
41}
42
43function inferImageMimeTypeForUnknownFile(file: Pick<File, "name" | "type">): string | null {
44 const mimeType = file.type.toLowerCase();
45 if (mimeType !== "" && mimeType !== "application/octet-stream") {
46 return null;
47 }
48 return inferImageMimeTypeFromName(file.name);
49}
50
51/** Give extension-recognized images a concrete type before compression. */
52export function normalizeComposerImageFileMimeType(file: File): File {
53 const inferredMimeType = inferImageMimeTypeForUnknownFile(file);
54 if (!inferredMimeType) {
55 return file;
56 }
57 return new File([file], file.name, {
58 type: inferredMimeType,
59 lastModified: file.lastModified,
60 });
61}
62
63export function classifyComposerAttachmentFile(
64 file: Pick<File, "name" | "type">,
65): ComposerAttachmentFileKind {
66 if (isHeicImageFile(file)) {
67 return "image";
68 }
69 if (inferImageMimeTypeForUnknownFile(file)) {
70 return "image";
71 }
72 if (!file.type.toLowerCase().startsWith("image/")) {
73 return "file";
74 }
75 return isProviderSendTurnSupportedImageMimeType(file.type) ? "image" : "unsupported-image";
76}
77
78/** Byte limit for adding a generic file to the local composer draft. */
79export function fileAttachmentStagingLimit(input: FileAttachmentCapabilityState): number | null {
80 if (!input.attachmentUploadsCapabilityKnown) {
81 return PROVIDER_SEND_TURN_MAX_FILE_BYTES;
82 }
83 if (!input.supportsAttachmentUploads || input.maxFileAttachmentBytes === null) {
84 return null;
85 }
86 return clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
87}
88
89/** Why retained generic files cannot send with the current server config. */
90export function fileAttachmentCapabilityBlockReason(
91 input: FileAttachmentCapabilityState & {
92 readonly files: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
93 },
94): string | null {
95 if (input.files.length === 0) {
96 return null;
97 }
98 if (!input.attachmentUploadsCapabilityKnown) {
99 return "Waiting for the server before file attachments can send";
100 }
101 const maxFileAttachmentBytes = fileAttachmentStagingLimit(input);
102 if (maxFileAttachmentBytes === null) {
103 return "This server does not accept file attachments right now. Remove the files to send.";
104 }
105 const oversizedFile = input.files.find((file) => file.sizeBytes > maxFileAttachmentBytes);
106 if (oversizedFile) {
107 return fileAttachmentTooLargeMessage(oversizedFile.name, maxFileAttachmentBytes);
108 }
109 return null;
110}
111
112/**
113 * When `capabilities.attachmentUploads` flips off (reconnect, version skew),
114 * tear down only uploads that have not been persisted onto a draft file.
115 * Once `uploadedAttachmentId` is stamped, the draft references that server
116 * copy after reload even if its local `File` is still available in memory.
117 * Explicit attachment removal releases persisted uploads through
118 * `releaseDraftAttachment`.
119 */
120export function attachmentsToReleaseOnUploadCapabilityLoss(
121 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
122): Array<ComposerImageAttachment | ComposerFileAttachment> {
123 return attachments.filter(
124 (attachment) => !(attachment.type === "file" && attachment.uploadedAttachmentId !== undefined),
125 );
126}
127
128/**
129 * Whether a paste's files should be claimed as composer attachments instead of
130 * falling through to the default text paste. Deliberately no capacity or
131 * pending-plan-question gate here: `addComposerAttachments` owns those limits
132 * and reports them, while a gate at this layer would swallow the paste with no
133 * feedback.
134 */
135export function shouldHandleComposerAttachmentPaste(input: {
136 readonly files: ReadonlyArray<File>;
137 readonly plainText: string;
138}): boolean {
139 if (
140 input.files.some((file) => {
141 const classification = classifyComposerAttachmentFile(file);
142 return classification === "image" || classification === "unsupported-image";
143 })
144 ) {
145 return true;
146 }
147
148 if (input.plainText.length > 0) {
149 return false;
150 }
151
152 return input.files.some((file) => classifyComposerAttachmentFile(file) === "file");
153}