Skip to content

An AI-powered search engine with a generative UI

Add paginated library notes loading (#895)

Yoshiki Miuradc897b5f1983
diff --git a/components/library/library-context.tsx b/components/library/library-context.tsx
index 15218eca..dddcef36 100644
--- a/components/library/library-context.tsx
+++ b/components/library/library-context.tsx
@@ -12,8 +12,15 @@ import type { Note } from '@/lib/db/schema'
import { useSidebar } from '../ui/sidebar'
+type NotesListCursor = {
+ updatedAt: string
+ id: string
+}
+
type NotesCache = {
notes: Note[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
updatedAt: number
}
@@ -24,7 +31,16 @@ type LibraryContextValue = {
openLibrary: () => void
closeLibrary: () => void
toggleLibrary: () => void
- replaceNotesCache: (notes: Note[]) => void
+ replaceNotesCache: (page: {
+ notes: Note[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => void
+ appendNotesCache: (page: {
+ notes: Note[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => void
upsertCachedNote: (note: Note) => void
removeCachedNote: (noteId: string) => void
refreshLibrary: () => void
@@ -51,15 +67,51 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
return !open
})
}, [setSidebarOpen])
- const replaceNotesCache = useCallback((notes: Note[]) => {
- setNotesCache({ notes, updatedAt: Date.now() })
- }, [])
+ const replaceNotesCache = useCallback(
+ (page: {
+ notes: Note[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => {
+ setNotesCache({ ...page, updatedAt: Date.now() })
+ },
+ []
+ )
+ const appendNotesCache = useCallback(
+ (page: {
+ notes: Note[]
+ nextCursor: NotesListCursor | null
+ hasMore: boolean
+ }) => {
+ setNotesCache(cache => {
+ if (!cache) {
+ return { ...page, updatedAt: Date.now() }
+ }
+
+ const existingIds = new Set(cache.notes.map(note => note.id))
+ const mergedNotes = [
+ ...cache.notes,
+ ...page.notes.filter(note => !existingIds.has(note.id))
+ ]
+
+ return {
+ notes: mergedNotes,
+ nextCursor: page.nextCursor,
+ hasMore: page.hasMore,
+ updatedAt: Date.now()
+ }
+ })
+ },
+ []
+ )
const upsertCachedNote = useCallback((note: Note) => {
setNotesCache(cache => {
if (!cache) return cache
return {
notes: [note, ...cache.notes.filter(item => item.id !== note.id)],
+ nextCursor: cache.nextCursor,
+ hasMore: cache.hasMore,
updatedAt: Date.now()
}
})
@@ -70,6 +122,8 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
return {
notes: cache.notes.filter(note => note.id !== noteId),
+ nextCursor: cache.nextCursor,
+ hasMore: cache.hasMore,
updatedAt: Date.now()
}
})
@@ -87,12 +141,14 @@ export function LibraryProvider({ children }: { children: React.ReactNode }) {
closeLibrary,
toggleLibrary,
replaceNotesCache,
+ appendNotesCache,
upsertCachedNote,
removeCachedNote,
refreshLibrary
}),
[
closeLibrary,
+ appendNotesCache,
isOpen,
notesCache,
openLibrary,
diff --git a/components/library/library-panel.tsx b/components/library/library-panel.tsx
index 756091c4..0e0f81eb 100644
--- a/components/library/library-panel.tsx
+++ b/components/library/library-panel.tsx
@@ -1,6 +1,13 @@
'use client'
-import { useEffect, useMemo, useRef, useState, useTransition } from 'react'
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useTransition
+} from 'react'
import {
IconArrowLeft as ArrowLeft,
@@ -44,6 +51,7 @@ import { MarkdownMessage } from '@/components/message'
import { useLibrary } from './library-context'
const LIBRARY_CACHE_TTL_MS = 60_000
+const LIBRARY_PAGE_SIZE = 25
function formatNoteDate(value: Date | string) {
const date = value instanceof Date ? value : new Date(value)
@@ -144,14 +152,18 @@ export function LibraryPanel() {
notesCache,
refreshKey,
replaceNotesCache,
+ appendNotesCache,
removeCachedNote
} = useLibrary()
const [selectedNote, setSelectedNote] = useState<Note | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Note | null>(null)
const [hasLoadAttempted, setHasLoadAttempted] = useState(false)
+ const [isLoadingMore, setIsLoadingMore] = useState(false)
const [isDeleting, startDeleteTransition] = useTransition()
const lastFetchedRefreshKeyRef = useRef<number | null>(null)
const previousIsOpenRef = useRef(false)
+ const listScrollRef = useRef<HTMLDivElement | null>(null)
+ const loadMoreRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
const justOpened = isOpen && !previousIsOpenRef.current
@@ -181,7 +193,7 @@ export function LibraryPanel() {
const loadReason = !hasCache ? 'cold' : isRefreshStale ? 'refresh' : 'ttl'
let cancelled = false
- listNotes().then(result => {
+ listNotes({ limit: LIBRARY_PAGE_SIZE }).then(result => {
if (cancelled) return
setHasLoadAttempted(true)
@@ -201,14 +213,19 @@ export function LibraryPanel() {
source: 'network',
reason: loadReason,
noteCount: nextNotes.length,
+ hasMore: Boolean(result.hasMore),
isEmpty: nextNotes.length === 0
})
- replaceNotesCache(nextNotes)
+ replaceNotesCache({
+ notes: nextNotes,
+ nextCursor: result.nextCursor ?? null,
+ hasMore: Boolean(result.hasMore)
+ })
lastFetchedRefreshKeyRef.current = refreshKey
setSelectedNote(current => {
if (!current) return current
- return nextNotes.find(note => note.id === current.id) ?? null
+ return nextNotes.find(note => note.id === current.id) ?? current
})
})
@@ -217,6 +234,67 @@ export function LibraryPanel() {
}
}, [isOpen, notesCache, refreshKey, replaceNotesCache])
+ const handleLoadMore = useCallback(async () => {
+ if (!notesCache?.hasMore || !notesCache.nextCursor || isLoadingMore) return
+
+ setIsLoadingMore(true)
+ try {
+ const result = await listNotes({
+ limit: LIBRARY_PAGE_SIZE,
+ cursor: notesCache.nextCursor
+ })
+
+ 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
+ })
+ } finally {
+ setIsLoadingMore(false)
+ }
+ }, [appendNotesCache, isLoadingMore, notesCache])
+
+ useEffect(() => {
+ if (!isOpen || selectedNote || !notesCache?.hasMore || isLoadingMore) return
+
+ const sentinel = loadMoreRef.current
+ const scrollRoot = listScrollRef.current
+ if (!sentinel || !scrollRoot) return
+
+ const observer = new IntersectionObserver(
+ entries => {
+ if (entries[0]?.isIntersecting) {
+ void handleLoadMore()
+ }
+ },
+ { root: scrollRoot, rootMargin: '160px 0px' }
+ )
+
+ observer.observe(sentinel)
+
+ return () => {
+ observer.disconnect()
+ }
+ }, [handleLoadMore, isLoadingMore, isOpen, notesCache?.hasMore, selectedNote])
+
const visibleNotes = notesCache?.notes ?? []
const isLoading = !notesCache && !hasLoadAttempted
const selectedTitle = useMemo(
@@ -349,6 +427,7 @@ export function LibraryPanel() {
</div>
) : (
<div
+ ref={listScrollRef}
data-vaul-no-drag
className="min-h-0 flex-1 overflow-y-auto p-2"
>
@@ -396,6 +475,14 @@ export function LibraryPanel() {
</div>
)
})}
+ {notesCache?.hasMore && (
+ <div
+ ref={loadMoreRef}
+ className="flex h-10 items-center justify-center text-muted-foreground"
+ >
+ {isLoadingMore && <Spinner />}
+ </div>
+ )}
</div>
)}
</div>
diff --git a/lib/actions/__tests__/notes.test.ts b/lib/actions/__tests__/notes.test.ts
index 21cb9029..667ee2bc 100644
--- a/lib/actions/__tests__/notes.test.ts
+++ b/lib/actions/__tests__/notes.test.ts
@@ -27,7 +27,11 @@ describe('Note Actions', () => {
process.env.ENABLE_AUTH = 'true'
vi.mocked(getCurrentUserId).mockResolvedValue('user-1')
vi.mocked(dbActions.createNote).mockResolvedValue(note)
- vi.mocked(dbActions.getNotes).mockResolvedValue([note])
+ vi.mocked(dbActions.getNotes).mockResolvedValue({
+ notes: [note],
+ nextCursor: null,
+ hasMore: false
+ })
vi.mocked(dbActions.getNote).mockResolvedValue(note)
vi.mocked(dbActions.deleteNote).mockResolvedValue({ success: true })
})
@@ -75,8 +79,30 @@ describe('Note Actions', () => {
it('lists current user notes', async () => {
const result = await listNotes()
- expect(result).toEqual({ success: true, notes: [note] })
- expect(dbActions.getNotes).toHaveBeenCalledWith('user-1')
+ expect(result).toEqual({
+ success: true,
+ notes: [note],
+ nextCursor: null,
+ hasMore: false
+ })
+ expect(dbActions.getNotes).toHaveBeenCalledWith('user-1', {
+ limit: 25,
+ cursor: undefined
+ })
+ })
+
+ it('lists current user notes from a cursor', async () => {
+ const cursor = {
+ updatedAt: '2026-06-17T00:00:00.000Z',
+ id: 'note-1'
+ }
+
+ await listNotes({ limit: 10, cursor })
+
+ expect(dbActions.getNotes).toHaveBeenCalledWith('user-1', {
+ limit: 10,
+ cursor
+ })
})
it('loads a current user note', async () => {
diff --git a/lib/actions/notes.ts b/lib/actions/notes.ts
index 101e1d7d..7725baee 100644
--- a/lib/actions/notes.ts
+++ b/lib/actions/notes.ts
@@ -5,6 +5,12 @@ import * as dbActions from '@/lib/db/actions'
import type { Note } from '@/lib/db/schema'
const MAX_TITLE_LENGTH = 120
+const DEFAULT_NOTES_PAGE_SIZE = 25
+
+export type NotesListCursor = {
+ updatedAt: string
+ id: string
+}
function stripMarkdownTitle(value: string) {
return value
@@ -81,9 +87,17 @@ export async function saveNote({
}
}
-export async function listNotes(): Promise<{
+export async function listNotes({
+ limit = DEFAULT_NOTES_PAGE_SIZE,
+ cursor
+}: {
+ limit?: number
+ cursor?: NotesListCursor | null
+} = {}): Promise<{
success: boolean
notes?: Note[]
+ nextCursor?: NotesListCursor | null
+ hasMore?: boolean
error?: string
}> {
const { userId, error } = await requireNoteUserId()
@@ -96,11 +110,25 @@ export async function listNotes(): Promise<{
}
try {
- const notes = await dbActions.getNotes(userId)
- return { success: true, notes }
+ const page = await dbActions.getNotes(userId, {
+ limit,
+ cursor: cursor ?? undefined
+ })
+ return {
+ success: true,
+ notes: page.notes,
+ nextCursor: page.nextCursor,
+ hasMore: page.hasMore
+ }
} catch (error) {
console.error('Error listing notes:', error)
- return { success: false, notes: [], error: 'Failed to load notes.' }
+ return {
+ success: false,
+ notes: [],
+ nextCursor: null,
+ hasMore: false,
+ error: 'Failed to load notes.'
+ }
}
}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index ab21c069..5be5d807 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -1,6 +1,6 @@
'use server'
-import { and, asc, desc, eq, gt, inArray } from 'drizzle-orm'
+import { and, asc, desc, eq, gt, inArray, lt, or } from 'drizzle-orm'
import type { UIMessage } from '@/lib/types/ai'
import type { PersistableUIMessage } from '@/lib/types/message-persistence'
@@ -372,13 +372,59 @@ export async function createNote(
})
}
-export async function getNotes(userId: string): Promise<Note[]> {
+export type NotesPageCursor = {
+ updatedAt: string
+ id: string
+}
+
+export async function getNotes(
+ userId: string,
+ {
+ limit = 25,
+ cursor
+ }: {
+ limit?: number
+ cursor?: NotesPageCursor
+ } = {}
+): Promise<{
+ notes: Note[]
+ nextCursor: NotesPageCursor | null
+ hasMore: boolean
+}> {
return withRLS(userId, async tx => {
- return tx
+ const cursorDate = cursor ? new Date(cursor.updatedAt) : null
+ const pageLimit = Math.max(1, Math.min(limit, 50))
+ const results = await tx
.select()
.from(notes)
- .where(eq(notes.userId, userId))
- .orderBy(desc(notes.updatedAt))
+ .where(
+ and(
+ eq(notes.userId, userId),
+ cursor && cursorDate && !Number.isNaN(cursorDate.getTime())
+ ? or(
+ lt(notes.updatedAt, cursorDate),
+ and(eq(notes.updatedAt, cursorDate), lt(notes.id, cursor.id))
+ )
+ : undefined
+ )
+ )
+ .orderBy(desc(notes.updatedAt), desc(notes.id))
+ .limit(pageLimit + 1)
+
+ const pageNotes = results.slice(0, pageLimit)
+ const lastNote = pageNotes[pageNotes.length - 1]
+
+ return {
+ notes: pageNotes,
+ nextCursor:
+ results.length > pageLimit && lastNote
+ ? {
+ updatedAt: lastNote.updatedAt.toISOString(),
+ id: lastNote.id
+ }
+ : null,
+ hasMore: results.length > pageLimit
+ }
})
}