Skip to content

An AI-powered search engine with a generative UI

Support signed library file reattachments (#903)

Yoshiki Miuradae7d8631ffe
diff --git a/app/api/upload/route.ts b/app/api/upload/route.ts
index 47b6ffa7..f6afcb84 100644
--- a/app/api/upload/route.ts
+++ b/app/api/upload/route.ts
@@ -2,7 +2,9 @@ import { NextRequest, NextResponse } from 'next/server'
import { PutObjectCommand } from '@aws-sdk/client-s3'
+import { capture } from '@/lib/analytics/dispatch'
import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
import {
getR2Client,
getSignedFileUrl,
@@ -60,7 +62,47 @@ export async function POST(req: NextRequest) {
)
}
const result = await uploadFileToR2(file, userId, chatId)
- return NextResponse.json({ success: true, file: result }, { status: 200 })
+ if (process.env.ENABLE_AUTH === 'false') {
+ return NextResponse.json({ success: true, file: result }, { status: 200 })
+ }
+
+ let libraryFile = null
+ try {
+ const createdFile = await dbActions.createLibraryFile({
+ userId,
+ chatId: chatId || null,
+ filename: result.filename,
+ objectKey: result.key,
+ mediaType: result.mediaType,
+ size: file.size
+ })
+ libraryFile = {
+ ...createdFile,
+ key: createdFile.objectKey,
+ url: result.url
+ }
+ await capture({
+ event: 'file_saved_to_library',
+ distinctId: userId,
+ properties: {
+ mediaType: result.mediaType,
+ source: 'upload',
+ size: file.size
+ }
+ })
+ } catch (error) {
+ console.error('Library file metadata save failed:', error)
+ }
+
+ return NextResponse.json(
+ {
+ success: true,
+ file: libraryFile
+ ? { ...result, id: libraryFile.id, size: file.size, libraryFile }
+ : { ...result, size: file.size }
+ },
+ { status: 200 }
+ )
} catch (err: any) {
console.error('Upload Error:', err)
return NextResponse.json(
diff --git a/components/__tests__/chat-panel.test.tsx b/components/__tests__/chat-panel.test.tsx
index 9edbe5a5..0151664f 100644
--- a/components/__tests__/chat-panel.test.tsx
+++ b/components/__tests__/chat-panel.test.tsx
@@ -19,8 +19,14 @@ vi.mock('../action-buttons', () => ({
ActionButtons: () => null
}))
-vi.mock('../file-upload-button', () => ({
- FileUploadButton: () => null
+vi.mock('../library/library-context', () => ({
+ useLibrary: () => ({
+ upsertCachedFile: vi.fn()
+ })
+}))
+
+vi.mock('../library/library-picker-dialog', () => ({
+ LibraryPickerDialog: () => null
}))
vi.mock('../message-navigation-dots', () => ({
@@ -71,6 +77,8 @@ describe('ChatPanel', () => {
setUploadedFiles={vi.fn()}
quotedContexts={[]}
setQuotedContexts={vi.fn()}
+ noteContexts={[]}
+ setNoteContexts={vi.fn()}
isGuest
isCloudDeployment
onAdaptiveModeAuthRequired={onAdaptiveModeAuthRequired}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 7b97388d..51be1e9e 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -16,7 +16,10 @@ import {
IconArrowUp as ArrowUp,
IconChevronDown as ChevronDown,
IconFileText as FileText,
+ IconLibrary as LibraryIcon,
IconMessageCirclePlus as MessageCirclePlus,
+ IconPaperclip as Paperclip,
+ IconPlus as Plus,
IconSquare as Square,
IconX as X
} from '@tabler/icons-react'
@@ -28,7 +31,7 @@ import {
isAdaptiveModeAuthBlocked,
requiresAdaptiveModeAuth
} from '@/lib/search-mode-availability'
-import { UploadedFile } from '@/lib/types'
+import { NoteContext, UploadedFile } from '@/lib/types'
import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import type { ModelSelectorData } from '@/lib/types/model-selector'
import type { SearchMode } from '@/lib/types/search'
@@ -38,8 +41,11 @@ import {
setCookie,
subscribeToCookieChange
} from '@/lib/utils/cookies'
+import { stripMarkdownText } from '@/lib/utils/markdown'
import { useArtifact } from './artifact/artifact-context'
+import { useLibrary } from './library/library-context'
+import { LibraryPickerDialog } from './library/library-picker-dialog'
import { Button } from './ui/button'
import { IconBlinkingLogo } from './ui/icons'
import {
@@ -49,7 +55,6 @@ import {
TooltipTrigger
} from './ui/tooltip'
import { ActionButtons } from './action-buttons'
-import { FileUploadButton } from './file-upload-button'
import { MessageNavigationDots } from './message-navigation-dots'
import { ModelSelectorClient } from './model-selector-client'
import { SearchModeSelector } from './search-mode-selector'
@@ -65,6 +70,7 @@ const PASTE_CARD_MIN_CHARS = 400
// L0 prototype: client-only, no fetch — the URL rides into the query at send
// time so the existing fetch tool picks it up.
const BARE_URL_RE = /^https?:\/\/\S+$/
+const ALLOWED_FILE_TYPES = ['image/png', 'image/jpeg', 'application/pdf']
function getSearchModeSnapshot(): SearchMode {
return getCookie('searchMode') === 'adaptive' ? 'adaptive' : 'quick'
@@ -89,6 +95,8 @@ interface ChatPanelProps {
setUploadedFiles: React.Dispatch<React.SetStateAction<UploadedFile[]>>
quotedContexts: string[]
setQuotedContexts: React.Dispatch<React.SetStateAction<string[]>>
+ noteContexts: NoteContext[]
+ setNoteContexts: React.Dispatch<React.SetStateAction<NoteContext[]>>
/** Callback to reset chatId when starting a new chat */
onNewChat?: () => void
/** Whether the current session is guest */
@@ -117,6 +125,8 @@ export function ChatPanel({
setUploadedFiles,
quotedContexts,
setQuotedContexts,
+ noteContexts,
+ setNoteContexts,
scrollContainerRef,
onNewChat,
isGuest = false,
@@ -127,6 +137,10 @@ export function ChatPanel({
}: ChatPanelProps) {
const router = useRouter()
const inputRef = useRef<HTMLTextAreaElement>(null)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ const attachmentMenuRef = useRef<HTMLDivElement>(null)
+ const noteContextsRef = useRef(noteContexts)
+ const uploadedFilesRef = useRef(uploadedFiles)
const isFirstRender = useRef(true)
const [isComposing, setIsComposing] = useState(false) // Composition state
const [enterDisabled, setEnterDisabled] = useState(false) // Disable Enter after composition ends
@@ -136,12 +150,16 @@ export function ChatPanel({
const [contentCards, setContentCards] = useState<string[]>([])
// A single pasted URL becomes a lightweight favicon chip (see BARE_URL_RE).
const [urlCards, setUrlCards] = useState<string[]>([])
+ const [isAttachmentMenuOpen, setIsAttachmentMenuOpen] = useState(false)
+ const [isLibraryPickerOpen, setIsLibraryPickerOpen] = useState(false)
const { close: closeArtifact } = useArtifact()
+ const { upsertCachedFile } = useLibrary()
const isLoading = status === 'submitted' || status === 'streaming'
const hasPendingInput =
input.trim().length > 0 ||
contentCards.length > 0 ||
quotedContexts.length > 0 ||
+ noteContexts.length > 0 ||
urlCards.length > 0 ||
uploadedFiles.some(file => file.status === 'uploaded')
const hasAvailableModels =
@@ -175,6 +193,14 @@ export function ChatPanel({
}, 50)
}
+ useEffect(() => {
+ noteContextsRef.current = noteContexts
+ }, [noteContexts])
+
+ useEffect(() => {
+ uploadedFilesRef.current = uploadedFiles
+ }, [uploadedFiles])
+
const handleNewChat = useCallback(() => {
setMessages([])
closeArtifact()
@@ -247,6 +273,150 @@ export function ChatPanel({
},
[setUploadedFiles]
)
+
+ const uploadSelectedFiles = useCallback(
+ async (files: File[]) => {
+ const validFiles = files
+ .slice(0, 3)
+ .filter(file => ALLOWED_FILE_TYPES.includes(file.type))
+ const rejected = files.filter(
+ file => !ALLOWED_FILE_TYPES.includes(file.type)
+ )
+
+ if (rejected.length > 0) {
+ toast.error(
+ 'Some files were not accepted: ' +
+ rejected.map(file => file.name).join(', ')
+ )
+ }
+
+ if (validFiles.length === 0) return
+
+ const newFiles: UploadedFile[] = validFiles.map(file => ({
+ file,
+ status: 'uploading',
+ mediaType: file.type
+ }))
+ setUploadedFiles(prev => [...prev, ...newFiles])
+ await Promise.all(
+ newFiles.map(async uf => {
+ if (!uf.file) return
+ const formData = new FormData()
+ formData.append('file', uf.file)
+ formData.append('chatId', chatId)
+ try {
+ const res = await fetch('/api/upload', {
+ method: 'POST',
+ body: formData
+ })
+
+ if (!res.ok) {
+ throw new Error('Upload failed')
+ }
+
+ const { file: uploaded } = await res.json()
+ if (uploaded.libraryFile) {
+ upsertCachedFile(uploaded.libraryFile)
+ }
+ setUploadedFiles(prev =>
+ prev.map(f =>
+ f.file === uf.file
+ ? {
+ ...f,
+ status: 'uploaded',
+ url: uploaded.url,
+ name: uploaded.filename,
+ key: uploaded.key,
+ mediaType: uploaded.mediaType,
+ libraryFileId: uploaded.id
+ }
+ : f
+ )
+ )
+ } catch (e) {
+ toast.error(`Failed to upload ${uf.file.name}`)
+ setUploadedFiles(prev =>
+ prev.map(f =>
+ f.file === uf.file ? { ...f, status: 'error' } : f
+ )
+ )
+ }
+ })
+ )
+ },
+ [chatId, setUploadedFiles, upsertCachedFile]
+ )
+
+ const handleAttachNote = useCallback(
+ (note: NoteContext) => {
+ if (noteContextsRef.current.some(item => item.id === note.id)) {
+ return false
+ }
+ noteContextsRef.current = [...noteContextsRef.current, note]
+ setNoteContexts(prev =>
+ prev.some(item => item.id === note.id) ? prev : [...prev, note]
+ )
+ toast.success('Note attached')
+ return true
+ },
+ [setNoteContexts]
+ )
+
+ const handleAttachLibraryFile = useCallback(
+ (file: UploadedFile) => {
+ if (
+ file.libraryFileId &&
+ uploadedFilesRef.current.some(
+ item => item.libraryFileId === file.libraryFileId
+ )
+ ) {
+ return false
+ }
+ uploadedFilesRef.current = [...uploadedFilesRef.current, file]
+ setUploadedFiles(prev =>
+ file.libraryFileId &&
+ prev.some(item => item.libraryFileId === file.libraryFileId)
+ ? prev
+ : [...prev, file]
+ )
+ toast.success('File attached')
+ return true
+ },
+ [setUploadedFiles]
+ )
+
+ const openLibraryPicker = useCallback(() => {
+ setIsAttachmentMenuOpen(false)
+ setIsLibraryPickerOpen(true)
+ }, [])
+
+ useEffect(() => {
+ if (!isAttachmentMenuOpen) return
+
+ function handlePointerDown(event: PointerEvent) {
+ if (
+ attachmentMenuRef.current &&
+ !attachmentMenuRef.current.contains(event.target as Node)
+ ) {
+ setIsAttachmentMenuOpen(false)
+ }
+ }
+
+ function handleKeyDown(event: KeyboardEvent) {
+ if (event.key === 'Escape') {
+ setIsAttachmentMenuOpen(false)
+ }
+ }
+
+ document.addEventListener('pointerdown', handlePointerDown)
+ document.addEventListener('keydown', handleKeyDown)
+
+ return () => {
+ document.removeEventListener('pointerdown', handlePointerDown)
+ document.removeEventListener('keydown', handleKeyDown)
+ }
+ }, [isAttachmentMenuOpen])
+
// Scroll to the bottom of the container
const handleScrollToBottom = () => {
const scrollContainer = scrollContainerRef.current
@@ -286,7 +456,9 @@ export function ChatPanel({
if (
contentCards.length > 0 ||
quotedContexts.length > 0 ||
- urlCards.length > 0
+ noteContexts.length > 0 ||
+ urlCards.length > 0 ||
+ uploadedFiles.some(file => file.status === 'uploaded')
) {
e.preventDefault()
if (adaptiveModeSubmitBlocked) {
@@ -307,6 +479,10 @@ export function ChatPanel({
type: 'data-quotedContext',
data: { text }
})),
+ ...noteContexts.map(note => ({
+ type: 'data-noteContext',
+ data: { title: note.title, text: note.content }
+ })),
...urlCards.map(url => ({
type: 'data-sourceUrl',
data: { url }
@@ -314,7 +490,7 @@ export function ChatPanel({
...uploaded.map(f => ({
type: 'file',
url: f.url!,
- filename: f.name!,
+ filename: f.name ?? f.file?.name ?? 'Attached file',
mediaType:
f.mediaType ?? f.file?.type ?? 'application/octet-stream',
key: f.key
@@ -332,8 +508,24 @@ export function ChatPanel({
cardCount: urlCards.length
})
}
+ if (noteContexts.length > 0) {
+ captureClient('note_context_submitted', {
+ count: noteContexts.length,
+ chars: noteContexts.reduce(
+ (sum, note) => sum + note.content.length,
+ 0
+ )
+ })
+ }
+ const libraryFiles = uploaded.filter(file => file.libraryFileId)
+ if (libraryFiles.length > 0) {
+ captureClient('library_file_submitted', {
+ count: libraryFiles.length
+ })
+ }
setContentCards([])
setQuotedContexts([])
+ setNoteContexts([])
setUrlCards([])
setUploadedFiles([])
handleInputChange({
@@ -487,6 +679,38 @@ export function ChatPanel({
))}
</div>
)}
+ {noteContexts.length > 0 && (
+ <div className="flex flex-col gap-1.5 px-3 pt-3">
+ {noteContexts.map((note, i) => (
+ <div
+ key={note.id}
+ className="relative rounded-xl border border-input bg-background px-3 py-2"
+ >
+ <div className="mb-1 flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1.5 truncate text-xs font-medium text-muted-foreground">
+ <FileText className="size-3.5 shrink-0" />
+ <span className="truncate">
+ Note: {stripMarkdownText(note.title) || 'Untitled note'}
+ </span>
+ </span>
+ <button
+ type="button"
+ aria-label="Remove note"
+ className="shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
+ onClick={() => {
+ setNoteContexts(prev => prev.filter((_, j) => j !== i))
+ }}
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ <p className="line-clamp-2 whitespace-pre-wrap break-words text-xs text-muted-foreground/80">
+ {stripMarkdownText(note.content)}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
{urlCards.length > 0 && (
<div className="flex flex-wrap gap-1.5 px-3 pt-3">
{urlCards.map((url, i) => {
@@ -610,57 +834,63 @@ export function ChatPanel({
<div className="flex items-center justify-between p-2 md:p-3">
<div className="flex items-center gap-2">
{!isGuest && (
- <FileUploadButton
- onFileSelect={async files => {
- const newFiles: UploadedFile[] = files.map(file => ({
- file,
- status: 'uploading'
- }))
- setUploadedFiles(prev => [...prev, ...newFiles])
- await Promise.all(
- newFiles.map(async uf => {
- const formData = new FormData()
- formData.append('file', uf.file!)
- formData.append('chatId', chatId)
- try {
- const res = await fetch('/api/upload', {
- method: 'POST',
- body: formData
- })
-
- if (!res.ok) {
- throw new Error('Upload failed')
- }
-
- const { file: uploaded } = await res.json()
- setUploadedFiles(prev =>
- prev.map(f =>
- f.file === uf.file
- ? {
- ...f,
- status: 'uploaded',
- url: uploaded.url,
- name: uploaded.filename,
- key: uploaded.key,
- mediaType: uploaded.mediaType
- }
- : f
- )
- )
- } catch (e) {
- toast.error(
- `Failed to upload ${uf.file?.name ?? 'file'}`
- )
- setUploadedFiles(prev =>
- prev.map(f =>
- f.file === uf.file ? { ...f, status: 'error' } : f
- )
- )
- }
- })
- )
- }}
- />
+ <div ref={attachmentMenuRef} className="relative">
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={ALLOWED_FILE_TYPES.join(',')}
+ className="hidden"
+ onChange={event => {
+ const files = Array.from(event.target.files ?? [])
+ event.target.value = ''
+ setIsAttachmentMenuOpen(false)
+ void uploadSelectedFiles(files)
+ }}
+ />
+ <TooltipProvider delayDuration={200}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="size-8 rounded-full"
+ aria-label="Add"
+ aria-expanded={isAttachmentMenuOpen}
+ onClick={() => setIsAttachmentMenuOpen(open => !open)}
+ >
+ <Plus className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent className="text-xs">Add</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+
+ {isAttachmentMenuOpen && (
+ <div className="absolute bottom-full left-0 z-50 mb-2 w-52 rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
+ <button
+ type="button"
+ className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none"
+ onClick={() => {
+ setIsAttachmentMenuOpen(false)
+ fileInputRef.current?.click()
+ }}
+ >
+ <Paperclip className="size-4" />
+ Upload file
+ </button>
+ <button
+ type="button"
+ className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none"
+ onClick={openLibraryPicker}
+ >
+ <LibraryIcon className="size-4" />
+ Add from library
+ </button>
+ </div>
+ )}
+ </div>
)}
<SearchModeSelector
isAdaptiveAuthRequired={isAdaptiveAuthRequired}
@@ -739,6 +969,12 @@ export function ChatPanel({
/>
)}
</form>
+ <LibraryPickerDialog
+ open={isLibraryPickerOpen}
+ onOpenChange={setIsLibraryPickerOpen}
+ onAttachNote={handleAttachNote}
+ onAttachFile={handleAttachLibraryFile}
+ />
</div>
)
}
diff --git a/components/chat.tsx b/components/chat.tsx
index 711611ba..fe5722b2 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -21,7 +21,7 @@ import {
ADAPTIVE_MODE_AUTH_REQUIRED_MESSAGE,
isAdaptiveModeAuthBlocked
} from '@/lib/search-mode-availability'
-import { UploadedFile } from '@/lib/types'
+import { NoteContext, UploadedFile } from '@/lib/types'
import type { UIMessage } from '@/lib/types/ai'
import {
isDynamicToolPart,
@@ -79,6 +79,7 @@ export function Chat({
setInput('')
setUploadedFiles([])
setQuotedContexts([])
+ setNoteContexts([])
setErrorModal({
open: false,
type: 'general',
@@ -90,6 +91,7 @@ export function Chat({
const [isAtBottom, setIsAtBottom] = useState(true)
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
const [quotedContexts, setQuotedContexts] = useState<string[]>([])
+ const [noteContexts, setNoteContexts] = useState<NoteContext[]>([])
const [input, setInput] = useState('')
const [errorModal, setErrorModal] = useState<{
open: boolean
@@ -607,6 +609,8 @@ export function Chat({
setUploadedFiles={setUploadedFiles}
quotedContexts={quotedContexts}
setQuotedContexts={setQuotedContexts}
+ noteContexts={noteContexts}
+ setNoteContexts={setNoteContexts}
scrollContainerRef={scrollContainerRef}
onNewChat={handleNewChat}
isGuest={isGuest}
diff --git a/components/library/library-context.tsx b/components/library/library-context.tsx
index dddcef36..b5299c9f 100644
--- a/components/library/library-context.tsx
+++ b/components/library/library-context.tsx
@@ -8,6 +8,7 @@ import {
useState
} from 'react'
+import type { LibraryFileItem } from '@/lib/actions/files'
import type { Note } from '@/lib/db/schema'
import { useSidebar } from '../ui/sidebar'
@@ -24,9 +25,17 @@ type NotesCache = {
updatedAt: number
}
+type FilesCache = {
+ files: LibraryFileItem[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ updatedAt: number
+}
+
type LibraryContextValue = {
isOpen: boolean
notesCache: NotesCache | null
+ filesCache: FilesCache | null
refreshKey: number
openLibrary: () => void
closeLibrary: () => void
@@ -43,6 +52,18 @@ type LibraryContextValue = {
}) => void
upsertCachedNote: (note: Note) => void
removeCachedNote: (noteId: string) => void
+ replaceFilesCache: (page: {
+ files: LibraryFileItem[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => void
+ appendFilesCache: (page: {
+ files: LibraryFileItem[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => void
+ upsertCachedFile: (file: LibraryFileItem) => void
+ removeCachedFile: (fileId: string) => void
refreshLibrary: () => void
}
@@ -51,6 +72,7 @@ const LibraryContext = createContext<LibraryContextValue | null>(null)
export function LibraryProvider({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false)
const [notesCache, setNotesCache] = useState<NotesCache | null>(null)
+ const [filesCache, setFilesCache] = useState<FilesCache | null>(null)
const [refreshKey, setRefreshKey] = useState(0)
const { setOpen: setSidebarOpen } = useSidebar()
@@ -60,13 +82,11 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
}, [setSidebarOpen])
const closeLibrary = useCallback(() => setIsOpen(false), [])
const toggleLibrary = useCallback(() => {
- setIsOpen(open => {
- if (!open) {
- setSidebarOpen(false)
- }
- return !open
- })
- }, [setSidebarOpen])
+ if (!isOpen) {
+ setSidebarOpen(false)
+ }
+ setIsOpen(open => !open)
+ }, [isOpen, setSidebarOpen])
const replaceNotesCache = useCallback(
(page: {
notes: Note[]
@@ -128,6 +148,67 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
}
})
}, [])
+ const replaceFilesCache = useCallback(
+ (page: {
+ files: LibraryFileItem[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => {
+ setFilesCache({ ...page, updatedAt: Date.now() })
+ },
+ []
+ )
+ const appendFilesCache = useCallback(
+ (page: {
+ files: LibraryFileItem[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => {
+ setFilesCache(cache => {
+ if (!cache) {
+ return { ...page, updatedAt: Date.now() }
+ }
+
+ const existingIds = new Set(cache.files.map(file => file.id))
+ const mergedFiles = [
+ ...cache.files,
+ ...page.files.filter(file => !existingIds.has(file.id))
+ ]
+
+ return {
+ files: mergedFiles,
+ nextCursor: page.nextCursor,
+ hasMore: page.hasMore,
+ updatedAt: Date.now()
+ }
+ })
+ },
+ []
+ )
+ const upsertCachedFile = useCallback((file: LibraryFileItem) => {
+ setFilesCache(cache => {
+ if (!cache) return cache
+
+ return {
+ files: [file, ...cache.files.filter(item => item.id !== file.id)],
+ nextCursor: cache.nextCursor,
+ hasMore: cache.hasMore,
+ updatedAt: Date.now()
+ }
+ })
+ }, [])
+ const removeCachedFile = useCallback((fileId: string) => {
+ setFilesCache(cache => {
+ if (!cache) return cache
+
+ return {
+ files: cache.files.filter(file => file.id !== fileId),
+ nextCursor: cache.nextCursor,
+ hasMore: cache.hasMore,
+ updatedAt: Date.now()
+ }
+ })
+ }, [])
const refreshLibrary = useCallback(() => {
setRefreshKey(key => key + 1)
}, [])
@@ -136,6 +217,7 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
() => ({
isOpen,
notesCache,
+ filesCache,
refreshKey,
openLibrary,
closeLibrary,
@@ -144,18 +226,27 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
appendNotesCache,
upsertCachedNote,
removeCachedNote,
+ replaceFilesCache,
+ appendFilesCache,
+ upsertCachedFile,
+ removeCachedFile,
refreshLibrary
}),
[
closeLibrary,
appendNotesCache,
+ appendFilesCache,
isOpen,
+ filesCache,
notesCache,
openLibrary,
removeCachedNote,
+ removeCachedFile,
+ replaceFilesCache,
replaceNotesCache,
refreshLibrary,
toggleLibrary,
+ upsertCachedFile,
upsertCachedNote,
refreshKey
]
diff --git a/components/library/library-panel.tsx b/components/library/library-panel.tsx
index 0e0f81eb..71e5276e 100644
--- a/components/library/library-panel.tsx
+++ b/components/library/library-panel.tsx
@@ -12,16 +12,21 @@ import {
import {
IconArrowLeft as ArrowLeft,
IconDots as MoreHorizontal,
+ IconFile as FileIcon,
IconFileText as FileText,
IconLibrary as LibraryIcon,
+ IconPhoto as Photo,
IconTrash as Trash,
IconX as X
} from '@tabler/icons-react'
import { toast } from 'sonner'
+import type { LibraryFileItem } from '@/lib/actions/files'
+import { deleteFile, listFiles } from '@/lib/actions/files'
import { deleteNote, listNotes } from '@/lib/actions/notes'
import { captureClient } from '@/lib/analytics/posthog-client'
import type { Note } from '@/lib/db/schema'
+import { stripMarkdownText } from '@/lib/utils/markdown'
import {
AlertDialog,
@@ -53,6 +58,15 @@ import { useLibrary } from './library-context'
const LIBRARY_CACHE_TTL_MS = 60_000
const LIBRARY_PAGE_SIZE = 25
+type LibraryTab = 'all' | 'notes' | 'files'
+type DeleteTarget =
+ | { kind: 'note'; item: Note; source: 'library_list' | 'library_detail' }
+ | {
+ kind: 'file'
+ item: LibraryFileItem
+ source: 'library_list' | 'library_detail'
+ }
+
function formatNoteDate(value: Date | string) {
const date = value instanceof Date ? value : new Date(value)
return new Intl.DateTimeFormat(undefined, {
@@ -63,37 +77,32 @@ function formatNoteDate(value: Date | string) {
}).format(date)
}
-function stripMarkdownText(value: string) {
- return value
- .replace(/```[\s\S]*?```/g, match =>
- match.replace(/```[^\n]*\n?|\n?```/g, ' ')
- )
- .replace(/`([^`]+)`/g, '$1')
- .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
- .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
- .replace(/^#{1,6}\s+/gm, '')
- .replace(/^>\s?/gm, '')
- .replace(/^\s*[-*+]\s+/gm, '')
- .replace(/^\s*\d+\.\s+/gm, '')
- .replace(/\*\*([^*]+)\*\*/g, '$1')
- .replace(/\*([^*]+)\*/g, '$1')
- .replace(/__([^_]+)__/g, '$1')
- .replace(/_([^_]+)_/g, '$1')
- .replace(/~~([^~]+)~~/g, '$1')
- .replace(/[*_~`>#]/g, '')
- .replace(/\s+/g, ' ')
- .trim()
-}
-
function getExcerpt(content: string) {
return stripMarkdownText(content).slice(0, 140)
}
+function formatBytes(value: number | null) {
+ if (!value) return 'Unknown size'
+ if (value < 1024) return `${value} B`
+ if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`
+ return `${(value / 1024 / 1024).toFixed(1)} MB`
+}
+
function stripMarkdownTitle(value: string) {
return stripMarkdownText(value)
}
-function NoteActionsMenu({ onDelete }: { onDelete: () => void }) {
+function fileIcon(file: LibraryFileItem) {
+ return file.mediaType.startsWith('image/') ? Photo : FileIcon
+}
+
+function LibraryItemActionsMenu({
+ deleteLabel,
+ onDelete
+}: {
+ deleteLabel: string
+ onDelete: () => void
+}) {
const [isMenuOpen, setIsMenuOpen] = useState(false)
return (
@@ -120,7 +129,7 @@ function NoteActionsMenu({ onDelete }: { onDelete: () => void }) {
}}
>
<Trash size={14} />
- Delete Note
+ {deleteLabel}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -150,17 +159,24 @@ export function LibraryPanel() {
isOpen,
closeLibrary,
notesCache,
+ filesCache,
refreshKey,
replaceNotesCache,
+ replaceFilesCache,
appendNotesCache,
- removeCachedNote
+ appendFilesCache,
+ removeCachedNote,
+ removeCachedFile
} = useLibrary()
+ const [activeTab, setActiveTab] = useState<LibraryTab>('all')
const [selectedNote, setSelectedNote] = useState<Note | null>(null)
- const [deleteTarget, setDeleteTarget] = useState<Note | null>(null)
+ const [selectedFile, setSelectedFile] = useState<LibraryFileItem | null>(null)
+ const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null)
const [hasLoadAttempted, setHasLoadAttempted] = useState(false)
const [isLoadingMore, setIsLoadingMore] = useState(false)
const [isDeleting, startDeleteTransition] = useTransition()
const lastFetchedRefreshKeyRef = useRef<number | null>(null)
+ const lastFetchedFilesRefreshKeyRef = useRef<number | null>(null)
const previousIsOpenRef = useRef(false)
const listScrollRef = useRef<HTMLDivElement | null>(null)
const loadMoreRef = useRef<HTMLDivElement | null>(null)
@@ -234,46 +250,162 @@ export function LibraryPanel() {
}
}, [isOpen, notesCache, refreshKey, replaceNotesCache])
- const handleLoadMore = useCallback(async () => {
- if (!notesCache?.hasMore || !notesCache.nextCursor || isLoadingMore) return
+ useEffect(() => {
+ if (!isOpen) return
- setIsLoadingMore(true)
- try {
- const result = await listNotes({
- limit: LIBRARY_PAGE_SIZE,
- cursor: notesCache.nextCursor
- })
+ const hasCache = Boolean(filesCache)
+ const isRefreshStale = lastFetchedFilesRefreshKeyRef.current !== refreshKey
+ const isTimeStale =
+ !filesCache || Date.now() - filesCache.updatedAt > LIBRARY_CACHE_TTL_MS
+
+ if (hasCache && !isRefreshStale && !isTimeStale) {
+ return
+ }
+
+ const loadReason = !hasCache ? 'cold' : isRefreshStale ? 'refresh' : 'ttl'
+ let cancelled = false
+ listFiles({ limit: LIBRARY_PAGE_SIZE }).then(result => {
+ if (cancelled) return
if (!result.success) {
- captureClient('library_list_load_failed', {
+ captureClient('library_files_load_failed', {
source: 'network',
- reason: 'load_more',
+ reason: loadReason,
error: result.error ?? 'unknown'
})
- toast.error(result.error ?? 'Failed to load library')
+ toast.error(result.error ?? 'Failed to load files')
return
}
- const nextNotes = result.notes ?? []
- appendNotesCache({
- notes: nextNotes,
+ const nextFiles = result.files ?? []
+ replaceFilesCache({
+ files: nextFiles,
nextCursor: result.nextCursor ?? null,
hasMore: Boolean(result.hasMore)
})
- captureClient('library_list_loaded', {
+ lastFetchedFilesRefreshKeyRef.current = refreshKey
+ captureClient('library_files_loaded', {
source: 'network',
- reason: 'load_more',
- noteCount: nextNotes.length,
- hasMore: Boolean(result.hasMore),
- isEmpty: nextNotes.length === 0
+ reason: loadReason,
+ fileCount: nextFiles.length,
+ isEmpty: nextFiles.length === 0
})
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [filesCache, isOpen, refreshKey, replaceFilesCache])
+
+ const handleLoadMore = useCallback(async () => {
+ if (isLoadingMore) return
+
+ const shouldLoadNotes =
+ (activeTab === 'all' || activeTab === 'notes') &&
+ notesCache?.hasMore &&
+ notesCache.nextCursor
+ const shouldLoadFiles =
+ (activeTab === 'all' || activeTab === 'files') &&
+ filesCache?.hasMore &&
+ filesCache.nextCursor
+
+ if (!shouldLoadNotes && !shouldLoadFiles) return
+
+ setIsLoadingMore(true)
+ try {
+ await Promise.all([
+ shouldLoadNotes
+ ? listNotes({
+ limit: LIBRARY_PAGE_SIZE,
+ cursor: notesCache.nextCursor
+ }).then(result => {
+ if (!result.success) {
+ captureClient('library_list_load_failed', {
+ source: 'network',
+ reason: 'load_more',
+ error: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to load library')
+ return
+ }
+
+ const nextNotes = result.notes ?? []
+ appendNotesCache({
+ notes: nextNotes,
+ nextCursor: result.nextCursor ?? null,
+ hasMore: Boolean(result.hasMore)
+ })
+ captureClient('library_list_loaded', {
+ source: 'network',
+ reason: 'load_more',
+ noteCount: nextNotes.length,
+ hasMore: Boolean(result.hasMore),
+ isEmpty: nextNotes.length === 0
+ })
+ })
+ : Promise.resolve(),
+ shouldLoadFiles
+ ? listFiles({
+ limit: LIBRARY_PAGE_SIZE,
+ cursor: filesCache.nextCursor
+ }).then(result => {
+ if (!result.success) {
+ captureClient('library_files_load_failed', {
+ source: 'network',
+ reason: 'load_more',
+ error: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to load files')
+ return
+ }
+
+ const nextFiles = result.files ?? []
+ appendFilesCache({
+ files: nextFiles,
+ nextCursor: result.nextCursor ?? null,
+ hasMore: Boolean(result.hasMore)
+ })
+ captureClient('library_files_loaded', {
+ source: 'network',
+ reason: 'load_more',
+ fileCount: nextFiles.length,
+ hasMore: Boolean(result.hasMore),
+ isEmpty: nextFiles.length === 0
+ })
+ })
+ : Promise.resolve()
+ ])
} finally {
setIsLoadingMore(false)
}
- }, [appendNotesCache, isLoadingMore, notesCache])
+ }, [
+ activeTab,
+ appendFilesCache,
+ appendNotesCache,
+ filesCache,
+ isLoadingMore,
+ notesCache
+ ])
useEffect(() => {
- if (!isOpen || selectedNote || !notesCache?.hasMore || isLoadingMore) return
+ const canLoadMoreNotes =
+ (activeTab === 'all' || activeTab === 'notes') &&
+ notesCache?.hasMore &&
+ notesCache.nextCursor
+ const canLoadMoreFiles =
+ (activeTab === 'all' || activeTab === 'files') &&
+ filesCache?.hasMore &&
+ filesCache.nextCursor
+
+ if (
+ !isOpen ||
+ selectedNote ||
+ selectedFile ||
+ isLoadingMore ||
+ (!canLoadMoreNotes && !canLoadMoreFiles)
+ ) {
+ return
+ }
const sentinel = loadMoreRef.current
const scrollRoot = listScrollRef.current
@@ -293,17 +425,72 @@ export function LibraryPanel() {
return () => {
observer.disconnect()
}
- }, [handleLoadMore, isLoadingMore, isOpen, notesCache?.hasMore, selectedNote])
-
- const visibleNotes = notesCache?.notes ?? []
+ }, [
+ activeTab,
+ filesCache?.hasMore,
+ filesCache?.nextCursor,
+ handleLoadMore,
+ isLoadingMore,
+ isOpen,
+ notesCache?.hasMore,
+ notesCache?.nextCursor,
+ selectedFile,
+ selectedNote
+ ])
+
+ const visibleNotes = useMemo(() => notesCache?.notes ?? [], [notesCache])
+ const visibleFiles = useMemo(() => filesCache?.files ?? [], [filesCache])
const isLoading = !notesCache && !hasLoadAttempted
+ const isFilesLoading = !filesCache
+ const isActiveTabLoading =
+ activeTab === 'notes'
+ ? isLoading
+ : activeTab === 'files'
+ ? isFilesLoading
+ : isLoading || isFilesLoading
+ const emptyMessage =
+ activeTab === 'notes'
+ ? 'No notes yet.'
+ : activeTab === 'files'
+ ? 'No files yet.'
+ : 'No library items yet.'
const selectedTitle = useMemo(
- () => stripMarkdownTitle(selectedNote?.title ?? ''),
- [selectedNote?.title]
+ () =>
+ selectedNote
+ ? stripMarkdownTitle(selectedNote.title)
+ : selectedFile?.filename || '',
+ [selectedFile?.filename, selectedNote]
)
+ const hasSelectedItem = Boolean(selectedNote || selectedFile)
+ const hasMoreVisibleItems =
+ ((activeTab === 'all' || activeTab === 'notes') &&
+ Boolean(notesCache?.hasMore && notesCache.nextCursor)) ||
+ ((activeTab === 'all' || activeTab === 'files') &&
+ Boolean(filesCache?.hasMore && filesCache.nextCursor))
+ const visibleLibraryItems = useMemo(() => {
+ const noteItems = visibleNotes.map(note => ({
+ kind: 'note' as const,
+ item: note,
+ updatedAt: note.updatedAt
+ }))
+ const fileItems = visibleFiles.map(file => ({
+ kind: 'file' as const,
+ item: file,
+ updatedAt: file.updatedAt
+ }))
+
+ return [
+ ...(activeTab === 'files' ? [] : noteItems),
+ ...(activeTab === 'notes' ? [] : fileItems)
+ ].sort(
+ (a, b) =>
+ new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
+ )
+ }, [activeTab, visibleFiles, visibleNotes])
function handleOpenNote(note: Note) {
setSelectedNote(note)
+ setSelectedFile(null)
captureClient('note_opened', {
source: 'library_list',
noteId: note.id,
@@ -311,41 +498,86 @@ export function LibraryPanel() {
})
}
+ function handleOpenFile(file: LibraryFileItem) {
+ setSelectedFile(file)
+ setSelectedNote(null)
+ captureClient('library_file_opened', {
+ source: 'library_list',
+ fileId: file.id,
+ mediaType: file.mediaType,
+ fileCount: visibleFiles.length
+ })
+ }
+
function handleCloseLibrary(source: 'panel_header' | 'detail_header') {
closeLibrary()
- captureClient('library_closed', { source })
+ captureClient('library_closed', { source, tab: activeTab })
}
function handleRequestDeleteNote(
note: Note,
source: 'library_list' | 'library_detail'
) {
- setDeleteTarget(note)
+ setDeleteTarget({ kind: 'note', item: note, source })
captureClient('note_delete_requested', { source, noteId: note.id })
}
- function handleDeleteNote() {
+ function handleRequestDeleteFile(
+ file: LibraryFileItem,
+ source: 'library_list' | 'library_detail'
+ ) {
+ setDeleteTarget({ kind: 'file', item: file, source })
+ captureClient('library_file_delete_requested', {
+ source,
+ fileId: file.id,
+ mediaType: file.mediaType
+ })
+ }
+
+ function handleDeleteItem() {
if (!deleteTarget) return
- const noteId = deleteTarget.id
+ const target = deleteTarget
setDeleteTarget(null)
startDeleteTransition(async () => {
- const result = await deleteNote(noteId)
+ const result =
+ target.kind === 'note'
+ ? await deleteNote(target.item.id)
+ : await deleteFile(target.item.id)
if (!result.success) {
- captureClient('note_delete_failed', {
- noteId,
- reason: result.error ?? 'unknown'
- })
- toast.error(result.error ?? 'Failed to delete note')
+ captureClient(
+ target.kind === 'note'
+ ? 'note_delete_failed'
+ : 'library_file_delete_failed',
+ {
+ itemId: target.item.id,
+ reason: result.error ?? 'unknown'
+ }
+ )
+ toast.error(result.error ?? 'Failed to delete item')
return
}
- captureClient('note_deleted', { noteId })
- toast.success('Note deleted')
- if (selectedNote?.id === noteId) {
+ captureClient(
+ target.kind === 'note' ? 'note_deleted' : 'library_file_deleted',
+ { itemId: target.item.id }
+ )
+ toast.success(
+ target.kind === 'note' ? 'Note deleted' : 'File removed from Library'
+ )
+ if (target.kind === 'note' && selectedNote?.id === target.item.id) {
setSelectedNote(null)
+ } else if (
+ target.kind === 'file' &&
+ selectedFile?.id === target.item.id
+ ) {
+ setSelectedFile(null)
+ }
+ if (target.kind === 'note') {
+ removeCachedNote(target.item.id)
+ } else {
+ removeCachedFile(target.item.id)
}
- removeCachedNote(noteId)
})
}
@@ -354,7 +586,7 @@ export function LibraryPanel() {
<div className="flex h-full min-h-0 flex-col overflow-hidden bg-muted md:px-4 md:pt-14 md:pb-4">
<div className="flex h-full flex-col overflow-hidden bg-background md:rounded-xl md:border">
<div className="flex items-center justify-between px-4 py-2">
- {selectedNote ? (
+ {hasSelectedItem ? (
<>
<div className="flex min-w-0 items-center gap-2">
<TooltipButton
@@ -362,7 +594,10 @@ export function LibraryPanel() {
variant="ghost"
size="icon"
className="size-8 shrink-0"
- onClick={() => setSelectedNote(null)}
+ onClick={() => {
+ setSelectedNote(null)
+ setSelectedFile(null)
+ }}
aria-label="Back to library"
tooltipContent="Back"
>
@@ -370,16 +605,27 @@ export function LibraryPanel() {
</TooltipButton>
<div className="min-w-0">
<h3 className="truncate text-sm font-medium">
- {selectedTitle || 'Untitled note'}
+ {selectedTitle || 'Untitled item'}
</h3>
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
- <NoteActionsMenu
- onDelete={() =>
- handleRequestDeleteNote(selectedNote, 'library_detail')
- }
- />
+ {selectedNote && (
+ <LibraryItemActionsMenu
+ deleteLabel="Delete Note"
+ onDelete={() =>
+ handleRequestDeleteNote(selectedNote, 'library_detail')
+ }
+ />
+ )}
+ {selectedFile && (
+ <LibraryItemActionsMenu
+ deleteLabel="Remove from Library"
+ onDelete={() =>
+ handleRequestDeleteFile(selectedFile, 'library_detail')
+ }
+ />
+ )}
<TooltipButton
variant="ghost"
size="icon"
@@ -425,26 +671,125 @@ export function LibraryPanel() {
Saved {formatNoteDate(selectedNote.createdAt)}
</footer>
</div>
+ ) : selectedFile ? (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div
+ data-vaul-no-drag
+ className="min-h-0 flex-1 overflow-y-auto p-4"
+ >
+ {selectedFile.mediaType.startsWith('image/') ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={selectedFile.url}
+ alt={selectedFile.filename}
+ className="max-h-[48vh] w-full rounded-md border object-contain"
+ />
+ ) : (
+ <div className="flex aspect-video items-center justify-center rounded-md border bg-muted/40">
+ <FileIcon className="size-10 text-muted-foreground" />
+ </div>
+ )}
+ <div className="mt-4 space-y-3 text-sm">
+ <div>
+ <p className="text-xs text-muted-foreground">Filename</p>
+ <p className="break-words font-medium">
+ {selectedFile.filename}
+ </p>
+ </div>
+ <div className="grid grid-cols-2 gap-3 text-xs">
+ <div>
+ <p className="text-muted-foreground">Type</p>
+ <p className="mt-0.5 break-words">
+ {selectedFile.mediaType}
+ </p>
+ </div>
+ <div>
+ <p className="text-muted-foreground">Size</p>
+ <p className="mt-0.5">{formatBytes(selectedFile.size)}</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <footer className="shrink-0 border-t px-4 py-2 text-xs text-muted-foreground">
+ Added {formatNoteDate(selectedFile.createdAt)}
+ </footer>
+ </div>
) : (
<div
ref={listScrollRef}
data-vaul-no-drag
className="min-h-0 flex-1 overflow-y-auto p-2"
>
- {isLoading ? (
+ <div className="mb-2 flex gap-1 px-1">
+ {(['all', 'notes', 'files'] as const).map(tab => (
+ <Button
+ key={tab}
+ type="button"
+ size="sm"
+ variant={activeTab === tab ? 'secondary' : 'ghost'}
+ className="h-7 rounded-md px-2 text-xs capitalize"
+ onClick={() => {
+ setActiveTab(tab)
+ captureClient('library_tab_selected', { tab })
+ }}
+ >
+ {tab}
+ </Button>
+ ))}
+ </div>
+ {isActiveTabLoading ? (
<LibraryLoadingSkeleton />
- ) : visibleNotes.length === 0 ? (
+ ) : visibleLibraryItems.length === 0 ? (
<div className="px-4 py-8 text-sm text-muted-foreground">
- No saved notes yet.
+ {emptyMessage}
</div>
) : (
<div className="space-y-1">
- {visibleNotes.map(note => {
+ {visibleLibraryItems.map(libraryItem => {
+ if (libraryItem.kind === 'file') {
+ const file = libraryItem.item
+ const Icon = fileIcon(file)
+ return (
+ <div
+ key={`file-${file.id}`}
+ className="group/note relative rounded-md hover:bg-accent"
+ >
+ <button
+ type="button"
+ className="w-full rounded-md px-3 py-2 pr-10 text-left text-sm transition-colors"
+ onClick={() => handleOpenFile(file)}
+ >
+ <div className="flex items-center gap-2">
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">
+ {file.filename}
+ </span>
+ </div>
+ <p className="mt-1 truncate text-xs text-muted-foreground">
+ {file.mediaType} · {formatBytes(file.size)}
+ </p>
+ <p className="mt-1 text-[11px] text-muted-foreground/75">
+ {formatNoteDate(file.updatedAt)}
+ </p>
+ </button>
+ <div className="absolute right-1 top-1.5 opacity-100 md:opacity-0 md:transition-opacity md:group-hover/note:opacity-100">
+ <LibraryItemActionsMenu
+ deleteLabel="Remove from Library"
+ onDelete={() =>
+ handleRequestDeleteFile(file, 'library_list')
+ }
+ />
+ </div>
+ </div>
+ )
+ }
+
+ const note = libraryItem.item
const title =
stripMarkdownTitle(note.title) || 'Untitled note'
return (
<div
- key={note.id}
+ key={`note-${note.id}`}
className="group/note relative rounded-md hover:bg-accent"
>
<button
@@ -466,7 +811,8 @@ export function LibraryPanel() {
</p>
</button>
<div className="absolute right-1 top-1.5 opacity-100 md:opacity-0 md:transition-opacity md:group-hover/note:opacity-100">
- <NoteActionsMenu
+ <LibraryItemActionsMenu
+ deleteLabel="Delete Note"
onDelete={() =>
handleRequestDeleteNote(note, 'library_list')
}
@@ -475,7 +821,7 @@ export function LibraryPanel() {
</div>
)
})}
- {notesCache?.hasMore && (
+ {hasMoreVisibleItems && (
<div
ref={loadMoreRef}
className="flex h-10 items-center justify-center text-muted-foreground"
@@ -500,10 +846,15 @@ export function LibraryPanel() {
>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>Delete this note?</AlertDialogTitle>
+ <AlertDialogTitle>
+ {deleteTarget?.kind === 'file'
+ ? 'Remove this file from Library?'
+ : `Delete this ${deleteTarget?.kind ?? 'item'}?`}
+ </AlertDialogTitle>
<AlertDialogDescription>
- This action cannot be undone. The saved note will be permanently
- deleted from your library.
+ {deleteTarget?.kind === 'file'
+ ? 'This removes the file from Library. Existing chat history and stored attachments are not deleted.'
+ : 'This action cannot be undone. The saved item will be permanently removed from your library.'}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -512,7 +863,7 @@ export function LibraryPanel() {
disabled={isDeleting}
onClick={event => {
event.preventDefault()
- handleDeleteNote()
+ handleDeleteItem()
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
@@ -520,6 +871,8 @@ export function LibraryPanel() {
<div className="flex items-center justify-center">
<Spinner />
</div>
+ ) : deleteTarget?.kind === 'file' ? (
+ 'Remove'
) : (
'Delete'
)}
diff --git a/components/library/library-picker-dialog.tsx b/components/library/library-picker-dialog.tsx
new file mode 100644
index 00000000..bf42ab64
--- /dev/null
+++ b/components/library/library-picker-dialog.tsx
@@ -0,0 +1,352 @@
+'use client'
+
+import { useEffect, useMemo, useRef, useState } from 'react'
+
+import {
+ IconFile as FileIcon,
+ IconFileText as FileText,
+ IconPhoto as Photo
+} from '@tabler/icons-react'
+import { toast } from 'sonner'
+
+import type { LibraryFileItem } from '@/lib/actions/files'
+import { searchFiles } from '@/lib/actions/files'
+import { listFiles } from '@/lib/actions/files'
+import { listNotes, searchNotes } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
+import type { Note } from '@/lib/db/schema'
+import type { NoteContext, UploadedFile } from '@/lib/types'
+import { stripMarkdownText } from '@/lib/utils/markdown'
+
+import { Button } from '@/components/ui/button'
+import {
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList
+} from '@/components/ui/command'
+import { Spinner } from '@/components/ui/spinner'
+
+import { useLibrary } from './library-context'
+
+type LibraryFilter = 'all' | 'notes' | 'files'
+const PICKER_SEARCH_DEBOUNCE_MS = 120
+const SERVER_SEARCH_MIN_CHARS = 2
+
+function filterCachedNotes(notes: Note[], query: string) {
+ const normalizedQuery = query.toLowerCase()
+ return notes
+ .filter(note => {
+ const title = stripMarkdownText(note.title).toLowerCase()
+ const content = stripMarkdownText(note.content).toLowerCase()
+ return (
+ title.includes(normalizedQuery) || content.includes(normalizedQuery)
+ )
+ })
+ .slice(0, 12)
+}
+
+function filterCachedFiles(files: LibraryFileItem[], query: string) {
+ const normalizedQuery = query.toLowerCase()
+ return files
+ .filter(file => {
+ return (
+ file.filename.toLowerCase().includes(normalizedQuery) ||
+ file.mediaType.toLowerCase().includes(normalizedQuery)
+ )
+ })
+ .slice(0, 12)
+}
+
+function fileIcon(file: LibraryFileItem) {
+ if (file.mediaType.startsWith('image/')) return Photo
+ return FileIcon
+}
+
+function toUploadedFile(file: LibraryFileItem): UploadedFile {
+ return {
+ status: 'uploaded',
+ url: file.url,
+ key: file.key,
+ name: file.filename,
+ mediaType: file.mediaType,
+ libraryFileId: file.id
+ }
+}
+
+export function LibraryPickerDialog({
+ open,
+ onOpenChange,
+ onAttachNote,
+ onAttachFile
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onAttachNote: (note: NoteContext) => boolean
+ onAttachFile: (file: UploadedFile) => boolean
+}) {
+ const [query, setQuery] = useState('')
+ const [filter, setFilter] = useState<LibraryFilter>('all')
+ const [notes, setNotes] = useState<Note[]>([])
+ const [files, setFiles] = useState<LibraryFileItem[]>([])
+ const [isLoading, setIsLoading] = useState(false)
+ const requestSeqRef = useRef(0)
+ const {
+ notesCache,
+ filesCache,
+ replaceNotesCache,
+ replaceFilesCache,
+ refreshKey
+ } = useLibrary()
+
+ useEffect(() => {
+ if (!open) {
+ requestSeqRef.current += 1
+ queueMicrotask(() => setIsLoading(false))
+ return
+ }
+
+ const seq = ++requestSeqRef.current
+ const trimmed = query.trim()
+ const shouldLoadNotes = filter === 'all' || filter === 'notes'
+ const shouldLoadFiles = filter === 'all' || filter === 'files'
+ const cachedNotes = notesCache?.notes ?? []
+ const cachedFiles = filesCache?.files ?? []
+ const cachedResultNotes =
+ shouldLoadNotes && trimmed
+ ? filterCachedNotes(cachedNotes, trimmed)
+ : shouldLoadNotes
+ ? cachedNotes.slice(0, 12)
+ : []
+ const cachedResultFiles =
+ shouldLoadFiles && trimmed
+ ? filterCachedFiles(cachedFiles, trimmed)
+ : shouldLoadFiles
+ ? cachedFiles.slice(0, 12)
+ : []
+
+ const needsNotesFetch =
+ shouldLoadNotes &&
+ (!notesCache || trimmed.length >= SERVER_SEARCH_MIN_CHARS)
+ const needsFilesFetch =
+ shouldLoadFiles &&
+ (!filesCache || trimmed.length >= SERVER_SEARCH_MIN_CHARS)
+
+ queueMicrotask(() => {
+ if (seq !== requestSeqRef.current) return
+
+ setNotes(cachedResultNotes)
+ setFiles(cachedResultFiles)
+ setIsLoading(
+ (needsNotesFetch || needsFilesFetch) &&
+ cachedResultNotes.length === 0 &&
+ cachedResultFiles.length === 0
+ )
+ })
+
+ if (!needsNotesFetch && !needsFilesFetch) {
+ return
+ }
+
+ const timeout = setTimeout(async () => {
+ const emptyNotesResult: Awaited<ReturnType<typeof listNotes>> = {
+ success: true,
+ notes: []
+ }
+ const emptyFilesResult: Awaited<ReturnType<typeof listFiles>> = {
+ success: true,
+ files: []
+ }
+
+ const [notesResult, filesResult] = await Promise.all([
+ needsNotesFetch
+ ? trimmed
+ ? searchNotes({ query: trimmed, limit: 12 })
+ : listNotes({ limit: 12 })
+ : Promise.resolve(emptyNotesResult),
+ needsFilesFetch
+ ? trimmed
+ ? searchFiles({ query: trimmed, limit: 12 })
+ : listFiles({ limit: 12 })
+ : Promise.resolve(emptyFilesResult)
+ ])
+
+ if (seq !== requestSeqRef.current) return
+
+ setIsLoading(false)
+
+ if (!notesResult.success) {
+ toast.error(notesResult.error ?? 'Failed to load notes')
+ }
+ if (!filesResult.success) {
+ toast.error(filesResult.error ?? 'Failed to load files')
+ }
+
+ if (needsNotesFetch) {
+ setNotes(notesResult.notes ?? [])
+ }
+ if (needsFilesFetch) {
+ setFiles(filesResult.files ?? [])
+ }
+
+ if (!trimmed && notesResult.success && needsNotesFetch) {
+ const notesPage = notesResult as Awaited<ReturnType<typeof listNotes>>
+ replaceNotesCache({
+ notes: notesPage.notes ?? [],
+ nextCursor: notesPage.nextCursor ?? null,
+ hasMore: Boolean(notesPage.hasMore)
+ })
+ }
+ if (!trimmed && filesResult.success && needsFilesFetch) {
+ const filesPage = filesResult as Awaited<ReturnType<typeof listFiles>>
+ replaceFilesCache({
+ files: filesPage.files ?? [],
+ nextCursor: filesPage.nextCursor ?? null,
+ hasMore: Boolean(filesPage.hasMore)
+ })
+ }
+ }, PICKER_SEARCH_DEBOUNCE_MS)
+
+ return () => clearTimeout(timeout)
+ }, [
+ filesCache,
+ filter,
+ notesCache,
+ open,
+ query,
+ replaceFilesCache,
+ replaceNotesCache,
+ refreshKey
+ ])
+
+ function handleOpenChange(nextOpen: boolean) {
+ onOpenChange(nextOpen)
+ if (!nextOpen) {
+ setQuery('')
+ setFilter('all')
+ setIsLoading(false)
+ requestAnimationFrame(() => {
+ if (!document.querySelector('[role="dialog"][data-state="open"]')) {
+ document.body.style.pointerEvents = ''
+ }
+ })
+ }
+ }
+
+ const empty = notes.length === 0 && files.length === 0
+ const heading = useMemo(() => {
+ if (query.trim()) return 'Search results'
+ return 'Recent library items'
+ }, [query])
+
+ function handleAttachNote(note: Note) {
+ const attached = onAttachNote({
+ id: note.id,
+ title: note.title,
+ content: note.content
+ })
+ if (attached) {
+ captureClient('note_context_attached', {
+ source: 'picker',
+ noteId: note.id,
+ chars: note.content.length
+ })
+ }
+ handleOpenChange(false)
+ }
+
+ function handleAttachFile(file: LibraryFileItem) {
+ const attached = onAttachFile(toUploadedFile(file))
+ if (attached) {
+ captureClient('library_file_attached', {
+ source: 'picker',
+ fileId: file.id,
+ mediaType: file.mediaType
+ })
+ }
+ handleOpenChange(false)
+ }
+
+ return (
+ <CommandDialog modal={false} open={open} onOpenChange={handleOpenChange}>
+ <div className="flex items-center gap-1 border-b px-3 py-2">
+ {(['all', 'notes', 'files'] as const).map(value => (
+ <Button
+ key={value}
+ type="button"
+ size="sm"
+ variant={filter === value ? 'secondary' : 'ghost'}
+ className="h-7 rounded-md px-2 text-xs capitalize"
+ onClick={() => setFilter(value)}
+ >
+ {value}
+ </Button>
+ ))}
+ </div>
+ <CommandInput
+ value={query}
+ onValueChange={setQuery}
+ placeholder="Search notes and files..."
+ />
+ <CommandList className="h-[420px] max-h-[calc(100vh-14rem)]">
+ {isLoading && (
+ <div className="flex items-center gap-2 px-4 py-3 text-sm text-muted-foreground">
+ <Spinner /> Loading library
+ </div>
+ )}
+ {!isLoading && empty && (
+ <CommandEmpty>No library items found.</CommandEmpty>
+ )}
+ {!isLoading && !empty && (
+ <CommandGroup heading={heading}>
+ {notes.map(note => (
+ <CommandItem
+ key={`note-${note.id}`}
+ value={`note-${note.id}-${stripMarkdownText(note.title)}`}
+ onSelect={() => handleAttachNote(note)}
+ >
+ <FileText className="size-4 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">
+ {stripMarkdownText(note.title) || 'Untitled note'}
+ </p>
+ <p className="line-clamp-1 text-xs text-muted-foreground">
+ {stripMarkdownText(note.content)}
+ </p>
+ </div>
+ <span className="shrink-0 text-[11px] text-muted-foreground">
+ Note
+ </span>
+ </CommandItem>
+ ))}
+ {files.map(file => {
+ const Icon = fileIcon(file)
+ return (
+ <CommandItem
+ key={`file-${file.id}`}
+ value={`file-${file.id}-${file.filename}`}
+ onSelect={() => handleAttachFile(file)}
+ >
+ <Icon className="size-4 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">
+ {file.filename}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {file.mediaType}
+ </p>
+ </div>
+ <span className="shrink-0 text-[11px] text-muted-foreground">
+ File
+ </span>
+ </CommandItem>
+ )
+ })}
+ </CommandGroup>
+ )}
+ </CommandList>
+ </CommandDialog>
+ )
+}
diff --git a/components/render-message.tsx b/components/render-message.tsx
index 3973d8b2..e1b3d0df 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -66,6 +66,12 @@ export function RenderMessage({
const quotedContexts = parts
.filter((part: any) => part.type === 'data-quotedContext')
.map((part: any) => part.data?.text ?? '')
+ const noteContexts = parts
+ .filter((part: any) => part.type === 'data-noteContext')
+ .map((part: any) => ({
+ title: part.data?.title,
+ text: part.data?.text ?? ''
+ }))
const urls = parts
.filter((part: any) => part.type === 'data-sourceUrl')
.map((part: any) => part.data?.url ?? '')
@@ -84,11 +90,13 @@ export function RenderMessage({
{(textPart ||
pastedTexts.length > 0 ||
quotedContexts.length > 0 ||
+ noteContexts.length > 0 ||
urls.length > 0) && (
<UserTextSection
content={textPart?.text ?? ''}
pastedTexts={pastedTexts}
quotedContexts={quotedContexts}
+ noteContexts={noteContexts}
urls={urls}
messageId={messageId}
onUpdateMessage={onUpdateMessage}
diff --git a/components/ui/command.tsx b/components/ui/command.tsx
index 664430b1..7eba3b3a 100644
--- a/components/ui/command.tsx
+++ b/components/ui/command.tsx
@@ -8,7 +8,7 @@ import { Command as CommandPrimitive } from 'cmdk'
import { cn } from '@/lib/utils'
-import { Dialog, DialogContent } from '@/components/ui/dialog'
+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
@@ -28,7 +28,11 @@ Command.displayName = CommandPrimitive.displayName
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
- <DialogContent className="overflow-hidden p-0 shadow-lg">
+ <DialogContent
+ aria-describedby={undefined}
+ className="overflow-hidden p-0 shadow-lg"
+ >
+ <DialogTitle className="sr-only">Command menu</DialogTitle>
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
diff --git a/components/uploaded-file-list.tsx b/components/uploaded-file-list.tsx
index cceed53c..312ddd7a 100644
--- a/components/uploaded-file-list.tsx
+++ b/components/uploaded-file-list.tsx
@@ -1,7 +1,6 @@
'use client'
import React from 'react'
-import Image from 'next/image'
import { IconLoader2 as Loader2, IconX as X } from '@tabler/icons-react'
@@ -20,59 +19,88 @@ export const UploadedFileList = React.memo(function UploadedFileList({
<div className="w-full flex p-4 max-w-3xl mx-auto">
<div className="flex gap-6 overflow-x-auto">
{files.map((it, index) => {
- const mediaType = it.mediaType ?? it.file?.type ?? ''
- const filename = it.name ?? it.file?.name ?? 'file'
- const isImage = mediaType.startsWith('image/')
-
return (
- <div
+ <UploadedFileListItem
key={index}
- className="relative w-20 shrink-0 flex flex-col items-center"
- >
- <div className="relative w-20 aspect-7/5 rounded-lg overflow-hidden shadow-sm border bg-muted/20 dark:bg-muted/10">
- {isImage && it.file ? (
- <Image
- src={URL.createObjectURL(it.file)}
- alt={`file-${index}`}
- fill
- className="object-cover"
- sizes="112px"
- />
- ) : isImage && it.url ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={it.url}
- alt={`file-${index}`}
- className="size-full object-cover"
- />
- ) : (
- <div className="w-full h-full flex items-center justify-center text-sm font-semibold bg-gray-300 dark:bg-gray-700">
- {filename.split('.').pop()?.toUpperCase()}
- </div>
- )}
+ file={it}
+ index={index}
+ onRemove={onRemove}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )
+})
+
+const UploadedFileListItem = React.memo(function UploadedFileListItem({
+ file,
+ index,
+ onRemove
+}: {
+ file: UploadedFile
+ index: number
+ onRemove: (index: number) => void
+}) {
+ const [objectUrl, setObjectUrl] = React.useState<
+ { file: File; url: string } | undefined
+ >()
+ const mediaType = file.mediaType ?? file.file?.type ?? ''
+ const filename = file.name ?? file.file?.name ?? 'file'
+ const isImage = mediaType.startsWith('image/')
+ const imageSrc =
+ file.url && file.status === 'uploaded'
+ ? file.url
+ : objectUrl && objectUrl.file === file.file
+ ? objectUrl.url
+ : undefined
- {/* Spinner overlay while uploading */}
- {it.status === 'uploading' && (
- <div className="absolute inset-0 bg-black/40 flex items-center justify-center z-10">
- <Loader2 className="animate-spin text-white" size={20} />
- </div>
- )}
+ React.useEffect(() => {
+ if ((file.url && file.status === 'uploaded') || !file.file) {
+ setObjectUrl(undefined)
+ return
+ }
- <button
- type="button"
- onClick={() => onRemove(index)}
- className="absolute top-1 right-1 bg-black/40 hover:bg-red-600 text-white rounded-full p-1 z-20"
- >
- <X size={12} />
- </button>
- </div>
+ const nextObjectUrl = URL.createObjectURL(file.file)
+ setObjectUrl({ file: file.file, url: nextObjectUrl })
- <div className="mt-2 text-xs text-center text-foreground truncate w-full">
- {filename}
- </div>
- </div>
- )
- })}
+ return () => URL.revokeObjectURL(nextObjectUrl)
+ }, [file.file, file.status, file.url])
+
+ return (
+ <div className="relative w-20 shrink-0 flex flex-col items-center">
+ <div className="relative w-20 aspect-7/5 rounded-lg overflow-hidden shadow-sm border bg-muted/20 dark:bg-muted/10">
+ {isImage && imageSrc ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={imageSrc}
+ alt={`file-${index}`}
+ className="size-full object-cover"
+ />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-sm font-semibold bg-gray-300 dark:bg-gray-700">
+ {filename.split('.').pop()?.toUpperCase()}
+ </div>
+ )}
+
+ {/* Spinner overlay while uploading */}
+ {file.status === 'uploading' && (
+ <div className="absolute inset-0 bg-black/40 flex items-center justify-center z-10">
+ <Loader2 className="animate-spin text-white" size={20} />
+ </div>
+ )}
+
+ <button
+ type="button"
+ onClick={() => onRemove(index)}
+ className="absolute top-1 right-1 bg-black/40 hover:bg-red-600 text-white rounded-full p-1 z-20"
+ >
+ <X size={12} />
+ </button>
+ </div>
+
+ <div className="mt-2 text-xs text-center text-foreground truncate w-full">
+ {filename}
</div>
</div>
)
diff --git a/components/user-text-section.tsx b/components/user-text-section.tsx
index 7ab9c7c3..9e38db9f 100644
--- a/components/user-text-section.tsx
+++ b/components/user-text-section.tsx
@@ -12,6 +12,7 @@ import {
} from '@tabler/icons-react'
import { cn } from '@/lib/utils'
+import { stripMarkdownText } from '@/lib/utils/markdown'
import { Button } from './ui/button'
import { CollapsibleMessage } from './collapsible-message'
@@ -41,6 +42,7 @@ interface UserTextSectionProps {
// Pasted attachments (new data parts), placed below the instruction.
pastedTexts?: string[]
quotedContexts?: string[]
+ noteContexts?: { title?: string; text: string }[]
urls?: string[]
messageId?: string
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
@@ -50,6 +52,7 @@ export const UserTextSection: React.FC<UserTextSectionProps> = ({
content,
pastedTexts = [],
quotedContexts = [],
+ noteContexts = [],
urls = [],
messageId,
onUpdateMessage
@@ -181,6 +184,7 @@ export const UserTextSection: React.FC<UserTextSectionProps> = ({
// Pasted attachments (cards + URL chips), placed below the instruction.
const attachments = (cards.length > 0 ||
quotedContexts.length > 0 ||
+ noteContexts.length > 0 ||
urls.length > 0) && (
<div className="mt-2 flex flex-col items-start gap-1.5">
{cards.map((c, i) => (
@@ -193,6 +197,17 @@ export const UserTextSection: React.FC<UserTextSectionProps> = ({
label="Quoted context"
/>
))}
+ {noteContexts.map((note, i) => (
+ <PastedContentCard
+ key={`note-context-${i}`}
+ text={stripMarkdownText(note.text)}
+ label={
+ note.title
+ ? `Note: ${stripMarkdownText(note.title) || 'Untitled note'}`
+ : 'Note'
+ }
+ />
+ ))}
{urls.map((u, i) => (
<UrlChip key={`url-${i}`} url={u} />
))}
diff --git a/drizzle/0015_library_file_object_keys_only.sql b/drizzle/0015_library_file_object_keys_only.sql
new file mode 100644
index 00000000..86a52317
--- /dev/null
+++ b/drizzle/0015_library_file_object_keys_only.sql
@@ -0,0 +1,42 @@
+ALTER TABLE "files" ADD COLUMN IF NOT EXISTS "object_key" text;
+
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'files'
+ AND column_name = 'url'
+ ) THEN
+ WITH normalized_file_urls AS (
+ SELECT
+ "id",
+ split_part(regexp_replace("url", '^https?://[^/]+/', ''), '?', 1) AS "url_path"
+ FROM "files"
+ WHERE "object_key" IS NULL
+ AND "url" IS NOT NULL
+ )
+ UPDATE "files"
+ SET "object_key" = NULLIF(
+ CASE
+ WHEN normalized_file_urls."url_path" ~ '^[^/]+/[^/]+/chats/' THEN
+ regexp_replace(
+ normalized_file_urls."url_path",
+ '^[^/]+/([^/]+/chats/.*)$',
+ '\1'
+ )
+ ELSE normalized_file_urls."url_path"
+ END,
+ ''
+ )
+ FROM normalized_file_urls
+ WHERE "files"."id" = normalized_file_urls."id";
+ END IF;
+END $$;
+
+ALTER TABLE "files" ALTER COLUMN "object_key" SET NOT NULL;
+
+CREATE INDEX IF NOT EXISTS "files_object_key_idx" ON "files" USING btree ("object_key");
+
+ALTER TABLE "files" DROP COLUMN IF EXISTS "url";
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 2c4de07e..65b4f423 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -106,6 +106,13 @@
"when": 1782345600000,
"tag": "0014_private_file_object_keys",
"breakpoints": true
+ },
+ {
+ "idx": 15,
+ "version": "7",
+ "when": 1782604800000,
+ "tag": "0015_library_file_object_keys_only",
+ "breakpoints": true
}
]
}
diff --git a/drizzle/schema.ts b/drizzle/schema.ts
index d58e712c..02a59d0e 100644
--- a/drizzle/schema.ts
+++ b/drizzle/schema.ts
@@ -261,8 +261,7 @@ export const files = pgTable(
userId: varchar('user_id', { length: 255 }).notNull(),
chatId: varchar('chat_id', { length: 191 }),
filename: text().notNull(),
- url: text().notNull(),
- objectKey: text('object_key'),
+ objectKey: text('object_key').notNull(),
mediaType: varchar('media_type', { length: 256 }).notNull(),
size: integer(),
createdAt: timestamp('created_at', { mode: 'string' })
diff --git a/hooks/use-file-dropzone.ts b/hooks/use-file-dropzone.ts
index 5adf4e01..b6f5cbd2 100644
--- a/hooks/use-file-dropzone.ts
+++ b/hooks/use-file-dropzone.ts
@@ -87,7 +87,8 @@ export function useFileDropzone({
url: uploaded.url,
name: uploaded.filename,
key: uploaded.key,
- mediaType: uploaded.mediaType
+ mediaType: uploaded.mediaType,
+ libraryFileId: uploaded.id
}
: f
)
diff --git a/lib/actions/__tests__/files.test.ts b/lib/actions/__tests__/files.test.ts
new file mode 100644
index 00000000..8087a541
--- /dev/null
+++ b/lib/actions/__tests__/files.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
+import { getSignedFileUrl } from '@/lib/storage/r2-client'
+
+import { deleteFile, listFiles, searchFiles } from '../files'
+
+vi.mock('@/lib/auth/get-current-user')
+vi.mock('@/lib/db/actions')
+vi.mock('@/lib/storage/r2-client')
+
+const originalEnableAuth = process.env.ENABLE_AUTH
+
+const libraryFile = {
+ id: 'file-1',
+ userId: 'user-1',
+ chatId: 'chat-1',
+ filename: 'report.pdf',
+ objectKey: 'user-1/chats/chat-1/report.pdf',
+ mediaType: 'application/pdf',
+ size: 1024,
+ createdAt: new Date('2026-06-24T00:00:00Z'),
+ updatedAt: new Date('2026-06-24T00:00:00Z')
+}
+
+describe('File Actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ process.env.ENABLE_AUTH = 'true'
+ vi.mocked(getCurrentUserId).mockResolvedValue('user-1')
+ vi.mocked(dbActions.getLibraryFiles).mockResolvedValue({
+ files: [libraryFile],
+ nextCursor: null,
+ hasMore: false
+ })
+ vi.mocked(dbActions.searchLibraryFiles).mockResolvedValue([libraryFile])
+ vi.mocked(dbActions.deleteLibraryFile).mockResolvedValue({ success: true })
+ vi.mocked(getSignedFileUrl).mockResolvedValue(
+ 'https://signed.example.com/report.pdf'
+ )
+ })
+
+ afterEach(() => {
+ process.env.ENABLE_AUTH = originalEnableAuth
+ })
+
+ it('lists current user files', async () => {
+ const result = await listFiles()
+
+ expect(result).toEqual({
+ success: true,
+ files: [
+ {
+ ...libraryFile,
+ key: 'user-1/chats/chat-1/report.pdf',
+ url: 'https://signed.example.com/report.pdf'
+ }
+ ],
+ nextCursor: null,
+ hasMore: false
+ })
+ expect(dbActions.getLibraryFiles).toHaveBeenCalledWith('user-1', {
+ limit: 25,
+ cursor: undefined
+ })
+ })
+
+ it('searches current user files', async () => {
+ const result = await searchFiles({ query: 'report', limit: 5 })
+
+ expect(result).toEqual({
+ success: true,
+ files: [
+ {
+ ...libraryFile,
+ key: 'user-1/chats/chat-1/report.pdf',
+ url: 'https://signed.example.com/report.pdf'
+ }
+ ]
+ })
+ expect(dbActions.searchLibraryFiles).toHaveBeenCalledWith(
+ 'user-1',
+ 'report',
+ { limit: 5 }
+ )
+ })
+
+ it('deletes a current user file', async () => {
+ const result = await deleteFile('file-1')
+
+ expect(result).toEqual({ success: true })
+ expect(dbActions.deleteLibraryFile).toHaveBeenCalledWith('file-1', 'user-1')
+ })
+
+ it('rejects anonymous mode', async () => {
+ process.env.ENABLE_AUTH = 'false'
+
+ const result = await listFiles()
+
+ expect(result).toEqual({
+ success: false,
+ files: [],
+ error: 'Library is unavailable in anonymous mode.'
+ })
+ expect(dbActions.getLibraryFiles).not.toHaveBeenCalled()
+ })
+})
diff --git a/lib/actions/files.ts b/lib/actions/files.ts
new file mode 100644
index 00000000..86e1fc1d
--- /dev/null
+++ b/lib/actions/files.ts
@@ -0,0 +1,129 @@
+'use server'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
+import type { LibraryFile } from '@/lib/db/schema'
+import { getSignedFileUrl } from '@/lib/storage/r2-client'
+
+const DEFAULT_FILES_PAGE_SIZE = 25
+
+export type FilesListCursor = {
+ updatedAt: string
+ id: string
+}
+
+export type LibraryFileItem = LibraryFile & {
+ key: string
+ url: string
+}
+
+async function signLibraryFile(file: LibraryFile): Promise<LibraryFileItem> {
+ return {
+ ...file,
+ key: file.objectKey,
+ url: await getSignedFileUrl(file.objectKey)
+ }
+}
+
+async function signLibraryFiles(
+ files: LibraryFile[]
+): Promise<LibraryFileItem[]> {
+ return Promise.all(files.map(file => signLibraryFile(file)))
+}
+
+async function requireLibraryFileUserId() {
+ if (process.env.ENABLE_AUTH === 'false') {
+ return {
+ userId: null,
+ error: 'Library is unavailable in anonymous mode.'
+ }
+ }
+
+ const userId = await getCurrentUserId()
+ if (!userId) {
+ return { userId: null, error: 'Sign in to use library files.' }
+ }
+
+ return { userId, error: null }
+}
+
+export async function listFiles({
+ limit = DEFAULT_FILES_PAGE_SIZE,
+ cursor
+}: {
+ limit?: number
+ cursor?: FilesListCursor | null
+} = {}): Promise<{
+ success: boolean
+ files?: LibraryFileItem[]
+ nextCursor?: FilesListCursor | null
+ hasMore?: boolean
+ error?: string
+}> {
+ const { userId, error } = await requireLibraryFileUserId()
+ if (!userId) {
+ return {
+ success: false,
+ files: [],
+ error: error ?? 'User not authenticated'
+ }
+ }
+
+ try {
+ const page = await dbActions.getLibraryFiles(userId, {
+ limit,
+ cursor: cursor ?? undefined
+ })
+ return {
+ success: true,
+ files: await signLibraryFiles(page.files),
+ nextCursor: page.nextCursor,
+ hasMore: page.hasMore
+ }
+ } catch (error) {
+ console.error('Error listing files:', error)
+ return {
+ success: false,
+ files: [],
+ nextCursor: null,
+ hasMore: false,
+ error: 'Failed to load files.'
+ }
+ }
+}
+
+export async function searchFiles({
+ query,
+ limit = DEFAULT_FILES_PAGE_SIZE
+}: {
+ query: string
+ limit?: number
+}): Promise<{ success: boolean; files?: LibraryFileItem[]; error?: string }> {
+ const { userId, error } = await requireLibraryFileUserId()
+ if (!userId) {
+ return {
+ success: false,
+ files: [],
+ error: error ?? 'User not authenticated'
+ }
+ }
+
+ try {
+ const files = await dbActions.searchLibraryFiles(userId, query, { limit })
+ return { success: true, files: await signLibraryFiles(files) }
+ } catch (error) {
+ console.error('Error searching files:', error)
+ return { success: false, files: [], error: 'Failed to search files.' }
+ }
+}
+
+export async function deleteFile(
+ fileId: string
+): Promise<{ success: boolean; error?: string }> {
+ const { userId, error } = await requireLibraryFileUserId()
+ if (!userId) {
+ return { success: false, error: error ?? 'User not authenticated' }
+ }
+
+ return dbActions.deleteLibraryFile(fileId, userId)
+}
diff --git a/lib/actions/notes.ts b/lib/actions/notes.ts
index 7725baee..8d3e8089 100644
--- a/lib/actions/notes.ts
+++ b/lib/actions/notes.ts
@@ -3,6 +3,7 @@
import { getCurrentUserId } from '@/lib/auth/get-current-user'
import * as dbActions from '@/lib/db/actions'
import type { Note } from '@/lib/db/schema'
+import { stripMarkdownText } from '@/lib/utils/markdown'
const MAX_TITLE_LENGTH = 120
const DEFAULT_NOTES_PAGE_SIZE = 25
@@ -13,11 +14,7 @@ export type NotesListCursor = {
}
function stripMarkdownTitle(value: string) {
- return value
- .replace(/^#{1,6}\s+/, '')
- .replace(/[*_~`>#\[\]()]/g, '')
- .replace(/\s+/g, ' ')
- .trim()
+ return stripMarkdownText(value)
}
function deriveTitle(content: string, title?: string) {
@@ -132,6 +129,31 @@ export async function listNotes({
}
}
+export async function searchNotes({
+ query,
+ limit = DEFAULT_NOTES_PAGE_SIZE
+}: {
+ query: string
+ limit?: number
+}): Promise<{ success: boolean; notes?: Note[]; error?: string }> {
+ const { userId, error } = await requireNoteUserId()
+ if (!userId) {
+ return {
+ success: false,
+ notes: [],
+ error: error ?? 'User not authenticated'
+ }
+ }
+
+ try {
+ const notes = await dbActions.searchNotes(userId, query, { limit })
+ return { success: true, notes }
+ } catch (error) {
+ console.error('Error searching notes:', error)
+ return { success: false, notes: [], error: 'Failed to search notes.' }
+ }
+}
+
export async function getNote(
noteId: string
): Promise<{ success: boolean; note?: Note | null; error?: string }> {
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index c1ee4606..edfcf9a9 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -1,6 +1,6 @@
'use server'
-import { and, asc, desc, eq, gt, inArray, lt, or } from 'drizzle-orm'
+import { and, asc, desc, eq, gt, ilike, inArray, lt, or } from 'drizzle-orm'
import type { UIMessage } from '@/lib/types/ai'
import type { PersistableUIMessage } from '@/lib/types/message-persistence'
@@ -12,7 +12,14 @@ import {
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
-import type { Chat, Message, NewNote, Note } from './schema'
+import type {
+ Chat,
+ LibraryFile,
+ Message,
+ NewLibraryFile,
+ NewNote,
+ Note
+} from './schema'
import {
chats,
feedback,
@@ -436,6 +443,29 @@ export async function getNotes(
})
}
+export async function searchNotes(
+ userId: string,
+ query: string,
+ { limit = 20 }: { limit?: number } = {}
+): Promise<Note[]> {
+ return withRLS(userId, async tx => {
+ const trimmed = query.trim()
+ const pageLimit = Math.max(1, Math.min(limit, 50))
+
+ return tx
+ .select()
+ .from(notes)
+ .where(
+ and(
+ eq(notes.userId, userId),
+ trimmed ? ilike(notes.title, `%${trimmed}%`) : undefined
+ )
+ )
+ .orderBy(desc(notes.updatedAt), desc(notes.id))
+ .limit(pageLimit)
+ })
+}
+
export async function getNote(
noteId: string,
userId: string
@@ -488,6 +518,138 @@ export async function deleteUserNotes(
}
}
+export async function createLibraryFile(
+ file: Omit<NewLibraryFile, 'id' | 'createdAt' | 'updatedAt'>
+): Promise<LibraryFile> {
+ return withRLS(file.userId, async tx => {
+ let chatId = file.chatId ?? null
+
+ if (chatId) {
+ const [chat] = await tx
+ .select({ id: chats.id })
+ .from(chats)
+ .where(and(eq(chats.id, chatId), eq(chats.userId, file.userId)))
+ .limit(1)
+
+ chatId = chat ? chatId : null
+ }
+
+ const [createdFile] = await tx
+ .insert(libraryFiles)
+ .values({ ...file, chatId })
+ .returning()
+
+ return createdFile
+ })
+}
+
+export type FilesPageCursor = {
+ updatedAt: string
+ id: string
+}
+
+export async function getLibraryFiles(
+ userId: string,
+ {
+ limit = 25,
+ cursor
+ }: {
+ limit?: number
+ cursor?: FilesPageCursor
+ } = {}
+): Promise<{
+ files: LibraryFile[]
+ nextCursor: FilesPageCursor | null
+ hasMore: boolean
+}> {
+ return withRLS(userId, async tx => {
+ const cursorDate = cursor ? new Date(cursor.updatedAt) : null
+ const pageLimit = Math.max(1, Math.min(limit, 50))
+ const results = await tx
+ .select()
+ .from(libraryFiles)
+ .where(
+ and(
+ eq(libraryFiles.userId, userId),
+ cursor && cursorDate && !Number.isNaN(cursorDate.getTime())
+ ? or(
+ lt(libraryFiles.updatedAt, cursorDate),
+ and(
+ eq(libraryFiles.updatedAt, cursorDate),
+ lt(libraryFiles.id, cursor.id)
+ )
+ )
+ : undefined
+ )
+ )
+ .orderBy(desc(libraryFiles.updatedAt), desc(libraryFiles.id))
+ .limit(pageLimit + 1)
+
+ const pageFiles = results.slice(0, pageLimit)
+ const lastFile = pageFiles[pageFiles.length - 1]
+
+ return {
+ files: pageFiles,
+ nextCursor:
+ results.length > pageLimit && lastFile
+ ? {
+ updatedAt: lastFile.updatedAt.toISOString(),
+ id: lastFile.id
+ }
+ : null,
+ hasMore: results.length > pageLimit
+ }
+ })
+}
+
+export async function searchLibraryFiles(
+ userId: string,
+ query: string,
+ { limit = 20 }: { limit?: number } = {}
+): Promise<LibraryFile[]> {
+ return withRLS(userId, async tx => {
+ const trimmed = query.trim()
+ const pageLimit = Math.max(1, Math.min(limit, 50))
+
+ return tx
+ .select()
+ .from(libraryFiles)
+ .where(
+ and(
+ eq(libraryFiles.userId, userId),
+ trimmed ? ilike(libraryFiles.filename, `%${trimmed}%`) : undefined
+ )
+ )
+ .orderBy(desc(libraryFiles.updatedAt), desc(libraryFiles.id))
+ .limit(pageLimit)
+ })
+}
+
+export async function deleteLibraryFile(
+ fileId: string,
+ userId: string
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ return withRLS(userId, async tx => {
+ const [deletedFile] = await tx
+ .delete(libraryFiles)
+ .where(
+ and(eq(libraryFiles.id, fileId), eq(libraryFiles.userId, userId))
+ )
+ .returning({ id: libraryFiles.id })
+
+ if (!deletedFile) {
+ return { success: false, error: 'File not found' }
+ }
+
+ return { success: true }
+ })
+ } catch (error) {
+ console.error('Error deleting library file:', error)
+ return { success: false, error: 'Failed to delete file' }
+ }
+}
+
export async function deleteUserLibraryFiles(
userId: string
): Promise<{ success: boolean; error?: string }> {
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 34140135..1b073cb6 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -314,8 +314,7 @@ export const libraryFiles = pgTable(
{ onDelete: 'set null' }
),
filename: text('filename').notNull(),
- url: text('url').notNull(),
- objectKey: text('object_key'),
+ objectKey: text('object_key').notNull(),
mediaType: varchar('media_type', { length: VARCHAR_LENGTH }).notNull(),
size: integer('size'),
createdAt: timestamp('created_at').notNull().defaultNow(),
diff --git a/lib/storage/__tests__/r2-client.test.ts b/lib/storage/__tests__/r2-client.test.ts
index 396d0071..4856759d 100644
--- a/lib/storage/__tests__/r2-client.test.ts
+++ b/lib/storage/__tests__/r2-client.test.ts
@@ -203,7 +203,7 @@ describe('R2 client', () => {
],
{ allowedKeyPrefix: 'user-123/chats/chat-123/' }
)
- ).rejects.toThrow('File object key is not allowed for this chat')
+ ).rejects.toThrow('File object key is not allowed for this user')
expect(s3Mocks.getSignedUrl).not.toHaveBeenCalled()
})
diff --git a/lib/storage/r2-client.ts b/lib/storage/r2-client.ts
index ce785181..e46f0985 100644
--- a/lib/storage/r2-client.ts
+++ b/lib/storage/r2-client.ts
@@ -76,6 +76,10 @@ export function getChatFileObjectKeyPrefix(userId: string, chatId: string) {
return `${normalizeObjectKey(userId)}/chats/${normalizeObjectKey(chatId)}/`
}
+export function getUserFileObjectKeyPrefix(userId: string) {
+ return `${normalizeObjectKey(userId)}/`
+}
+
function isObjectKeyWithinPrefix(key: string, prefix: string) {
const normalizedKey = normalizeObjectKey(key)
const normalizedPrefix = normalizeObjectKey(prefix).replace(/\/+$/, '')
@@ -123,7 +127,7 @@ export async function signFilePartUrls(
options.allowedKeyPrefix &&
!isObjectKeyWithinPrefix(part.key, options.allowedKeyPrefix)
) {
- throw new Error('File object key is not allowed for this chat')
+ throw new Error('File object key is not allowed for this user')
}
try {
diff --git a/lib/streaming/helpers/__tests__/prepare-messages.test.ts b/lib/streaming/helpers/__tests__/prepare-messages.test.ts
index 2e32b09f..41c7e08f 100644
--- a/lib/streaming/helpers/__tests__/prepare-messages.test.ts
+++ b/lib/streaming/helpers/__tests__/prepare-messages.test.ts
@@ -23,9 +23,7 @@ vi.mock('@/lib/db/schema', async () => {
}
})
vi.mock('@/lib/storage/r2-client', () => ({
- getChatFileObjectKeyPrefix: vi.fn(
- (userId: string, chatId: string) => `${userId}/chats/${chatId}/`
- ),
+ getUserFileObjectKeyPrefix: vi.fn((userId: string) => `${userId}/`),
signFilePartUrls: vi.fn(async (parts: any[]) => parts)
}))
@@ -382,7 +380,7 @@ describe('prepareMessages', () => {
id: 'msg-1'
})
expect(signFilePartUrls).toHaveBeenCalledWith(newMessage.parts, {
- allowedKeyPrefix: 'user-123/chats/chat-123/'
+ allowedKeyPrefix: 'user-123/'
})
})
diff --git a/lib/streaming/helpers/convert-data-part.ts b/lib/streaming/helpers/convert-data-part.ts
index b328aea7..317c9c6c 100644
--- a/lib/streaming/helpers/convert-data-part.ts
+++ b/lib/streaming/helpers/convert-data-part.ts
@@ -36,6 +36,19 @@ export function convertDataPart(part: {
}
}
+ if (part.type === 'data-noteContext') {
+ const data = part.data as { title?: unknown; text?: unknown } | undefined
+ const text = typeof data?.text === 'string' ? data.text : ''
+ const title = typeof data?.title === 'string' ? data.title.trim() : ''
+ if (!text) return undefined
+ const nonce = randomUUID().slice(0, 8)
+ const body = title ? `Title: ${title}\n\n${text}` : text
+ return {
+ type: 'text',
+ text: `[note-context ${nonce}]\n${body}\n[/note-context ${nonce}]`
+ }
+ }
+
if (part.type === 'data-sourceUrl') {
const data = part.data as { url?: unknown } | undefined
const url = typeof data?.url === 'string' ? data.url : ''
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index d71bc0bd..5c6b5192 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -9,7 +9,7 @@ import {
} from '@/lib/actions/chat'
import { generateId } from '@/lib/db/schema'
import {
- getChatFileObjectKeyPrefix,
+ getUserFileObjectKeyPrefix,
signFilePartUrls
} from '@/lib/storage/r2-client'
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
@@ -91,7 +91,7 @@ export async function prepareMessages(
...message,
id: message.id || generateId(),
parts: await signFilePartUrls(message.parts, {
- allowedKeyPrefix: getChatFileObjectKeyPrefix(userId, chatId)
+ allowedKeyPrefix: getUserFileObjectKeyPrefix(userId)
})
}
diff --git a/lib/types/ai.ts b/lib/types/ai.ts
index b3499207..4e43b557 100644
--- a/lib/types/ai.ts
+++ b/lib/types/ai.ts
@@ -30,6 +30,7 @@ export type UIDataTypes = {
// User-authored attachments (composer): a pasted text blob and a pasted URL.
pastedContent?: { text: string }
quotedContext?: { text: string }
+ noteContext?: { title?: string; text: string }
sourceUrl?: { url: string }
}
diff --git a/lib/types/index.ts b/lib/types/index.ts
index 548b4a29..86976c93 100644
--- a/lib/types/index.ts
+++ b/lib/types/index.ts
@@ -103,3 +103,9 @@ export type UploadedFile = {
mediaType?: string
libraryFileId?: string
}
+
+export type NoteContext = {
+ id: string
+ title: string
+ content: string
+}
diff --git a/lib/utils/markdown.ts b/lib/utils/markdown.ts
new file mode 100644
index 00000000..305f76ab
--- /dev/null
+++ b/lib/utils/markdown.ts
@@ -0,0 +1,21 @@
+export function stripMarkdownText(value: string) {
+ return value
+ .replace(/```[\s\S]*?```/g, match =>
+ match.replace(/```[^\n]*\n?|\n?```/g, ' ')
+ )
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
+ .replace(/^#{1,6}\s+/gm, '')
+ .replace(/^>\s?/gm, '')
+ .replace(/^\s*[-*+]\s+/gm, '')
+ .replace(/^\s*\d+\.\s+/gm, '')
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/\*([^*]+)\*/g, '$1')
+ .replace(/__([^_]+)__/g, '$1')
+ .replace(/_([^_]+)_/g, '$1')
+ .replace(/~~([^~]+)~~/g, '$1')
+ .replace(/[*_~`>#]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
diff --git a/scripts/backfill-file-object-keys.ts b/scripts/backfill-file-object-keys.ts
index 68385530..2cc5ad5e 100644
--- a/scripts/backfill-file-object-keys.ts
+++ b/scripts/backfill-file-object-keys.ts
@@ -50,19 +50,6 @@ function keyFromUrl(url: string) {
return null
}
-async function tableExists(sql: postgres.Sql, tableName: string) {
- const [row] = await sql<{ exists: boolean }[]>`
- SELECT EXISTS (
- SELECT 1
- FROM information_schema.tables
- WHERE table_schema = 'public'
- AND table_name = ${tableName}
- ) AS "exists"
- `
-
- return Boolean(row?.exists)
-}
-
async function backfillParts(sql: postgres.Sql) {
const rows = await sql<BackfillTarget[]>`
SELECT id, file_url AS url
@@ -96,42 +83,6 @@ async function backfillParts(sql: postgres.Sql) {
return { total: rows.length, converted, skipped }
}
-async function backfillFiles(sql: postgres.Sql) {
- if (!(await tableExists(sql, 'files'))) {
- return { total: 0, converted: 0, skipped: 0, missing: true }
- }
-
- const rows = await sql<BackfillTarget[]>`
- SELECT id, url
- FROM files
- WHERE object_key IS NULL
- AND url IS NOT NULL
- `
-
- let converted = 0
- let skipped = 0
-
- for (const row of rows) {
- const key = keyFromUrl(row.url)
- if (!key) {
- skipped++
- continue
- }
-
- converted++
- if (apply) {
- await sql`
- UPDATE files
- SET object_key = ${key}
- WHERE id = ${row.id}
- AND object_key IS NULL
- `
- }
- }
-
- return { total: rows.length, converted, skipped, missing: false }
-}
-
async function main() {
const sql = postgres(process.env.DATABASE_URL!, {
ssl:
@@ -142,18 +93,14 @@ async function main() {
})
try {
- const [partsResult, filesResult] = await Promise.all([
- backfillParts(sql),
- backfillFiles(sql)
- ])
+ const partsResult = await backfillParts(sql)
console.log(
JSON.stringify(
{
mode: apply ? 'apply' : 'dry-run',
baseUrls,
- parts: partsResult,
- files: filesResult
+ parts: partsResult
},
null,
2
@@ -164,7 +111,7 @@ async function main() {
console.log('Re-run with --apply to update rows.')
}
- const skipped = partsResult.skipped + filesResult.skipped
+ const skipped = partsResult.skipped
if (apply && skipped > 0 && !allowSkipped) {
throw new Error(
`Backfill left ${skipped} URL(s) without object keys. Add the missing --base-url value and rerun, or pass --allow-skipped to accept unavailable legacy attachments.`