An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(attachments): enforce the 3-file limit on every attach path (#1048)
Yoshiki Miura653f17441699
diff --git a/app/api/chat/route.ts b/app/api/chat/route.tsindex 9e7c6128..e842c371 100644--- a/app/api/chat/route.ts+++ b/app/api/chat/route.ts@@ -33,6 +33,10 @@ import {trackUsageLimitReached,usageLimitResponse} from '@/lib/usage-budget'+import {+ exceedsAttachmentLimit,+ MAX_ATTACHMENTS_PER_MESSAGE+} from '@/lib/utils/attachment-limits'import { getTextFromParts } from '@/lib/utils/message-utils'import { selectModel } from '@/lib/utils/model-selection'import { perfLog, perfTime } from '@/lib/utils/perf-logging'@@ -116,6 +120,21 @@ export async function POST(req: Request) {const guestChatEnabled = process.env.ENABLE_GUEST_CHAT === 'true'const isGuest = !userId+ if (exceedsAttachmentLimit({ isGuest, trigger, message, messages })) {+ return new Response(+ JSON.stringify({+ error: `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message.`,+ type: 'general',+ code: 'bad_request',+ retryable: false+ }),+ {+ status: 400,+ headers: { 'Content-Type': 'application/json' }+ }+ )+ }+const keylessFilePartCount = Array.isArray(message?.parts)? message.parts.filter((part: unknown) =>diff --git a/components/__tests__/chat-panel.test.tsx b/components/__tests__/chat-panel.test.tsxindex 0151664f..780151ac 100644--- a/components/__tests__/chat-panel.test.tsx+++ b/components/__tests__/chat-panel.test.tsx@@ -1,8 +1,10 @@import React from 'react'-import { render, waitFor } from '@testing-library/react'+import { fireEvent, render, waitFor } from '@testing-library/react'+import { toast } from 'sonner'import { beforeEach, describe, expect, test, vi } from 'vitest'+import type { UploadedFile } from '@/lib/types'import { deleteCookie, getCookie, setCookie } from '@/lib/utils/cookies'import { ChatPanel } from '../chat-panel'@@ -25,8 +27,21 @@ vi.mock('../library/library-context', () => ({})}))+let attachLibraryFile: ((file: UploadedFile) => boolean) | undefined+vi.mock('../library/library-picker-dialog', () => ({- LibraryPickerDialog: () => null+ LibraryPickerDialog: ({+ onAttachFile+ }: {+ onAttachFile: (file: UploadedFile) => boolean+ }) => {+ attachLibraryFile = onAttachFile+ return null+ }+}))++vi.mock('sonner', () => ({+ toast: { error: vi.fn(), success: vi.fn() }}))vi.mock('../message-navigation-dots', () => ({@@ -96,4 +111,112 @@ describe('ChatPanel', () => {})expect(onAdaptiveModeAuthRequired).not.toHaveBeenCalled()})++ describe('attachment limit', () => {+ const existing = (count: number): UploadedFile[] =>+ Array.from({ length: count }, (_, i) => ({+ status: 'uploaded',+ name: `existing-${i}.pdf`,+ key: `key-${i}`,+ mediaType: 'application/pdf',+ libraryFileId: `lib-${i}`+ }))++ function renderPanel(uploadedFiles: UploadedFile[]) {+ const setUploadedFiles = vi.fn()+ const utils = render(+ <ChatPanel+ chatId="chat-1"+ input=""+ handleInputChange={vi.fn()}+ handleSubmit={vi.fn()}+ status="ready"+ messages={[]}+ setMessages={vi.fn()}+ stop={vi.fn()}+ append={vi.fn()}+ showScrollToBottomButton={false}+ scrollContainerRef={React.createRef<HTMLDivElement>()}+ uploadedFiles={uploadedFiles}+ setUploadedFiles={setUploadedFiles}+ quotedContexts={[]}+ setQuotedContexts={vi.fn()}+ noteContexts={[]}+ setNoteContexts={vi.fn()}+ isGuest={false}+ isCloudDeployment+ onAdaptiveModeAuthRequired={vi.fn()}+ />+ )+ return { ...utils, setUploadedFiles }+ }++ test('file picker only uploads into the remaining slots', async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({+ file: {+ url: 'u',+ filename: 'f.pdf',+ key: 'k',+ mediaType: 'application/pdf'+ }+ })+ })+ vi.stubGlobal('fetch', fetchMock)++ const { container } = renderPanel(existing(2))+ const input = container.querySelector(+ 'input[type="file"]'+ ) as HTMLInputElement+ const files = ['a.pdf', 'b.pdf'].map(+ name => new File(['x'], name, { type: 'application/pdf' })+ )+ fireEvent.change(input, { target: { files } })++ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))+ expect(toast.error).toHaveBeenCalledWith(+ 'You can attach up to 3 files per message.'+ )+ vi.unstubAllGlobals()+ })++ test('file picker uploads nothing when the message is full', async () => {+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)++ const { container, setUploadedFiles } = renderPanel(existing(3))+ const input = container.querySelector(+ 'input[type="file"]'+ ) as HTMLInputElement+ fireEvent.change(input, {+ target: {+ files: [new File(['x'], 'a.pdf', { type: 'application/pdf' })]+ }+ })++ await waitFor(() => expect(toast.error).toHaveBeenCalled())+ expect(fetchMock).not.toHaveBeenCalled()+ expect(setUploadedFiles).not.toHaveBeenCalled()+ vi.unstubAllGlobals()+ })++ test('library attach is refused when the message is full', () => {+ const { setUploadedFiles } = renderPanel(existing(3))++ const attached = attachLibraryFile?.({+ status: 'uploaded',+ name: 'new.pdf',+ key: 'new-key',+ mediaType: 'application/pdf',+ libraryFileId: 'lib-new'+ })++ expect(attached).toBe(false)+ expect(setUploadedFiles).not.toHaveBeenCalled()+ expect(toast.error).toHaveBeenCalledWith(+ 'You can attach up to 3 files per message.'+ )+ })+ })})diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex 54111e4a..08ab3156 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -36,6 +36,10 @@ import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'import type { ModelSelectorData } from '@/lib/types/model-selector'import type { SearchMode } from '@/lib/types/search'import { cn } from '@/lib/utils'+import {+ MAX_ATTACHMENTS_PER_MESSAGE,+ remainingAttachmentSlots+} from '@/lib/utils/attachment-limits'import {getCookie,setCookie,@@ -277,9 +281,9 @@ export function ChatPanel({const uploadSelectedFiles = useCallback(async (files: File[]) => {- const validFiles = files- .slice(0, 3)- .filter(file => ALLOWED_FILE_TYPES.includes(file.type))+ const allowedFiles = files.filter(file =>+ ALLOWED_FILE_TYPES.includes(file.type)+ )const rejected = files.filter(file => !ALLOWED_FILE_TYPES.includes(file.type))@@ -291,6 +295,14 @@ export function ChatPanel({)}+ const slots = remainingAttachmentSlots(uploadedFilesRef.current.length)+ if (allowedFiles.length > slots) {+ toast.error(+ `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message.`+ )+ }+ const validFiles = allowedFiles.slice(0, slots)+if (validFiles.length === 0) returnconst newFiles: UploadedFile[] = validFiles.map(file => ({@@ -298,6 +310,7 @@ export function ChatPanel({status: 'uploading',mediaType: file.type}))+ uploadedFilesRef.current = [...uploadedFilesRef.current, ...newFiles]setUploadedFiles(prev => [...prev, ...newFiles])await Promise.all(newFiles.map(async uf => {@@ -373,6 +386,12 @@ export function ChatPanel({) {return false}+ if (remainingAttachmentSlots(uploadedFilesRef.current.length) === 0) {+ toast.error(+ `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message.`+ )+ return false+ }uploadedFilesRef.current = [...uploadedFilesRef.current, file]setUploadedFiles(prev =>file.libraryFileId &&diff --git a/hooks/use-file-dropzone.ts b/hooks/use-file-dropzone.tsindex b6f5cbd2..53ec2252 100644--- a/hooks/use-file-dropzone.ts+++ b/hooks/use-file-dropzone.ts@@ -3,6 +3,7 @@ import { useCallback, useState } from 'react'import { toast } from 'sonner'import { UploadedFile } from '@/lib/types'+import { MAX_ATTACHMENTS_PER_MESSAGE } from '@/lib/utils/attachment-limits'type UseFileDropzoneProps = {uploadedFiles: UploadedFile[]@@ -16,7 +17,7 @@ export function useFileDropzone({uploadedFiles,setUploadedFiles,chatId,- maxFiles = 3,+ maxFiles = MAX_ATTACHMENTS_PER_MESSAGE,allowedTypes = ['image/png', 'image/jpeg', 'application/pdf']}: UseFileDropzoneProps) {const [isDragging, setIsDragging] = useState(false)@@ -51,7 +52,7 @@ export function useFileDropzone({const total = uploadedFiles.length + allowed.lengthif (total > maxFiles) {- toast.error(`You can upload a maximum of ${maxFiles} files.`)+ toast.error(`You can attach up to ${maxFiles} files per message.`)return}diff --git a/lib/streaming/helpers/__tests__/prepare-messages.test.ts b/lib/streaming/helpers/__tests__/prepare-messages.test.tsindex e99f4cc8..f37a92c1 100644--- a/lib/streaming/helpers/__tests__/prepare-messages.test.ts+++ b/lib/streaming/helpers/__tests__/prepare-messages.test.ts@@ -261,6 +261,72 @@ describe('prepareMessages', () => {})})+ describe('attachment limit on edits', () => {+ const files = (count: number): UIMessage['parts'] =>+ Array.from({ length: count }, (_, i) => ({+ type: 'file' as const,+ mediaType: 'application/pdf',+ url: `https://example.com/${i}.pdf`+ }))++ const chatWithStoredFiles = (+ count: number+ ): Chat & { messages: UIMessage[] } => ({+ id: chatId,+ title: 'Test Chat',+ userId,+ visibility: 'private',+ createdAt: new Date(),+ messages: [+ { id: 'msg-1', role: 'user', parts: files(count) },+ {+ id: 'msg-2',+ role: 'assistant',+ parts: [{ type: 'text', text: 'Answer' }]+ }+ ]+ })++ const context = (+ initialChat: Chat & { messages: UIMessage[] }+ ): StreamContext => ({+ chatId,+ userId,+ modelId: 'gpt-4',+ trigger: 'regenerate-message',+ messageId: 'msg-1',+ initialChat,+ isNewChat: false+ })++ it('rejects an edit that adds files beyond the limit', async () => {+ await expect(+ prepareMessages(context(chatWithStoredFiles(1)), {+ id: 'msg-1',+ role: 'user',+ parts: files(5)+ })+ ).rejects.toBeInstanceOf(DeterministicPreparationError)+ expect(upsertMessage).not.toHaveBeenCalled()+ })++ it('allows regenerating a stored message that already exceeds the limit', async () => {+ vi.mocked(deleteMessagesFromIndex).mockResolvedValue({+ success: true,+ count: 1+ })+ const initialChat = chatWithStoredFiles(5)++ const result = await prepareMessages(+ context(initialChat),+ initialChat.messages[0]+ )++ expect(result).toHaveLength(1)+ expect(upsertMessage).toHaveBeenCalled()+ })+ })+it('should throw error when no messages found in chat', async () => {const emptyChat: Chat & { messages: UIMessage[] } = {id: chatId,diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.tsindex 56be7b75..6218efe2 100644--- a/lib/streaming/helpers/prepare-messages.ts+++ b/lib/streaming/helpers/prepare-messages.ts@@ -13,6 +13,10 @@ import {getUserFileObjectKeyPrefix,signFilePartUrls} from '@/lib/storage/r2-client'+import {+ countFileParts,+ MAX_ATTACHMENTS_PER_MESSAGE+} from '@/lib/utils/attachment-limits'import { perfLog, perfTime } from '@/lib/utils/perf-logging'import type { StreamContext } from './types'@@ -70,6 +74,17 @@ export async function prepareMessages(} else {// User message editif (message && message.id === messageId) {+ // Messages saved before the limit was enforced may already carry more+ // files, so only reject an edit that adds files beyond it.+ const fileCount = countFileParts(message)+ if (+ fileCount > MAX_ATTACHMENTS_PER_MESSAGE &&+ fileCount > countFileParts(targetMessage)+ ) {+ throw new DeterministicPreparationError(+ 'Edited message exceeds the attachment limit'+ )+ }await upsertMessage(chatId, message, userId)}const messagesToDelete = currentChat.messages.slice(messageIndex + 1)diff --git a/lib/utils/__tests__/attachment-limits.test.ts b/lib/utils/__tests__/attachment-limits.test.tsnew file mode 100644index 00000000..92603d7b--- /dev/null+++ b/lib/utils/__tests__/attachment-limits.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest'++import {+ countFileParts,+ exceedsAttachmentLimit,+ MAX_ATTACHMENTS_PER_MESSAGE,+ remainingAttachmentSlots+} from '../attachment-limits'++describe('countFileParts', () => {+ it('counts only file parts', () => {+ expect(+ countFileParts({+ parts: [+ { type: 'text', text: 'hi' },+ { type: 'file', mediaType: 'application/pdf' },+ { type: 'data-pastedContent', data: { text: 'x' } },+ { type: 'file', mediaType: 'image/png' }+ ]+ })+ ).toBe(2)+ })++ it('returns 0 for malformed input', () => {+ expect(countFileParts(undefined)).toBe(0)+ expect(countFileParts(null)).toBe(0)+ expect(countFileParts({ parts: 'file' })).toBe(0)+ expect(countFileParts({ parts: [null, 'file'] })).toBe(0)+ })+})++describe('remainingAttachmentSlots', () => {+ it('counts down to zero and never goes negative', () => {+ expect(remainingAttachmentSlots(0)).toBe(MAX_ATTACHMENTS_PER_MESSAGE)+ expect(remainingAttachmentSlots(MAX_ATTACHMENTS_PER_MESSAGE)).toBe(0)+ expect(remainingAttachmentSlots(MAX_ATTACHMENTS_PER_MESSAGE + 2)).toBe(0)+ })+})++describe('exceedsAttachmentLimit', () => {+ const withFiles = (count: number) => ({+ role: 'user',+ parts: Array.from({ length: count }, () => ({ type: 'file' }))+ })++ it('checks the submitted message for authenticated users', () => {+ expect(+ exceedsAttachmentLimit({+ isGuest: false,+ trigger: 'submit-message',+ message: withFiles(4),+ messages: undefined+ })+ ).toBe(true)+ expect(+ exceedsAttachmentLimit({+ isGuest: false,+ trigger: 'submit-message',+ message: withFiles(3),+ messages: undefined+ })+ ).toBe(false)+ })++ it('treats a missing or unknown trigger as a submission', () => {+ for (const trigger of [undefined, 'something-else']) {+ expect(+ exceedsAttachmentLimit({+ isGuest: false,+ trigger,+ message: withFiles(4),+ messages: undefined+ })+ ).toBe(true)+ }+ })++ it('does not block regenerating an existing message', () => {+ expect(+ exceedsAttachmentLimit({+ isGuest: false,+ trigger: 'regenerate-message',+ message: withFiles(5),+ messages: undefined+ })+ ).toBe(false)+ })++ it('checks the guest history instead of the separate message field', () => {+ expect(+ exceedsAttachmentLimit({+ isGuest: true,+ trigger: 'submit-message',+ message: withFiles(0),+ messages: [withFiles(1), withFiles(4)]+ })+ ).toBe(true)+ expect(+ exceedsAttachmentLimit({+ isGuest: true,+ trigger: 'submit-message',+ message: withFiles(0),+ messages: [withFiles(3), withFiles(3)]+ })+ ).toBe(false)+ })+})diff --git a/lib/utils/attachment-limits.ts b/lib/utils/attachment-limits.tsnew file mode 100644index 00000000..e1346d9a--- /dev/null+++ b/lib/utils/attachment-limits.ts@@ -0,0 +1,47 @@+export const MAX_ATTACHMENTS_PER_MESSAGE = 3++export function countFileParts(message: unknown): number {+ if (typeof message !== 'object' || message === null) return 0++ const parts = (message as { parts?: unknown }).parts+ if (!Array.isArray(parts)) return 0++ return parts.filter(+ part =>+ typeof part === 'object' &&+ part !== null &&+ (part as { type?: unknown }).type === 'file'+ ).length+}++export function remainingAttachmentSlots(currentCount: number): number {+ return Math.max(0, MAX_ATTACHMENTS_PER_MESSAGE - currentCount)+}++// Guests send their whole history and the model receives all of it.+// prepareMessages treats every other trigger as a submission, so only+// regenerate is left to prepareMessages, which compares the edit against+// the stored message.+export function exceedsAttachmentLimit({+ isGuest,+ trigger,+ message,+ messages+}: {+ isGuest: boolean+ trigger: unknown+ message: unknown+ messages: unknown+}): boolean {+ const checked = isGuest+ ? Array.isArray(messages)+ ? messages+ : []+ : trigger === 'regenerate-message'+ ? []+ : [message]++ return checked.some(+ item => countFileParts(item) > MAX_ATTACHMENTS_PER_MESSAGE+ )+}