🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(support): add support form max file size error toast (#10328)
Michael Fröhlichafa68bd81345
diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsxindex 829165e252..56027affb8 100644--- a/web/src/features/support-chat/SupportFormSection.tsx+++ b/web/src/features/support-chat/SupportFormSection.tsx@@ -42,11 +42,112 @@ import {DropzoneEmptyState,} from "@/src/components/ui/shadcn-io/dropzone";import { Paperclip, Loader2, Trash2 } from "lucide-react";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { PLAIN_MAX_FILE_SIZE_BYTES } from "./plain/plainConstants";/** Make RHF generics match the resolver (Zod defaults => input can be undefined) */type SupportFormInput = z.input<typeof SupportFormSchema>;type SupportFormValues = z.output<typeof SupportFormSchema>;+/**+ * File upload constraints - single source of truth for validation+ * Uses Plain API's file size limit+ */+const FILE_UPLOAD_CONSTRAINTS = {+ maxFiles: 5,+ maxFileSizeBytes: PLAIN_MAX_FILE_SIZE_BYTES, // 6MB (Plain API limit)+ maxCombinedBytes: 50 * 1024 * 1024, // 50MB+} as const;++/**+ * Validates files against upload constraints+ * @returns {isValid: boolean, error?: string}+ */+function validateFiles(files: File[] | undefined): {+ isValid: boolean;+ error?: string;+} {+ if (!files || files.length === 0) {+ return { isValid: true };+ }++ const { maxFiles, maxFileSizeBytes, maxCombinedBytes } =+ FILE_UPLOAD_CONSTRAINTS;++ // Check file count+ if (files.length > maxFiles) {+ return {+ isValid: false,+ error: `Please upload at most ${maxFiles} files.`,+ };+ }++ // Check individual file sizes+ const oversizedFile = files.find((f) => f.size > maxFileSizeBytes);+ if (oversizedFile) {+ const maxMB = (maxFileSizeBytes / (1024 * 1024)).toFixed(0);+ return {+ isValid: false,+ error: `File "${oversizedFile.name}" is too large. Maximum file size is ${maxMB}MB per file.`,+ };+ }++ // Check combined size+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);+ if (totalSize > maxCombinedBytes) {+ const totalMB = (totalSize / (1024 * 1024)).toFixed(2);+ const maxMB = (maxCombinedBytes / (1024 * 1024)).toFixed(0);+ return {+ isValid: false,+ error: `Total attachment size (${totalMB}MB) exceeds the limit of ${maxMB}MB.`,+ };+ }++ return { isValid: true };+}++/**+ * Converts technical file error messages to user-friendly ones+ */+function formatFileError(error: Error): string {+ const msg = error.message.toLowerCase();+ const { maxFiles, maxFileSizeBytes, maxCombinedBytes } =+ FILE_UPLOAD_CONSTRAINTS;+ const maxMB = (maxFileSizeBytes / (1024 * 1024)).toFixed(0);+ const maxCombinedMB = (maxCombinedBytes / (1024 * 1024)).toFixed(0);++ // File size errors+ if (+ msg.includes("larger than") ||+ msg.includes("10485760") ||+ msg.includes("10mb") ||+ msg.includes("too large")+ ) {+ return `File is too large. Maximum file size is ${maxMB}MB per file.`;+ }++ // File count errors+ if (+ msg.includes("too many") ||+ msg.includes("maxfiles") ||+ msg.includes("5 files")+ ) {+ return `Too many files. Maximum ${maxFiles} files allowed.`;+ }++ // Combined size errors+ if (msg.includes("total") && (msg.includes("50mb") || msg.includes("size"))) {+ return `Total attachment size exceeds limit. Maximum combined size is ${maxCombinedMB}MB.`;+ }++ // File type errors+ if (msg.includes("file type") || msg.includes("accept")) {+ return "File type not supported. Please select a different file.";+ }++ return error.message || "File upload failed. Please try again.";+}+export function SupportFormSection({onCancel,onSuccess,@@ -103,7 +204,14 @@ export function SupportFormSection({});const prepareUploads = api.plainRouter.prepareAttachmentUploads.useMutation({- onError: () => setIsSubmittingLocal(false),+ onError: (error) => {+ setIsSubmittingLocal(false);+ showErrorToast(+ "Upload Preparation Failed",+ error.message || "Failed to prepare file uploads. Please try again.",+ "ERROR",+ );+ },});async function uploadToPlainS3(@@ -135,18 +243,10 @@ export function SupportFormSection({try {setIsSubmittingLocal(true);- // UI-side constraints- const maxFiles = 5;- const maxFileSize = 10 * 1024 * 1024;- const maxCombined = 50 * 1024 * 1024;- if ((files?.length ?? 0) > maxFiles) {- throw new Error(`Please upload at most ${maxFiles} files.`);- }- if ((files ?? []).some((f) => f.size > maxFileSize)) {- throw new Error("Each file must be ≤ 10MB.");- }- if (totalUploadBytes > maxCombined) {- throw new Error("Total attachment size must be ≤ 50MB.");+ // Validate files using centralized validation function+ const validation = validateFiles(files);+ if (!validation.isValid) {+ throw new Error(validation.error);}// 1) Request presigned S3 upload forms@@ -404,10 +504,13 @@ export function SupportFormSection({<DropzoneclassName="mt-1 border-none p-0 text-left"- maxFiles={5}- maxSize={1024 * 1024 * 10}+ maxFiles={FILE_UPLOAD_CONSTRAINTS.maxFiles}+ maxSize={FILE_UPLOAD_CONSTRAINTS.maxFileSizeBytes}onDrop={(accepted) => setFiles(accepted)}- onError={console.error}+ onError={(error) => {+ const userMessage = formatFileError(error);+ showErrorToast("File Upload Error", userMessage, "WARNING");+ }}src={files}>{/* Small, single-line trigger */}diff --git a/web/src/features/support-chat/plain/plainClient.ts b/web/src/features/support-chat/plain/plainClient.tsindex 55f821b824..35f81070b7 100644--- a/web/src/features/support-chat/plain/plainClient.ts+++ b/web/src/features/support-chat/plain/plainClient.ts@@ -6,6 +6,10 @@ import {} from "@team-plain/typescript-sdk";import { TRPCError } from "@trpc/server";import { logger } from "@langfuse/shared/src/server";+import { PLAIN_MAX_FILE_SIZE_BYTES } from "./plainConstants";++// Re-export for backward compatibility+export { PLAIN_MAX_FILE_SIZE_BYTES };// ===== App-level types exported for router use =====export type Project = { id: string };@@ -69,6 +73,63 @@ function describeSdkError(err: unknown) {};}+/**+ * Formats Plain API errors into user-friendly messages+ * @returns User-friendly error message and appropriate HTTP status code+ */+function formatPlainError(error: unknown): {+ message: string;+ code: "BAD_REQUEST" | "INTERNAL_SERVER_ERROR";+} {+ const e = error as any;+ const errorMessage =+ e?.message || e?.errorDetails?.message || String(error) || "";+ const msg = errorMessage.toLowerCase();++ // File size errors+ if (+ msg.includes("file size") ||+ msg.includes("too large") ||+ msg.includes(">6mb") ||+ msg.includes("larger than")+ ) {+ return {+ message: `File is too large. Maximum file size is ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB per file.`,+ code: "BAD_REQUEST",+ };+ }++ // File type errors+ if (msg.includes("file type") || msg.includes("not supported")) {+ return {+ message: "File type not supported. Please select a different file.",+ code: "BAD_REQUEST",+ };+ }++ // Rate limit errors+ if (msg.includes("rate limit") || msg.includes("too many requests")) {+ return {+ message: "Too many requests. Please try again in a moment.",+ code: "BAD_REQUEST",+ };+ }++ // Extract original message if available and meaningful+ if (errorMessage && errorMessage.length > 0 && errorMessage.length < 200) {+ return {+ message: errorMessage,+ code: "BAD_REQUEST",+ };+ }++ // Fallback for unknown errors+ return {+ message: "Failed to prepare file upload. Please try again.",+ code: "INTERNAL_SERVER_ERROR",+ };+}+function unwrap<T>(label: string, res: { data?: T; error?: unknown }): T {if (res.error) {logger.error(`${label} failed`, describeSdkError(res.error));@@ -140,11 +201,32 @@ export async function createAttachmentUploadUrls(attachmentType: AttachmentType.Email,});- const data = unwrap("createAttachmentUploadUrl", r); // throws on error+ // Handle Plain API errors with user-friendly messages+ if (r.error) {+ const formatted = formatPlainError(r.error);+ logger.error(+ "createAttachmentUploadUrl failed",+ describeSdkError(r.error),+ );+ throw new TRPCError({+ code: formatted.code,+ message: formatted.message,+ cause: r.error,+ });+ }++ if (!r.data) {+ logger.error("createAttachmentUploadUrl returned no data", r);+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Plain Client: createAttachmentUploadUrl returned no data",+ });+ }+out.push({- attachmentId: data.attachment.id,- uploadFormUrl: data.uploadFormUrl,- uploadFormData: data.uploadFormData,+ attachmentId: r.data.attachment.id,+ uploadFormUrl: r.data.uploadFormUrl,+ uploadFormData: r.data.uploadFormData,fileName: f.fileName,fileSizeBytes: f.fileSizeBytes,});diff --git a/web/src/features/support-chat/plain/plainConstants.ts b/web/src/features/support-chat/plain/plainConstants.tsnew file mode 100644index 0000000000..c1a7ebfc7b--- /dev/null+++ b/web/src/features/support-chat/plain/plainConstants.ts@@ -0,0 +1,10 @@+/**+ * Client-safe constants for Plain API integration+ * These can be safely imported in both client and server code+ */++/**+ * Maximum file size allowed by Plain API for attachments+ * This is enforced by Plain's API, so we must match it on client and server+ */+export const PLAIN_MAX_FILE_SIZE_BYTES = 6 * 1024 * 1024; // 6MBdiff --git a/web/src/features/support-chat/trpc/plainRouter.ts b/web/src/features/support-chat/trpc/plainRouter.tsindex 007cfc3ed9..9d349d64ad 100644--- a/web/src/features/support-chat/trpc/plainRouter.ts+++ b/web/src/features/support-chat/trpc/plainRouter.ts@@ -31,6 +31,7 @@ import {type SessionUser,type Organization,} from "../plain/plainClient";+import { PLAIN_MAX_FILE_SIZE_BYTES } from "../plain/plainConstants";// =========================// Input Schemas@@ -57,7 +58,22 @@ const PrepareAttachmentUploadsInput = z.object({fileSizeBytes: z.number().int().positive(),}),)- .max(100)+ .max(+ 5,+ `Maximum 5 files allowed (each ≤ ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB)`,+ )+ .refine(+ (files) =>+ files.every((f) => f.fileSizeBytes <= PLAIN_MAX_FILE_SIZE_BYTES),+ {+ message: `Each file must be ≤ ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB`,+ },+ )+ .refine(+ (files) =>+ files.reduce((sum, f) => sum + f.fileSizeBytes, 0) <= 50 * 1024 * 1024,+ { message: "Total attachment size must be ≤ 50MB" },+ ).optional().default([]),});