Skip to content

An AI-powered search engine with a generative UI

Add knowledge library notes (#893)

Yoshiki Miura7392d60f27c9
diff --git a/app/layout.tsx b/app/layout.tsx
index d244ef0b..9da1ac88 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -16,6 +16,7 @@ import AppSidebar from '@/components/app-sidebar'
import ArtifactRoot from '@/components/artifact/artifact-root'
import Header from '@/components/header'
import { KeyboardShortcutHandler } from '@/components/keyboard-shortcut-handler'
+import { LibraryProvider } from '@/components/library/library-context'
import { PostHogProvider } from '@/components/posthog-provider'
import { ThemeProvider } from '@/components/theme-provider'
@@ -87,14 +88,16 @@ export default async function RootLayout({
<PostHogProvider userId={user?.id ?? null}>
<UserProvider hasUser={!!userId}>
<SidebarProvider defaultOpen={false}>
- {userId && <AppSidebar />}
- <KeyboardShortcutHandler />
- <div className="flex flex-col flex-1 min-w-0">
- <Header user={user} />
- <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
- <ArtifactRoot>{children}</ArtifactRoot>
- </main>
- </div>
+ <LibraryProvider>
+ {userId && <AppSidebar />}
+ <KeyboardShortcutHandler />
+ <div className="flex flex-col flex-1 min-w-0">
+ <Header user={user} />
+ <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
+ <ArtifactRoot>{children}</ArtifactRoot>
+ </main>
+ </div>
+ </LibraryProvider>
</SidebarProvider>
</UserProvider>
</PostHogProvider>
diff --git a/app/page.tsx b/app/page.tsx
index 7ab870b3..0c093f91 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -6,12 +6,14 @@ import { Chat } from '@/components/chat'
export default async function Page() {
const userId = await getCurrentUserId()
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
const modelSelectorData = await getModelSelectorData()
return (
<Chat
isGuest={!userId}
isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
modelSelectorData={modelSelectorData}
/>
)
diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsx
index 749c1900..1219762e 100644
--- a/app/search/[id]/page.tsx
+++ b/app/search/[id]/page.tsx
@@ -45,6 +45,7 @@ export default async function SearchPage(props: {
const messages: UIMessage[] = chat.messages
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
const modelSelectorData = await getModelSelectorData()
return (
@@ -53,6 +54,7 @@ export default async function SearchPage(props: {
savedMessages={messages}
isGuest={!userId}
isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
modelSelectorData={modelSelectorData}
/>
)
diff --git a/app/search/page.tsx b/app/search/page.tsx
index db1ce83d..077daa05 100644
--- a/app/search/page.tsx
+++ b/app/search/page.tsx
@@ -19,6 +19,7 @@ export default async function SearchPage(props: {
const id = generateUUID()
const userId = await getCurrentUserId()
const isCloudDeployment = process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true'
+ const libraryAvailable = process.env.ENABLE_AUTH !== 'false'
const modelSelectorData = await getModelSelectorData()
return (
@@ -27,6 +28,7 @@ export default async function SearchPage(props: {
query={q}
isGuest={!userId}
isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
modelSelectorData={modelSelectorData}
/>
)
diff --git a/components/__tests__/chat-panel.test.tsx b/components/__tests__/chat-panel.test.tsx
index c812523e..9edbe5a5 100644
--- a/components/__tests__/chat-panel.test.tsx
+++ b/components/__tests__/chat-panel.test.tsx
@@ -69,6 +69,8 @@ describe('ChatPanel', () => {
scrollContainerRef={React.createRef<HTMLDivElement>()}
uploadedFiles={[]}
setUploadedFiles={vi.fn()}
+ quotedContexts={[]}
+ setQuotedContexts={vi.fn()}
isGuest
isCloudDeployment
onAdaptiveModeAuthRequired={onAdaptiveModeAuthRequired}
diff --git a/components/answer-section.tsx b/components/answer-section.tsx
index 0dc13b24..965cd080 100644
--- a/components/answer-section.tsx
+++ b/components/answer-section.tsx
@@ -1,8 +1,18 @@
'use client'
+import { useEffect, useRef, useState } from 'react'
+import Link from 'next/link'
+
import { UseChatHelpers } from '@ai-sdk/react'
+import {
+ IconBookmark as Bookmark,
+ IconMessageCirclePlus as MessageCirclePlus
+} from '@tabler/icons-react'
import { ChatRequestOptions } from 'ai'
+import { toast } from 'sonner'
+import { saveNote } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
import type { SearchResultItem } from '@/lib/types'
import type {
UIDataTypes,
@@ -11,6 +21,16 @@ import type {
UITools
} from '@/lib/types/ai'
+import { useLibrary } from './library/library-context'
+import { Button } from './ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from './ui/dialog'
import { CollapsibleMessage } from './collapsible-message'
import { MarkdownMessage } from './message'
import { MessageActions } from './message-actions'
@@ -30,6 +50,9 @@ export type AnswerSectionProps = {
) => Promise<void | string | null | undefined>
citationMaps?: Record<string, Record<number, SearchResultItem>>
isGuest?: boolean
+ isCloudDeployment?: boolean
+ libraryAvailable?: boolean
+ onQuoteContext?: (text: string) => void
}
export function AnswerSection({
@@ -43,10 +66,67 @@ export function AnswerSection({
status,
reload,
citationMaps,
- isGuest = false
+ isGuest = false,
+ isCloudDeployment = false,
+ libraryAvailable = true,
+ onQuoteContext
}: AnswerSectionProps) {
+ const contentRef = useRef<HTMLDivElement>(null)
+ const [selection, setSelection] = useState<{
+ text: string
+ top: number
+ left: number
+ } | null>(null)
+ const [isSavingSelection, setIsSavingSelection] = useState(false)
+ const [authPromptOpen, setAuthPromptOpen] = useState(false)
+ const lastTrackedSelectionKeyRef = useRef<string | null>(null)
+ const { openLibrary, upsertCachedNote } = useLibrary()
const enableShare =
process.env.NEXT_PUBLIC_SUPABASE_URL !== undefined && !isGuest
+ const showSelectionSaveButton =
+ libraryAvailable && (!isGuest || isCloudDeployment)
+ const showSelectionDeepDiveButton = Boolean(onQuoteContext)
+
+ useEffect(() => {
+ if (!selection) return
+
+ const clearSelection = () => {
+ setSelection(null)
+ lastTrackedSelectionKeyRef.current = null
+ }
+
+ const handleSelectionChange = () => {
+ const text = window.getSelection()?.toString().trim()
+ if (!text) {
+ clearSelection()
+ }
+ }
+
+ const handleMouseDown = (event: MouseEvent) => {
+ const target = event.target
+ if (!(target instanceof Node)) return
+
+ if (contentRef.current?.contains(target)) return
+ if (
+ target instanceof Element &&
+ target.closest('[data-selection-actions]')
+ ) {
+ return
+ }
+
+ clearSelection()
+ }
+
+ document.addEventListener('selectionchange', handleSelectionChange)
+ document.addEventListener('mousedown', handleMouseDown)
+ window.addEventListener('scroll', clearSelection, true)
+
+ return () => {
+ document.removeEventListener('selectionchange', handleSelectionChange)
+ document.removeEventListener('mousedown', handleMouseDown)
+ window.removeEventListener('scroll', clearSelection, true)
+ }
+ }, [selection])
const handleReload = () => {
if (reload) {
@@ -55,6 +135,128 @@ export function AnswerSection({
return Promise.resolve(undefined)
}
+ const updateSelection = () => {
+ const currentSelection = window.getSelection()
+ const text = currentSelection?.toString().trim()
+ if (!text || !currentSelection || currentSelection.rangeCount === 0) {
+ setSelection(null)
+ lastTrackedSelectionKeyRef.current = null
+ return
+ }
+
+ const range = currentSelection.getRangeAt(0)
+ const container = contentRef.current
+ if (
+ !container ||
+ !container.contains(range.commonAncestorContainer) ||
+ text.length < 2
+ ) {
+ setSelection(null)
+ lastTrackedSelectionKeyRef.current = null
+ return
+ }
+
+ const rect = range.getBoundingClientRect()
+ const trackingKey = `${messageId}:${text.length}:${Math.round(rect.top)}:${Math.round(rect.left)}`
+ if (lastTrackedSelectionKeyRef.current !== trackingKey) {
+ lastTrackedSelectionKeyRef.current = trackingKey
+ captureClient('selection_note_actions_shown', {
+ chatId,
+ chars: text.length,
+ isGuest,
+ isCloudDeployment
+ })
+ }
+
+ setSelection({
+ text,
+ top: Math.max(8, rect.top - 42),
+ left: Math.max(8, Math.min(window.innerWidth - 220, rect.left))
+ })
+ }
+
+ async function handleSaveSelection() {
+ if (!selection || isSavingSelection) return
+
+ captureClient('note_save_clicked', {
+ source: 'selection',
+ chatId,
+ chars: selection.text.length,
+ isGuest,
+ isCloudDeployment
+ })
+
+ if (isGuest) {
+ setAuthPromptOpen(true)
+ captureClient('library_auth_prompt_opened', {
+ source: 'selection_save',
+ chatId
+ })
+ return
+ }
+
+ setIsSavingSelection(true)
+ try {
+ const result = await saveNote({
+ content: selection.text,
+ chatId,
+ sourceMessageId: messageId
+ })
+
+ if (!result.success) {
+ captureClient('note_save_failed', {
+ source: 'selection',
+ chatId,
+ reason: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to save note')
+ return
+ }
+
+ if (result.note) {
+ upsertCachedNote(result.note)
+ }
+ captureClient('note_saved', {
+ source: 'selection',
+ chatId,
+ chars: selection.text.length
+ })
+ toast.success('Saved to library', {
+ action: {
+ label: 'Open',
+ onClick: () => {
+ openLibrary()
+ captureClient('library_opened', { source: 'toast' })
+ }
+ }
+ })
+ setSelection(null)
+ window.getSelection()?.removeAllRanges()
+ } catch (error) {
+ console.error('Error saving selected note:', error)
+ captureClient('note_save_failed', {
+ source: 'selection',
+ chatId,
+ reason: 'exception'
+ })
+ toast.error('Failed to save note')
+ } finally {
+ setIsSavingSelection(false)
+ }
+ }
+
+ function handleQuoteSelection() {
+ if (!selection) return
+
+ onQuoteContext?.(selection.text)
+ captureClient('selection_followup', {
+ chatId,
+ chars: selection.text.length
+ })
+ setSelection(null)
+ window.getSelection()?.removeAllRanges()
+ }
+
return (
<CollapsibleMessage
role="assistant"
@@ -66,7 +268,48 @@ export function AnswerSection({
>
{content && (
<div className="flex flex-col gap-1">
- <MarkdownMessage message={content} citationMaps={citationMaps} />
+ <div
+ ref={contentRef}
+ onMouseUp={updateSelection}
+ onKeyUp={updateSelection}
+ >
+ <MarkdownMessage message={content} citationMaps={citationMaps} />
+ </div>
+ {selection &&
+ (showSelectionSaveButton || showSelectionDeepDiveButton) && (
+ <div
+ data-selection-actions
+ className="fixed z-40 flex items-center gap-1 rounded-md border bg-popover p-1 text-popover-foreground shadow-md"
+ style={{ top: selection.top, left: selection.left }}
+ onMouseDown={event => event.preventDefault()}
+ >
+ {showSelectionSaveButton && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 px-2 text-xs"
+ disabled={isSavingSelection}
+ onClick={handleSaveSelection}
+ >
+ <Bookmark className="size-3.5" />
+ Save
+ </Button>
+ )}
+ {showSelectionDeepDiveButton && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 px-2 text-xs"
+ onClick={handleQuoteSelection}
+ >
+ <MessageCirclePlus className="size-3.5" />
+ Deep dive
+ </Button>
+ )}
+ </div>
+ )}
<MessageActions
message={content} // Provide original message; copy path remaps citations
messageId={messageId}
@@ -74,6 +317,9 @@ export function AnswerSection({
feedbackScore={metadata?.feedbackScore}
chatId={chatId}
enableShare={enableShare}
+ isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
reload={handleReload}
status={status}
visible={showActions}
@@ -81,6 +327,52 @@ export function AnswerSection({
/>
</div>
)}
+ <Dialog open={authPromptOpen} onOpenChange={setAuthPromptOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-full bg-muted">
+ <Bookmark className="size-6 text-muted-foreground" />
+ </div>
+ <DialogTitle className="text-center text-xl font-semibold">
+ Save notes to your library
+ </DialogTitle>
+ <DialogDescription className="text-center text-muted-foreground">
+ Sign in or create an account to save selected text to your
+ Library.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="flex-col gap-2">
+ <Button asChild className="w-full">
+ <Link
+ href="/auth/sign-up"
+ onClick={() =>
+ captureClient('library_auth_prompt_cta_clicked', {
+ source: 'selection_save',
+ target: 'sign_up',
+ chatId
+ })
+ }
+ >
+ Sign Up
+ </Link>
+ </Button>
+ <Button asChild variant="outline" className="w-full">
+ <Link
+ href="/auth/login"
+ onClick={() =>
+ captureClient('library_auth_prompt_cta_clicked', {
+ source: 'selection_save',
+ target: 'sign_in',
+ chatId
+ })
+ }
+ >
+ Sign In
+ </Link>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</CollapsibleMessage>
)
}
diff --git a/components/artifact/artifact-context.tsx b/components/artifact/artifact-context.tsx
index a2158708..3e7b54a9 100644
--- a/components/artifact/artifact-context.tsx
+++ b/components/artifact/artifact-context.tsx
@@ -11,6 +11,7 @@ import {
import type { Part } from '@/lib/types/ai'
+import { useLibrary } from '../library/library-context'
import { useSidebar } from '../ui/sidebar'
// Animation duration should match the inspector panel exit transition.
@@ -60,6 +61,7 @@ const ArtifactContext = createContext<ArtifactContextValue | undefined>(
export function ArtifactProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(artifactReducer, initialState)
const { setOpen, open: sidebarOpen } = useSidebar()
+ const { isOpen: libraryOpen, closeLibrary } = useLibrary()
const close = useCallback(() => {
dispatch({ type: 'CLOSE' })
@@ -74,13 +76,25 @@ export function ArtifactProvider({ children }: { children: ReactNode }) {
if (sidebarOpen && state.isOpen) {
close()
}
- }, [sidebarOpen, state.isOpen, close])
+ // LibraryProvider closes the sidebar before opening Library; this handles
+ // the inverse path when the sidebar is opened while Library is visible.
+ if (sidebarOpen && libraryOpen) {
+ closeLibrary()
+ }
+ }, [sidebarOpen, state.isOpen, libraryOpen, close, closeLibrary])
const open = (part: Part) => {
+ closeLibrary()
dispatch({ type: 'OPEN', payload: part })
setOpen(false)
}
+ useEffect(() => {
+ if (libraryOpen && state.isOpen) {
+ close()
+ }
+ }, [libraryOpen, state.isOpen, close])
+
return (
<ArtifactContext.Provider value={{ state, open, close }}>
{children}
diff --git a/components/artifact/chat-artifact-container.tsx b/components/artifact/chat-artifact-container.tsx
index dbd068ed..fc83df9c 100644
--- a/components/artifact/chat-artifact-container.tsx
+++ b/components/artifact/chat-artifact-container.tsx
@@ -9,6 +9,8 @@ import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar'
import { InspectorDrawer } from '@/components/inspector/inspector-drawer'
import { InspectorPanel } from '@/components/inspector/inspector-panel'
+import { useLibrary } from '@/components/library/library-context'
+import { LibraryPanel } from '@/components/library/library-panel'
import { useArtifact } from './artifact-context'
@@ -49,6 +51,9 @@ export function ChatArtifactContainer({
const [isResizing, setIsResizing] = useState(false)
const hasUser = useHasUser()
const { open, isMobile: isMobileSidebar } = useSidebar()
+ const { isOpen: libraryOpen } = useLibrary()
+ const artifactOpen = state.isOpen && state.part
+ const panelOpen = Boolean(artifactOpen || libraryOpen)
const setContainerRef = useCallback((node: HTMLDivElement | null) => {
setContainerElement(node)
@@ -147,7 +152,7 @@ export function ChatArtifactContainer({
<div className="flex-1 min-w-0 flex flex-col">{children}</div>
{/* Resize Handle */}
- {state.isOpen && state.part && (
+ {panelOpen && (
<div
className={cn(
'w-1 mx-0.5 my-6 hover:bg-border transition-colors duration-200 cursor-col-resize select-none relative',
@@ -163,16 +168,20 @@ export function ChatArtifactContainer({
<div
className={cn(
'bg-background overflow-hidden',
- state.isOpen && state.part ? 'opacity-100' : 'w-0 opacity-0',
+ panelOpen ? 'opacity-100' : 'w-0 opacity-0',
!isResizing &&
'transition-[opacity,width] duration-[260ms] ease-[var(--motion-ease-in-out)]'
)}
style={{
- width: state.isOpen && state.part ? `${width}px` : '0px'
+ width: panelOpen ? `${width}px` : '0px'
}}
>
<div className="h-full" style={{ width: `${width}px` }}>
- {state.isOpen && state.part && <InspectorPanel />}
+ {artifactOpen ? (
+ <InspectorPanel />
+ ) : libraryOpen ? (
+ <LibraryPanel />
+ ) : null}
</div>
</div>
</div>
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index b93a2537..95777873 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -26,12 +26,15 @@ interface ChatMessagesProps {
status: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
chatId?: string
isGuest?: boolean
+ isCloudDeployment?: boolean
+ libraryAvailable?: boolean
addToolResult?: (params: { toolCallId: string; result: any }) => void
/** Ref for the scroll container */
scrollContainerRef: React.RefObject<HTMLDivElement>
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
reload?: (messageId: string) => Promise<void | string | null | undefined>
error?: Error | string | null | undefined
+ onQuoteContext?: (text: string) => void
}
const DESKTOP_LATEST_SECTION_OFFSET = 196
@@ -43,11 +46,14 @@ export function ChatMessages({
status,
chatId,
isGuest = false,
+ isCloudDeployment = false,
+ libraryAvailable = true,
addToolResult,
scrollContainerRef,
onUpdateMessage,
reload,
- error
+ error,
+ onQuoteContext
}: ChatMessagesProps) {
// Track user-modified states (when user explicitly opens/closes)
const [userModifiedStates, setUserModifiedStates] = useState<
@@ -222,11 +228,14 @@ export function ChatMessages({
onOpenChange={handleOpenChange}
chatId={chatId}
isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
status={status}
addToolResult={addToolResult}
onUpdateMessage={onUpdateMessage}
reload={reload}
citationMaps={allCitationMaps}
+ onQuoteContext={onQuoteContext}
/>
</div>
@@ -251,12 +260,15 @@ export function ChatMessages({
onOpenChange={handleOpenChange}
chatId={chatId}
isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
status={status}
addToolResult={addToolResult}
onUpdateMessage={onUpdateMessage}
reload={reload}
isLatestMessage={isLatestMessage}
citationMaps={allCitationMaps}
+ onQuoteContext={onQuoteContext}
/>
</div>
)
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 8e2b47d8..f113b593 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -87,6 +87,8 @@ interface ChatPanelProps {
scrollContainerRef: React.RefObject<HTMLDivElement>
uploadedFiles: UploadedFile[]
setUploadedFiles: React.Dispatch<React.SetStateAction<UploadedFile[]>>
+ quotedContexts: string[]
+ setQuotedContexts: React.Dispatch<React.SetStateAction<string[]>>
/** Callback to reset chatId when starting a new chat */
onNewChat?: () => void
/** Whether the current session is guest */
@@ -113,6 +115,8 @@ export function ChatPanel({
showScrollToBottomButton,
uploadedFiles,
setUploadedFiles,
+ quotedContexts,
+ setQuotedContexts,
scrollContainerRef,
onNewChat,
isGuest = false,
@@ -134,6 +138,12 @@ export function ChatPanel({
const [urlCards, setUrlCards] = useState<string[]>([])
const { close: closeArtifact } = useArtifact()
const isLoading = status === 'submitted' || status === 'streaming'
+ const hasPendingInput =
+ input.trim().length > 0 ||
+ contentCards.length > 0 ||
+ quotedContexts.length > 0 ||
+ urlCards.length > 0 ||
+ uploadedFiles.some(file => file.status === 'uploaded')
const hasAvailableModels =
isCloudDeployment || modelSelectorData?.hasAvailableModels !== false
const searchMode = useSyncExternalStore(
@@ -273,7 +283,11 @@ export function ChatPanel({
// Pasted attachments (content cards / URL chips) are sent as
// structured data parts alongside the instruction text part — no
// in-band markers. The server maps them to the model prompt.
- if (contentCards.length > 0 || urlCards.length > 0) {
+ if (
+ contentCards.length > 0 ||
+ quotedContexts.length > 0 ||
+ urlCards.length > 0
+ ) {
e.preventDefault()
if (adaptiveModeSubmitBlocked) {
onAdaptiveModeAuthRequired?.()
@@ -289,6 +303,10 @@ export function ChatPanel({
type: 'data-pastedContent',
data: { text }
})),
+ ...quotedContexts.map(text => ({
+ type: 'data-quotedContext',
+ data: { text }
+ })),
...urlCards.map(url => ({
type: 'data-sourceUrl',
data: { url }
@@ -313,6 +331,7 @@ export function ChatPanel({
})
}
setContentCards([])
+ setQuotedContexts([])
setUrlCards([])
setUploadedFiles([])
handleInputChange({
@@ -434,6 +453,38 @@ export function ChatPanel({
))}
</div>
)}
+ {quotedContexts.length > 0 && (
+ <div className="flex flex-col gap-1.5 px-3 pt-3">
+ {quotedContexts.map((card, i) => (
+ <div
+ key={i}
+ 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 text-xs font-medium text-muted-foreground">
+ <FileText className="size-3.5 shrink-0" />
+ Quoted context · {card.length.toLocaleString()} chars
+ </span>
+ <button
+ type="button"
+ aria-label="Remove quoted context"
+ className="shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
+ onClick={() => {
+ setQuotedContexts(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">
+ {card}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
{urlCards.length > 0 && (
<div className="flex flex-wrap gap-1.5 px-3 pt-3">
{urlCards.map((url, i) => {
@@ -522,7 +573,7 @@ export function ChatPanel({
// Plain Enter (no modifiers) → submit
if (!e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey) {
- if (input.trim().length === 0) {
+ if (!hasPendingInput) {
e.preventDefault()
return
}
@@ -635,7 +686,7 @@ export function ChatPanel({
'size-8 md:size-10 rounded-full'
)}
disabled={
- (input.length === 0 && !isLoading) || !hasAvailableModels
+ (!hasPendingInput && !isLoading) || !hasAvailableModels
}
onClick={isLoading ? stop : undefined}
title={
diff --git a/components/chat.tsx b/components/chat.tsx
index 5a742abb..2fb76aae 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -53,6 +53,7 @@ export function Chat({
query,
isGuest = false,
isCloudDeployment = false,
+ libraryAvailable = true,
modelSelectorData
}: {
id?: string
@@ -60,6 +61,7 @@ export function Chat({
query?: string
isGuest?: boolean
isCloudDeployment?: boolean
+ libraryAvailable?: boolean
modelSelectorData?: ModelSelectorData
}) {
const router = useRouter()
@@ -76,6 +78,7 @@ export function Chat({
// Clear other chat-related state that persists due to Next.js 16 component caching
setInput('')
setUploadedFiles([])
+ setQuotedContexts([])
setErrorModal({
open: false,
type: 'general',
@@ -86,6 +89,7 @@ export function Chat({
const scrollContainerRef = useRef<HTMLDivElement>(null)
const [isAtBottom, setIsAtBottom] = useState(true)
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
+ const [quotedContexts, setQuotedContexts] = useState<string[]>([])
const [input, setInput] = useState('')
const [errorModal, setErrorModal] = useState<{
open: boolean
@@ -249,6 +253,16 @@ export function Chat({
setInput(e.target.value)
}
+ const handleQuoteContext = useCallback(
+ (text: string) => {
+ const trimmed = text.trim()
+ if (!trimmed) return
+
+ setQuotedContexts(prev => [...prev, trimmed])
+ },
+ [setQuotedContexts]
+ )
+
// Convert messages array to sections array.
// Deduplicate by message.id — @ai-sdk/react useChat can occasionally
// surface the same assistant message twice during stream finalization,
@@ -530,6 +544,8 @@ export function Chat({
status={status}
chatId={chatId}
isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
addToolResult={({
toolCallId,
result
@@ -570,6 +586,7 @@ export function Chat({
onUpdateMessage={handleUpdateAndReloadMessage}
reload={handleReloadFrom}
error={error}
+ onQuoteContext={handleQuoteContext}
/>
<ChatPanel
chatId={chatId}
@@ -587,6 +604,8 @@ export function Chat({
showScrollToBottomButton={!isAtBottom}
uploadedFiles={uploadedFiles}
setUploadedFiles={setUploadedFiles}
+ quotedContexts={quotedContexts}
+ setQuotedContexts={setQuotedContexts}
scrollContainerRef={scrollContainerRef}
onNewChat={handleNewChat}
isGuest={isGuest}
diff --git a/components/header.tsx b/components/header.tsx
index 4bc50d60..6c867592 100644
--- a/components/header.tsx
+++ b/components/header.tsx
@@ -5,11 +5,14 @@ import React, { useState } from 'react'
import { usePathname } from 'next/navigation'
import { User } from '@supabase/supabase-js'
+import { IconLibrary as LibraryIcon } from '@tabler/icons-react'
+import { captureClient } from '@/lib/analytics/posthog-client'
import { cn } from '@/lib/utils'
import { useSidebar } from '@/components/ui/sidebar'
+import { useLibrary } from './library/library-context'
import { Button } from './ui/button'
import { FeedbackModal } from './feedback-modal'
// import { Button } from './ui/button' // No longer needed directly here for Sign In button
@@ -22,6 +25,7 @@ interface HeaderProps {
export const Header: React.FC<HeaderProps> = ({ user }) => {
const { open } = useSidebar()
+ const { isOpen: libraryOpen, toggleLibrary } = useLibrary()
const pathname = usePathname()
const [feedbackOpen, setFeedbackOpen] = useState(false)
const isRootPage = pathname === '/'
@@ -48,6 +52,23 @@ export const Header: React.FC<HeaderProps> = ({ user }) => {
Feedback
</Button>
)}
+ {user && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="gap-1.5"
+ onClick={() => {
+ toggleLibrary()
+ captureClient(
+ libraryOpen ? 'library_closed' : 'library_opened',
+ { source: 'header' }
+ )
+ }}
+ >
+ <LibraryIcon className="size-4" />
+ Library
+ </Button>
+ )}
{user ? <UserMenu user={user} /> : <GuestMenu />}
</div>
</header>
diff --git a/components/inspector/inspector-drawer.tsx b/components/inspector/inspector-drawer.tsx
index db5feff9..f3d6d363 100644
--- a/components/inspector/inspector-drawer.tsx
+++ b/components/inspector/inspector-drawer.tsx
@@ -7,16 +7,21 @@ import { useMediaQuery } from '@/lib/hooks/use-media-query'
import { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer'
import { useArtifact } from '@/components/artifact/artifact-context'
+import { useLibrary } from '@/components/library/library-context'
+import { LibraryPanel } from '@/components/library/library-panel'
import { InspectorPanel } from './inspector-panel'
export function InspectorDrawer() {
const { state, close } = useArtifact()
+ const { isOpen: libraryOpen, closeLibrary } = useLibrary()
const part = state.part
const isMobile = useMediaQuery('(max-width: 767px)')
+ const open = state.isOpen || libraryOpen
// Function to get the title based on part type (mirrors ArtifactPanel logic)
const getTitle = () => {
+ if (libraryOpen) return 'Library'
if (!part) return 'Artifact' // Default title
switch (part.type) {
case 'tool-search':
@@ -38,17 +43,25 @@ export function InspectorDrawer() {
return (
<Drawer
- open={state.isOpen}
+ open={open}
onOpenChange={open => {
- if (!open) close()
+ if (!open) {
+ if (libraryOpen) {
+ closeLibrary()
+ } else {
+ close()
+ }
+ }
}}
modal={true}
>
- <DrawerContent className="p-0 max-h-[90vh] md:hidden">
+ <DrawerContent className="h-[90svh] max-h-[90svh] p-0 md:hidden">
<DrawerTitle asChild>
<VisuallyHidden>{getTitle()}</VisuallyHidden>
</DrawerTitle>
- <InspectorPanel />
+ <div className="min-h-0 flex-1 overflow-hidden">
+ {libraryOpen ? <LibraryPanel /> : <InspectorPanel />}
+ </div>
</DrawerContent>
</Drawer>
)
diff --git a/components/library/library-context.tsx b/components/library/library-context.tsx
new file mode 100644
index 00000000..15218eca
--- /dev/null
+++ b/components/library/library-context.tsx
@@ -0,0 +1,120 @@
+'use client'
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState
+} from 'react'
+
+import type { Note } from '@/lib/db/schema'
+
+import { useSidebar } from '../ui/sidebar'
+
+type NotesCache = {
+ notes: Note[]
+ updatedAt: number
+}
+
+type LibraryContextValue = {
+ isOpen: boolean
+ notesCache: NotesCache | null
+ refreshKey: number
+ openLibrary: () => void
+ closeLibrary: () => void
+ toggleLibrary: () => void
+ replaceNotesCache: (notes: Note[]) => void
+ upsertCachedNote: (note: Note) => void
+ removeCachedNote: (noteId: string) => void
+ refreshLibrary: () => void
+}
+
+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 [refreshKey, setRefreshKey] = useState(0)
+ const { setOpen: setSidebarOpen } = useSidebar()
+
+ const openLibrary = useCallback(() => {
+ setSidebarOpen(false)
+ setIsOpen(true)
+ }, [setSidebarOpen])
+ const closeLibrary = useCallback(() => setIsOpen(false), [])
+ const toggleLibrary = useCallback(() => {
+ setIsOpen(open => {
+ if (!open) {
+ setSidebarOpen(false)
+ }
+ return !open
+ })
+ }, [setSidebarOpen])
+ const replaceNotesCache = useCallback((notes: Note[]) => {
+ setNotesCache({ notes, 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)],
+ updatedAt: Date.now()
+ }
+ })
+ }, [])
+ const removeCachedNote = useCallback((noteId: string) => {
+ setNotesCache(cache => {
+ if (!cache) return cache
+
+ return {
+ notes: cache.notes.filter(note => note.id !== noteId),
+ updatedAt: Date.now()
+ }
+ })
+ }, [])
+ const refreshLibrary = useCallback(() => {
+ setRefreshKey(key => key + 1)
+ }, [])
+
+ const value = useMemo(
+ () => ({
+ isOpen,
+ notesCache,
+ refreshKey,
+ openLibrary,
+ closeLibrary,
+ toggleLibrary,
+ replaceNotesCache,
+ upsertCachedNote,
+ removeCachedNote,
+ refreshLibrary
+ }),
+ [
+ closeLibrary,
+ isOpen,
+ notesCache,
+ openLibrary,
+ removeCachedNote,
+ replaceNotesCache,
+ refreshLibrary,
+ toggleLibrary,
+ upsertCachedNote,
+ refreshKey
+ ]
+ )
+
+ return (
+ <LibraryContext.Provider value={value}>{children}</LibraryContext.Provider>
+ )
+}
+
+export function useLibrary() {
+ const context = useContext(LibraryContext)
+ if (!context) {
+ throw new Error('useLibrary must be used within a LibraryProvider')
+ }
+
+ return context
+}
diff --git a/components/library/library-panel.tsx b/components/library/library-panel.tsx
new file mode 100644
index 00000000..756091c4
--- /dev/null
+++ b/components/library/library-panel.tsx
@@ -0,0 +1,445 @@
+'use client'
+
+import { useEffect, useMemo, useRef, useState, useTransition } from 'react'
+
+import {
+ IconArrowLeft as ArrowLeft,
+ IconDots as MoreHorizontal,
+ IconFileText as FileText,
+ IconLibrary as LibraryIcon,
+ IconTrash as Trash,
+ IconX as X
+} from '@tabler/icons-react'
+import { toast } from 'sonner'
+
+import { deleteNote, listNotes } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
+import type { Note } from '@/lib/db/schema'
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle
+} from '@/components/ui/alert-dialog'
+import { Button } from '@/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { Separator } from '@/components/ui/separator'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Spinner } from '@/components/ui/spinner'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { TooltipButton } from '@/components/ui/tooltip-button'
+
+import { MarkdownMessage } from '@/components/message'
+
+import { useLibrary } from './library-context'
+
+const LIBRARY_CACHE_TTL_MS = 60_000
+
+function formatNoteDate(value: Date | string) {
+ const date = value instanceof Date ? value : new Date(value)
+ return new Intl.DateTimeFormat(undefined, {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ }).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 stripMarkdownTitle(value: string) {
+ return stripMarkdownText(value)
+}
+
+function NoteActionsMenu({ onDelete }: { onDelete: () => void }) {
+ const [isMenuOpen, setIsMenuOpen] = useState(false)
+
+ return (
+ <DropdownMenu open={isMenuOpen} onOpenChange={setIsMenuOpen}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0 text-muted-foreground"
+ onClick={event => event.stopPropagation()}
+ aria-label="Note actions"
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="left" align="start">
+ <DropdownMenuItem
+ className="gap-2 text-destructive focus:text-destructive"
+ onSelect={event => {
+ event.preventDefault()
+ setIsMenuOpen(false)
+ onDelete()
+ }}
+ >
+ <Trash size={14} />
+ Delete Note
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function LibraryLoadingSkeleton() {
+ return (
+ <div className="space-y-1 p-2">
+ {Array.from({ length: 5 }).map((_, index) => (
+ <div key={index} className="rounded-md px-3 py-2">
+ <div className="flex items-center gap-2">
+ <Skeleton className="size-3.5 shrink-0 rounded-sm" />
+ <Skeleton className="h-4 w-3/5" />
+ </div>
+ <Skeleton className="mt-2 h-3 w-full" />
+ <Skeleton className="mt-1 h-3 w-4/5" />
+ <Skeleton className="mt-2 h-3 w-24" />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export function LibraryPanel() {
+ const {
+ isOpen,
+ closeLibrary,
+ notesCache,
+ refreshKey,
+ replaceNotesCache,
+ removeCachedNote
+ } = useLibrary()
+ const [selectedNote, setSelectedNote] = useState<Note | null>(null)
+ const [deleteTarget, setDeleteTarget] = useState<Note | null>(null)
+ const [hasLoadAttempted, setHasLoadAttempted] = useState(false)
+ const [isDeleting, startDeleteTransition] = useTransition()
+ const lastFetchedRefreshKeyRef = useRef<number | null>(null)
+ const previousIsOpenRef = useRef(false)
+
+ useEffect(() => {
+ const justOpened = isOpen && !previousIsOpenRef.current
+ previousIsOpenRef.current = isOpen
+
+ if (!justOpened || !notesCache) return
+
+ captureClient('library_list_loaded', {
+ source: 'cache',
+ noteCount: notesCache.notes.length,
+ isEmpty: notesCache.notes.length === 0,
+ cacheAgeMs: Date.now() - notesCache.updatedAt
+ })
+ }, [isOpen, notesCache])
+
+ useEffect(() => {
+ if (!isOpen) return
+
+ const hasCache = Boolean(notesCache)
+ const isRefreshStale = lastFetchedRefreshKeyRef.current !== refreshKey
+ const isTimeStale =
+ !notesCache || Date.now() - notesCache.updatedAt > LIBRARY_CACHE_TTL_MS
+
+ if (hasCache && !isRefreshStale && !isTimeStale) {
+ return
+ }
+
+ const loadReason = !hasCache ? 'cold' : isRefreshStale ? 'refresh' : 'ttl'
+ let cancelled = false
+ listNotes().then(result => {
+ if (cancelled) return
+
+ setHasLoadAttempted(true)
+
+ if (!result.success) {
+ captureClient('library_list_load_failed', {
+ source: 'network',
+ reason: loadReason,
+ error: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to load library')
+ return
+ }
+
+ const nextNotes = result.notes ?? []
+ captureClient('library_list_loaded', {
+ source: 'network',
+ reason: loadReason,
+ noteCount: nextNotes.length,
+ isEmpty: nextNotes.length === 0
+ })
+ replaceNotesCache(nextNotes)
+ lastFetchedRefreshKeyRef.current = refreshKey
+ setSelectedNote(current => {
+ if (!current) return current
+
+ return nextNotes.find(note => note.id === current.id) ?? null
+ })
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [isOpen, notesCache, refreshKey, replaceNotesCache])
+
+ const visibleNotes = notesCache?.notes ?? []
+ const isLoading = !notesCache && !hasLoadAttempted
+ const selectedTitle = useMemo(
+ () => stripMarkdownTitle(selectedNote?.title ?? ''),
+ [selectedNote?.title]
+ )
+
+ function handleOpenNote(note: Note) {
+ setSelectedNote(note)
+ captureClient('note_opened', {
+ source: 'library_list',
+ noteId: note.id,
+ noteCount: visibleNotes.length
+ })
+ }
+
+ function handleCloseLibrary(source: 'panel_header' | 'detail_header') {
+ closeLibrary()
+ captureClient('library_closed', { source })
+ }
+
+ function handleRequestDeleteNote(
+ note: Note,
+ source: 'library_list' | 'library_detail'
+ ) {
+ setDeleteTarget(note)
+ captureClient('note_delete_requested', { source, noteId: note.id })
+ }
+
+ function handleDeleteNote() {
+ if (!deleteTarget) return
+
+ const noteId = deleteTarget.id
+ setDeleteTarget(null)
+ startDeleteTransition(async () => {
+ const result = await deleteNote(noteId)
+ if (!result.success) {
+ captureClient('note_delete_failed', {
+ noteId,
+ reason: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to delete note')
+ return
+ }
+
+ captureClient('note_deleted', { noteId })
+ toast.success('Note deleted')
+ if (selectedNote?.id === noteId) {
+ setSelectedNote(null)
+ }
+ removeCachedNote(noteId)
+ })
+ }
+
+ return (
+ <TooltipProvider>
+ <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 ? (
+ <>
+ <div className="flex min-w-0 items-center gap-2">
+ <TooltipButton
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 shrink-0"
+ onClick={() => setSelectedNote(null)}
+ aria-label="Back to library"
+ tooltipContent="Back"
+ >
+ <ArrowLeft className="size-4" />
+ </TooltipButton>
+ <div className="min-w-0">
+ <h3 className="truncate text-sm font-medium">
+ {selectedTitle || 'Untitled note'}
+ </h3>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <NoteActionsMenu
+ onDelete={() =>
+ handleRequestDeleteNote(selectedNote, 'library_detail')
+ }
+ />
+ <TooltipButton
+ variant="ghost"
+ size="icon"
+ onClick={() => handleCloseLibrary('detail_header')}
+ aria-label="Close panel"
+ tooltipContent="Close"
+ >
+ <X className="size-4" />
+ </TooltipButton>
+ </div>
+ </>
+ ) : (
+ <>
+ <h3 className="flex min-w-0 items-center gap-2">
+ <div className="flex items-center gap-2 rounded-md p-2">
+ <LibraryIcon size={18} />
+ </div>
+ <span className="truncate text-sm font-medium">Library</span>
+ </h3>
+ <TooltipButton
+ variant="ghost"
+ size="icon"
+ onClick={() => handleCloseLibrary('panel_header')}
+ aria-label="Close panel"
+ tooltipContent="Close"
+ >
+ <X className="size-4" />
+ </TooltipButton>
+ </>
+ )}
+ </div>
+ <Separator className="my-1 bg-border/50" />
+
+ {selectedNote ? (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <article
+ data-vaul-no-drag
+ className="min-h-0 flex-1 overflow-y-auto p-4"
+ >
+ <MarkdownMessage message={selectedNote.content} />
+ </article>
+ <footer className="shrink-0 border-t px-4 py-2 text-xs text-muted-foreground">
+ Saved {formatNoteDate(selectedNote.createdAt)}
+ </footer>
+ </div>
+ ) : (
+ <div
+ data-vaul-no-drag
+ className="min-h-0 flex-1 overflow-y-auto p-2"
+ >
+ {isLoading ? (
+ <LibraryLoadingSkeleton />
+ ) : visibleNotes.length === 0 ? (
+ <div className="px-4 py-8 text-sm text-muted-foreground">
+ No saved notes yet.
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {visibleNotes.map(note => {
+ const title =
+ stripMarkdownTitle(note.title) || 'Untitled note'
+ return (
+ <div
+ key={note.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={() => handleOpenNote(note)}
+ >
+ <div className="flex items-center gap-2">
+ <FileText className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">
+ {title}
+ </span>
+ </div>
+ <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
+ {getExcerpt(note.content)}
+ </p>
+ <p className="mt-1 text-[11px] text-muted-foreground/75">
+ {formatNoteDate(note.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">
+ <NoteActionsMenu
+ onDelete={() =>
+ handleRequestDeleteNote(note, 'library_list')
+ }
+ />
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <AlertDialog
+ open={Boolean(deleteTarget)}
+ onOpenChange={open => {
+ if (!open && !isDeleting) {
+ setDeleteTarget(null)
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete this note?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This action cannot be undone. The saved note will be permanently
+ deleted from your library.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={isDeleting}
+ onClick={event => {
+ event.preventDefault()
+ handleDeleteNote()
+ }}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {isDeleting ? (
+ <div className="flex items-center justify-center">
+ <Spinner />
+ </div>
+ ) : (
+ 'Delete'
+ )}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </TooltipProvider>
+ )
+}
diff --git a/components/message-actions.tsx b/components/message-actions.tsx
index bf17176c..63f12c9f 100644
--- a/components/message-actions.tsx
+++ b/components/message-actions.tsx
@@ -1,22 +1,35 @@
'use client'
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import Link from 'next/link'
import { UseChatHelpers } from '@ai-sdk/react'
import {
+ IconBookmark as Bookmark,
IconCopy as Copy,
IconThumbDown as ThumbsDown,
IconThumbUp as ThumbsUp
} from '@tabler/icons-react'
import { toast } from 'sonner'
+import { saveNote } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
import { stripSpecBlocks } from '@/lib/render/strip-spec-blocks'
import type { SearchResultItem } from '@/lib/types'
import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import { cn } from '@/lib/utils'
import { processCitations } from '@/lib/utils/citation'
+import { useLibrary } from './library/library-context'
import { Button } from './ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from './ui/dialog'
import { ChatShare } from './chat-share'
import { RetryButton } from './retry-button'
@@ -28,6 +41,9 @@ interface MessageActionsProps {
reload?: () => Promise<void | string | null | undefined>
chatId?: string
enableShare?: boolean
+ isGuest?: boolean
+ isCloudDeployment?: boolean
+ libraryAvailable?: boolean
className?: string
status?: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
visible?: boolean
@@ -42,6 +58,9 @@ export function MessageActions({
reload,
chatId,
enableShare,
+ isGuest = false,
+ isCloudDeployment = false,
+ libraryAvailable = true,
className,
status,
visible = true,
@@ -50,6 +69,9 @@ export function MessageActions({
const [feedbackScore, setFeedbackScore] = useState<number | null>(
initialFeedbackScore ?? null
)
+ const [isSavingNote, setIsSavingNote] = useState(false)
+ const [authPromptOpen, setAuthPromptOpen] = useState(false)
+ const { openLibrary, upsertCachedNote } = useLibrary()
const mappedMessage = useMemo(() => {
if (!message) return ''
return processCitations(message, citationMaps || {})
@@ -57,6 +79,20 @@ export function MessageActions({
const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false)
const isLoading = status === 'submitted' || status === 'streaming'
+ const showSaveButton = libraryAvailable && (!isGuest || isCloudDeployment)
+ const saveButtonShownRef = useRef(false)
+
+ useEffect(() => {
+ if (!visible || !showSaveButton || saveButtonShownRef.current) return
+
+ saveButtonShownRef.current = true
+ captureClient('note_save_button_shown', {
+ source: 'message_action',
+ chatId,
+ isGuest,
+ isCloudDeployment
+ })
+ }, [chatId, isCloudDeployment, isGuest, showSaveButton, visible])
// Keep the element mounted during loading to preserve layout; otherwise skip rendering.
if (!visible && !isLoading) {
@@ -68,6 +104,75 @@ export function MessageActions({
toast.success('Message copied to clipboard')
}
+ async function handleSaveNote() {
+ if (isSavingNote) return
+
+ const content = stripSpecBlocks(mappedMessage)
+ captureClient('note_save_clicked', {
+ source: 'button',
+ chatId,
+ chars: content.length,
+ isGuest,
+ isCloudDeployment
+ })
+
+ if (isGuest) {
+ setAuthPromptOpen(true)
+ captureClient('library_auth_prompt_opened', {
+ source: 'save_button',
+ chatId
+ })
+ return
+ }
+
+ setIsSavingNote(true)
+ try {
+ const result = await saveNote({
+ content,
+ chatId,
+ sourceMessageId: messageId
+ })
+
+ if (!result.success) {
+ captureClient('note_save_failed', {
+ source: 'button',
+ chatId,
+ reason: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to save note')
+ return
+ }
+
+ if (result.note) {
+ upsertCachedNote(result.note)
+ }
+ captureClient('note_saved', {
+ source: 'button',
+ chatId,
+ chars: content.length
+ })
+ toast.success('Saved to library', {
+ action: {
+ label: 'Open',
+ onClick: () => {
+ openLibrary()
+ captureClient('library_opened', { source: 'toast' })
+ }
+ }
+ })
+ } catch (error) {
+ console.error('Error saving note:', error)
+ captureClient('note_save_failed', {
+ source: 'button',
+ chatId,
+ reason: 'exception'
+ })
+ toast.error('Failed to save note')
+ } finally {
+ setIsSavingNote(false)
+ }
+ }
+
async function handleFeedback(score: number) {
if (isSubmittingFeedback || !traceId) return
@@ -103,56 +208,122 @@ export function MessageActions({
}
return (
- <div
- aria-hidden={!visible}
- className={cn(
- 'flex items-center gap-0.5 self-end transition-opacity duration-200',
- visible ? 'opacity-100' : 'pointer-events-none opacity-0 invisible',
- className
- )}
- >
- {reload && <RetryButton reload={reload} messageId={messageId} />}
- <Button
- variant="ghost"
- size="icon"
- onClick={handleCopy}
- className="rounded-full"
+ <>
+ <div
+ aria-hidden={!visible}
+ className={cn(
+ 'flex w-full items-center justify-between gap-3 self-stretch transition-opacity duration-200',
+ visible ? 'opacity-100' : 'pointer-events-none opacity-0 invisible',
+ className
+ )}
>
- <Copy size={14} />
- </Button>
- {traceId && (
- <>
- {(feedbackScore === null || feedbackScore === 1) && (
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleFeedback(1)}
- disabled={isSubmittingFeedback || feedbackScore === 1}
- className="rounded-full"
- >
- <ThumbsUp
- size={14}
- className={feedbackScore === 1 ? 'fill-current' : ''}
- />
- </Button>
+ <div className="flex items-center gap-0.5">
+ {reload && <RetryButton reload={reload} messageId={messageId} />}
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleCopy}
+ className="rounded-full"
+ >
+ <Copy size={14} />
+ </Button>
+ {enableShare && chatId && <ChatShare chatId={chatId} />}
+ {traceId && (
+ <>
+ {(feedbackScore === null || feedbackScore === 1) && (
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => handleFeedback(1)}
+ disabled={isSubmittingFeedback || feedbackScore === 1}
+ className="rounded-full"
+ >
+ <ThumbsUp
+ size={14}
+ className={feedbackScore === 1 ? 'fill-current' : ''}
+ />
+ </Button>
+ )}
+ {(feedbackScore === null || feedbackScore === -1) && (
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => handleFeedback(-1)}
+ disabled={isSubmittingFeedback || feedbackScore === -1}
+ className="rounded-full"
+ >
+ <ThumbsDown
+ size={14}
+ className={feedbackScore === -1 ? 'fill-current' : ''}
+ />
+ </Button>
+ )}
+ </>
)}
- {(feedbackScore === null || feedbackScore === -1) && (
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleFeedback(-1)}
- disabled={isSubmittingFeedback || feedbackScore === -1}
- className="rounded-full"
- >
- <ThumbsDown
- size={14}
- className={feedbackScore === -1 ? 'fill-current' : ''}
- />
+ </div>
+ {showSaveButton ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleSaveNote}
+ disabled={isSavingNote}
+ className="h-8 shrink-0 gap-1.5 rounded-full px-3"
+ aria-label="Save to library"
+ >
+ <Bookmark size={14} />
+ Save
+ </Button>
+ ) : (
+ <div />
+ )}
+ </div>
+
+ <Dialog open={authPromptOpen} onOpenChange={setAuthPromptOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-full bg-muted">
+ <Bookmark className="size-6 text-muted-foreground" />
+ </div>
+ <DialogTitle className="text-center text-xl font-semibold">
+ Save notes to your library
+ </DialogTitle>
+ <DialogDescription className="text-center text-muted-foreground">
+ Sign in or create an account to save answers and selected text to
+ your Library.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="flex-col gap-2">
+ <Button asChild className="w-full">
+ <Link
+ href="/auth/sign-up"
+ onClick={() =>
+ captureClient('library_auth_prompt_cta_clicked', {
+ source: 'save_button',
+ target: 'sign_up',
+ chatId
+ })
+ }
+ >
+ Sign Up
+ </Link>
</Button>
- )}
- </>
- )}
- {enableShare && chatId && <ChatShare chatId={chatId} />}
- </div>
+ <Button asChild variant="outline" className="w-full">
+ <Link
+ href="/auth/login"
+ onClick={() =>
+ captureClient('library_auth_prompt_cta_clicked', {
+ source: 'save_button',
+ target: 'sign_in',
+ chatId
+ })
+ }
+ >
+ Sign In
+ </Link>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
)
}
diff --git a/components/pasted-parts.tsx b/components/pasted-parts.tsx
index 360a70c5..2d874ff5 100644
--- a/components/pasted-parts.tsx
+++ b/components/pasted-parts.tsx
@@ -10,7 +10,13 @@ import {
// Collapsed card for a pasted text blob (a `data-pastedContent` part, or a
// legacy `<user-content>` block in old messages).
-export function PastedContentCard({ text }: { text: string }) {
+export function PastedContentCard({
+ text,
+ label = 'Pasted content'
+}: {
+ text: string
+ label?: string
+}) {
const [open, setOpen] = useState(false)
return (
<div>
@@ -20,7 +26,7 @@ export function PastedContentCard({ text }: { text: string }) {
onClick={() => setOpen(o => !o)}
>
<FileText className="size-3.5 shrink-0" />
- Pasted content · {text.length.toLocaleString()} chars
+ {label} · {text.length.toLocaleString()} chars
{open ? (
<ChevronUp className="size-3.5 shrink-0" />
) : (
diff --git a/components/render-message.tsx b/components/render-message.tsx
index a7cb52cd..3973d8b2 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -22,12 +22,15 @@ interface RenderMessageProps {
onOpenChange: (id: string, open: boolean) => void
chatId?: string
isGuest?: boolean
+ isCloudDeployment?: boolean
+ libraryAvailable?: boolean
status?: UseChatHelpers<UIMessage<unknown, UIDataTypes, UITools>>['status']
addToolResult?: (params: { toolCallId: string; result: any }) => void
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
reload?: (messageId: string) => Promise<void | string | null | undefined>
isLatestMessage?: boolean
citationMaps?: Record<string, Record<number, SearchResultItem>>
+ onQuoteContext?: (text: string) => void
}
export function RenderMessage({
@@ -37,12 +40,15 @@ export function RenderMessage({
onOpenChange,
chatId,
isGuest = false,
+ isCloudDeployment = false,
+ libraryAvailable = true,
status,
addToolResult,
onUpdateMessage,
reload,
isLatestMessage = false,
- citationMaps = {}
+ citationMaps = {},
+ onQuoteContext
}: RenderMessageProps) {
const isNonEmptyTextPart = (part: any) =>
part?.type === 'text' &&
@@ -57,6 +63,9 @@ export function RenderMessage({
const pastedTexts = parts
.filter((part: any) => part.type === 'data-pastedContent')
.map((part: any) => part.data?.text ?? '')
+ const quotedContexts = parts
+ .filter((part: any) => part.type === 'data-quotedContext')
+ .map((part: any) => part.data?.text ?? '')
const urls = parts
.filter((part: any) => part.type === 'data-sourceUrl')
.map((part: any) => part.data?.url ?? '')
@@ -72,10 +81,14 @@ export function RenderMessage({
}}
/>
))}
- {(textPart || pastedTexts.length > 0 || urls.length > 0) && (
+ {(textPart ||
+ pastedTexts.length > 0 ||
+ quotedContexts.length > 0 ||
+ urls.length > 0) && (
<UserTextSection
content={textPart?.text ?? ''}
pastedTexts={pastedTexts}
+ quotedContexts={quotedContexts}
urls={urls}
messageId={messageId}
onUpdateMessage={onUpdateMessage}
@@ -156,12 +169,15 @@ export function RenderMessage({
onOpenChange={open => onOpenChange(messageId, open)}
chatId={chatId}
isGuest={isGuest}
+ isCloudDeployment={isCloudDeployment}
+ libraryAvailable={libraryAvailable}
showActions={shouldShowActions}
messageId={messageId}
metadata={message.metadata as UIMessageMetadata | undefined}
reload={reload}
status={status}
citationMaps={citationMaps}
+ onQuoteContext={onQuoteContext}
/>
)
} else if (part.type === 'reasoning' || part.type?.startsWith?.('tool-')) {
diff --git a/components/user-text-section.tsx b/components/user-text-section.tsx
index 100487d7..7ab9c7c3 100644
--- a/components/user-text-section.tsx
+++ b/components/user-text-section.tsx
@@ -40,6 +40,7 @@ interface UserTextSectionProps {
content: string
// Pasted attachments (new data parts), placed below the instruction.
pastedTexts?: string[]
+ quotedContexts?: string[]
urls?: string[]
messageId?: string
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
@@ -48,6 +49,7 @@ interface UserTextSectionProps {
export const UserTextSection: React.FC<UserTextSectionProps> = ({
content,
pastedTexts = [],
+ quotedContexts = [],
urls = [],
messageId,
onUpdateMessage
@@ -177,11 +179,20 @@ export const UserTextSection: React.FC<UserTextSectionProps> = ({
}
// Pasted attachments (cards + URL chips), placed below the instruction.
- const attachments = (cards.length > 0 || urls.length > 0) && (
+ const attachments = (cards.length > 0 ||
+ quotedContexts.length > 0 ||
+ urls.length > 0) && (
<div className="mt-2 flex flex-col items-start gap-1.5">
{cards.map((c, i) => (
<PastedContentCard key={`card-${i}`} text={c} />
))}
+ {quotedContexts.map((c, i) => (
+ <PastedContentCard
+ key={`quoted-context-${i}`}
+ text={c}
+ label="Quoted context"
+ />
+ ))}
{urls.map((u, i) => (
<UrlChip key={`url-${i}`} url={u} />
))}
diff --git a/drizzle/0012_knowledge_library_notes.sql b/drizzle/0012_knowledge_library_notes.sql
new file mode 100644
index 00000000..8cec6a1e
--- /dev/null
+++ b/drizzle/0012_knowledge_library_notes.sql
@@ -0,0 +1,35 @@
+CREATE TABLE IF NOT EXISTS "notes" (
+ "id" varchar(191) PRIMARY KEY NOT NULL,
+ "user_id" varchar(255) NOT NULL,
+ "chat_id" varchar(191),
+ "source_message_id" varchar(191),
+ "title" text NOT NULL,
+ "content" text NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "notes_chat_id_chats_id_fk"
+ FOREIGN KEY ("chat_id") REFERENCES "public"."chats"("id")
+ ON DELETE SET NULL ON UPDATE NO ACTION
+);
+
+CREATE INDEX IF NOT EXISTS "notes_user_id_idx" ON "notes" USING btree ("user_id");
+CREATE INDEX IF NOT EXISTS "notes_user_id_updated_at_idx" ON "notes" USING btree ("user_id", "updated_at" DESC);
+CREATE INDEX IF NOT EXISTS "notes_chat_id_idx" ON "notes" USING btree ("chat_id");
+CREATE INDEX IF NOT EXISTS "notes_source_message_id_idx" ON "notes" USING btree ("source_message_id");
+
+ALTER TABLE "notes" ENABLE ROW LEVEL SECURITY;
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'notes' AND policyname = 'users_manage_own_notes'
+ ) THEN
+ CREATE POLICY "users_manage_own_notes" ON "notes"
+ AS PERMISSIVE
+ FOR ALL
+ TO public
+ USING (user_id = current_setting('app.current_user_id', true))
+ WITH CHECK (user_id = current_setting('app.current_user_id', true));
+ END IF;
+END $$;
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index a4a82ed7..28b6916a 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -85,6 +85,13 @@
"when": 1779207879792,
"tag": "0011_feedback_anonymization",
"breakpoints": true
+ },
+ {
+ "idx": 12,
+ "version": "7",
+ "when": 1781635200000,
+ "tag": "0012_knowledge_library_notes",
+ "breakpoints": true
}
]
}
diff --git a/drizzle/relations.ts b/drizzle/relations.ts
index 28c2f5e5..4e6297f4 100644
--- a/drizzle/relations.ts
+++ b/drizzle/relations.ts
@@ -1,6 +1,6 @@
import { relations } from 'drizzle-orm/relations'
-import { chats, messages, parts } from './schema'
+import { chats, messages, notes, parts } from './schema'
export const messagesRelations = relations(messages, ({ one, many }) => ({
chat: one(chats, {
@@ -11,7 +11,8 @@ export const messagesRelations = relations(messages, ({ one, many }) => ({
}))
export const chatsRelations = relations(chats, ({ many }) => ({
- messages: many(messages)
+ messages: many(messages),
+ notes: many(notes)
}))
export const partsRelations = relations(parts, ({ one }) => ({
@@ -20,3 +21,10 @@ export const partsRelations = relations(parts, ({ one }) => ({
references: [messages.id]
})
}))
+
+export const notesRelations = relations(notes, ({ one }) => ({
+ chat: one(chats, {
+ fields: [notes.chatId],
+ references: [chats.id]
+ })
+}))
diff --git a/drizzle/schema.ts b/drizzle/schema.ts
index 2646371d..07b5ec18 100644
--- a/drizzle/schema.ts
+++ b/drizzle/schema.ts
@@ -204,6 +204,55 @@ export const parts = pgTable(
]
)
+export const notes = pgTable(
+ 'notes',
+ {
+ id: varchar({ length: 191 }).primaryKey().notNull(),
+ userId: varchar('user_id', { length: 255 }).notNull(),
+ chatId: varchar('chat_id', { length: 191 }),
+ sourceMessageId: varchar('source_message_id', { length: 191 }),
+ title: text().notNull(),
+ content: text().notNull(),
+ createdAt: timestamp('created_at', { mode: 'string' })
+ .defaultNow()
+ .notNull(),
+ updatedAt: timestamp('updated_at', { mode: 'string' })
+ .defaultNow()
+ .notNull()
+ },
+ table => [
+ index('notes_chat_id_idx').using(
+ 'btree',
+ table.chatId.asc().nullsLast().op('text_ops')
+ ),
+ index('notes_source_message_id_idx').using(
+ 'btree',
+ table.sourceMessageId.asc().nullsLast().op('text_ops')
+ ),
+ index('notes_user_id_idx').using(
+ 'btree',
+ table.userId.asc().nullsLast().op('text_ops')
+ ),
+ index('notes_user_id_updated_at_idx').using(
+ 'btree',
+ table.userId.asc().nullsLast().op('text_ops'),
+ table.updatedAt.desc().nullsLast().op('timestamp_ops')
+ ),
+ foreignKey({
+ columns: [table.chatId],
+ foreignColumns: [chats.id],
+ name: 'notes_chat_id_chats_id_fk'
+ }).onDelete('set null'),
+ pgPolicy('users_manage_own_notes', {
+ as: 'permissive',
+ for: 'all',
+ to: ['public'],
+ using: sql`user_id = current_setting('app.current_user_id', true)`,
+ withCheck: sql`user_id = current_setting('app.current_user_id', true)`
+ })
+ ]
+)
+
export const feedback = pgTable(
'feedback',
{
diff --git a/lib/actions/__tests__/account.test.ts b/lib/actions/__tests__/account.test.ts
index 2329ad2d..c5a40b31 100644
--- a/lib/actions/__tests__/account.test.ts
+++ b/lib/actions/__tests__/account.test.ts
@@ -28,6 +28,7 @@ describe('Account Actions', () => {
vi.mocked(getCurrentUser).mockResolvedValue(user as any)
vi.mocked(dbActions.deleteUserChats).mockResolvedValue({ success: true })
+ vi.mocked(dbActions.deleteUserNotes).mockResolvedValue({ success: true })
vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({
success: true
})
@@ -91,6 +92,7 @@ describe('Account Actions', () => {
expect(result).toEqual({ success: true })
expect(dbActions.deleteUserChats).toHaveBeenCalledWith(user.id)
+ expect(dbActions.deleteUserNotes).toHaveBeenCalledWith(user.id)
expect(dbActions.anonymizeUserFeedback).toHaveBeenCalledWith(user.id)
expect(deleteUserObjects).toHaveBeenCalledWith(user.id)
expect(deleteUser).toHaveBeenCalledWith(user.id)
@@ -115,6 +117,23 @@ describe('Account Actions', () => {
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
+ it('stops before storage and auth deletion when notes deletion fails', async () => {
+ vi.mocked(dbActions.deleteUserNotes).mockResolvedValue({
+ success: false,
+ error: 'Failed to delete user notes'
+ })
+
+ const result = await deleteAccount()
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Failed to delete user notes'
+ })
+ expect(deleteUserObjects).not.toHaveBeenCalled()
+ expect(deleteUser).not.toHaveBeenCalled()
+ expect(trackAccountDeleted).not.toHaveBeenCalled()
+ })
+
it('stops before storage and auth deletion when feedback anonymization fails', async () => {
vi.mocked(dbActions.anonymizeUserFeedback).mockResolvedValue({
success: false,
@@ -142,6 +161,7 @@ describe('Account Actions', () => {
error: 'Storage error'
})
expect(dbActions.deleteUserChats).toHaveBeenCalledWith(user.id)
+ expect(dbActions.deleteUserNotes).toHaveBeenCalledWith(user.id)
expect(deleteUser).not.toHaveBeenCalled()
expect(trackAccountDeleted).not.toHaveBeenCalled()
})
diff --git a/lib/actions/__tests__/notes.test.ts b/lib/actions/__tests__/notes.test.ts
new file mode 100644
index 00000000..21cb9029
--- /dev/null
+++ b/lib/actions/__tests__/notes.test.ts
@@ -0,0 +1,95 @@
+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 { deleteNote, getNote, listNotes, saveNote } from '../notes'
+
+vi.mock('@/lib/auth/get-current-user')
+vi.mock('@/lib/db/actions')
+
+const originalEnableAuth = process.env.ENABLE_AUTH
+
+const note = {
+ id: 'note-1',
+ userId: 'user-1',
+ chatId: 'chat-1',
+ sourceMessageId: 'message-1',
+ title: 'Saved answer',
+ content: 'Saved answer content',
+ createdAt: new Date('2026-06-17T00:00:00Z'),
+ updatedAt: new Date('2026-06-17T00:00:00Z')
+}
+
+describe('Note Actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ 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.getNote).mockResolvedValue(note)
+ vi.mocked(dbActions.deleteNote).mockResolvedValue({ success: true })
+ })
+
+ afterEach(() => {
+ process.env.ENABLE_AUTH = originalEnableAuth
+ })
+
+ it('saves a markdown note for the current user', async () => {
+ const result = await saveNote({
+ content: '## **Saved answer**\n\nSaved answer content',
+ chatId: 'chat-1',
+ sourceMessageId: 'message-1'
+ })
+
+ expect(result).toEqual({ success: true, note })
+ expect(dbActions.createNote).toHaveBeenCalledWith({
+ userId: 'user-1',
+ chatId: 'chat-1',
+ sourceMessageId: 'message-1',
+ title: 'Saved answer',
+ content: '## **Saved answer**\n\nSaved answer content'
+ })
+ })
+
+ it('rejects empty content', async () => {
+ const result = await saveNote({ content: ' ' })
+
+ expect(result).toEqual({ success: false, error: 'Nothing to save.' })
+ expect(dbActions.createNote).not.toHaveBeenCalled()
+ })
+
+ it('rejects anonymous mode', async () => {
+ process.env.ENABLE_AUTH = 'false'
+
+ const result = await saveNote({ content: 'Saved answer' })
+
+ expect(result).toEqual({
+ success: false,
+ error: 'Library is unavailable in anonymous mode.'
+ })
+ expect(dbActions.createNote).not.toHaveBeenCalled()
+ })
+
+ it('lists current user notes', async () => {
+ const result = await listNotes()
+
+ expect(result).toEqual({ success: true, notes: [note] })
+ expect(dbActions.getNotes).toHaveBeenCalledWith('user-1')
+ })
+
+ it('loads a current user note', async () => {
+ const result = await getNote('note-1')
+
+ expect(result).toEqual({ success: true, note })
+ expect(dbActions.getNote).toHaveBeenCalledWith('note-1', 'user-1')
+ })
+
+ it('deletes a current user note', async () => {
+ const result = await deleteNote('note-1')
+
+ expect(result).toEqual({ success: true })
+ expect(dbActions.deleteNote).toHaveBeenCalledWith('note-1', 'user-1')
+ })
+})
diff --git a/lib/actions/account.ts b/lib/actions/account.ts
index 5ce18642..2a50fcd9 100644
--- a/lib/actions/account.ts
+++ b/lib/actions/account.ts
@@ -52,6 +52,14 @@ export async function deleteAccount(): Promise<{
}
}
+ const deleteNotesResult = await dbActions.deleteUserNotes(user.id)
+ if (!deleteNotesResult.success) {
+ return {
+ success: false,
+ error: deleteNotesResult.error ?? 'Failed to delete account data'
+ }
+ }
+
const anonymizeFeedbackResult = await dbActions.anonymizeUserFeedback(
user.id
)
diff --git a/lib/actions/notes.ts b/lib/actions/notes.ts
new file mode 100644
index 00000000..101e1d7d
--- /dev/null
+++ b/lib/actions/notes.ts
@@ -0,0 +1,137 @@
+'use server'
+
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import * as dbActions from '@/lib/db/actions'
+import type { Note } from '@/lib/db/schema'
+
+const MAX_TITLE_LENGTH = 120
+
+function stripMarkdownTitle(value: string) {
+ return value
+ .replace(/^#{1,6}\s+/, '')
+ .replace(/[*_~`>#\[\]()]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+function deriveTitle(content: string, title?: string) {
+ const candidate = stripMarkdownTitle(
+ title?.trim() ||
+ content
+ .split('\n')
+ .map(line => stripMarkdownTitle(line))
+ .find(Boolean) ||
+ 'Untitled note'
+ )
+
+ return candidate.length > MAX_TITLE_LENGTH
+ ? `${candidate.slice(0, MAX_TITLE_LENGTH - 1)}...`
+ : candidate
+}
+
+async function requireNoteUserId() {
+ 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 save notes.' }
+ }
+
+ return { userId, error: null }
+}
+
+export async function saveNote({
+ content,
+ title,
+ chatId,
+ sourceMessageId
+}: {
+ content: string
+ title?: string
+ chatId?: string
+ sourceMessageId?: string
+}): Promise<{ success: boolean; note?: Note; error?: string }> {
+ const trimmedContent = content.trim()
+ if (!trimmedContent) {
+ return { success: false, error: 'Nothing to save.' }
+ }
+
+ const { userId, error } = await requireNoteUserId()
+ if (!userId) {
+ return { success: false, error: error ?? 'User not authenticated' }
+ }
+
+ try {
+ const note = await dbActions.createNote({
+ userId,
+ chatId: chatId || null,
+ sourceMessageId: sourceMessageId || null,
+ title: deriveTitle(trimmedContent, title),
+ content: trimmedContent
+ })
+ return { success: true, note }
+ } catch (error) {
+ console.error('Error saving note:', error)
+ return { success: false, error: 'Failed to save note.' }
+ }
+}
+
+export async function listNotes(): 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.getNotes(userId)
+ return { success: true, notes }
+ } catch (error) {
+ console.error('Error listing notes:', error)
+ return { success: false, notes: [], error: 'Failed to load notes.' }
+ }
+}
+
+export async function getNote(
+ noteId: string
+): Promise<{ success: boolean; note?: Note | null; error?: string }> {
+ const { userId, error } = await requireNoteUserId()
+ if (!userId) {
+ return {
+ success: false,
+ note: null,
+ error: error ?? 'User not authenticated'
+ }
+ }
+
+ try {
+ const note = await dbActions.getNote(noteId, userId)
+ return { success: true, note }
+ } catch (error) {
+ console.error('Error loading note:', error)
+ return { success: false, note: null, error: 'Failed to load note.' }
+ }
+}
+
+export async function deleteNote(
+ noteId: string
+): Promise<{ success: boolean; error?: string }> {
+ const { userId, error } = await requireNoteUserId()
+ if (!userId) {
+ return { success: false, error: error ?? 'User not authenticated' }
+ }
+
+ return dbActions.deleteNote(noteId, userId)
+}
diff --git a/lib/db/actions.ts b/lib/db/actions.ts
index a3c2b5b4..ab21c069 100644
--- a/lib/db/actions.ts
+++ b/lib/db/actions.ts
@@ -12,8 +12,8 @@ import {
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import { incrementDbOperationCount } from '@/lib/utils/perf-tracking'
-import type { Chat, Message } from './schema'
-import { chats, feedback, generateId, messages, parts } from './schema'
+import type { Chat, Message, NewNote, Note } from './schema'
+import { chats, feedback, generateId, messages, notes, parts } from './schema'
import { withOptionalRLS, withRLS } from './with-rls'
import { db } from '.'
@@ -362,6 +362,78 @@ export async function deleteUserChats(
}
}
+export async function createNote(
+ note: Omit<NewNote, 'id' | 'createdAt' | 'updatedAt'>
+): Promise<Note> {
+ return withRLS(note.userId, async tx => {
+ const [createdNote] = await tx.insert(notes).values(note).returning()
+
+ return createdNote
+ })
+}
+
+export async function getNotes(userId: string): Promise<Note[]> {
+ return withRLS(userId, async tx => {
+ return tx
+ .select()
+ .from(notes)
+ .where(eq(notes.userId, userId))
+ .orderBy(desc(notes.updatedAt))
+ })
+}
+
+export async function getNote(
+ noteId: string,
+ userId: string
+): Promise<Note | null> {
+ return withRLS(userId, async tx => {
+ const [note] = await tx
+ .select()
+ .from(notes)
+ .where(and(eq(notes.id, noteId), eq(notes.userId, userId)))
+ .limit(1)
+
+ return note ?? null
+ })
+}
+
+export async function deleteNote(
+ noteId: string,
+ userId: string
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ return withRLS(userId, async tx => {
+ const [deletedNote] = await tx
+ .delete(notes)
+ .where(and(eq(notes.id, noteId), eq(notes.userId, userId)))
+ .returning({ id: notes.id })
+
+ if (!deletedNote) {
+ return { success: false, error: 'Note not found' }
+ }
+
+ return { success: true }
+ })
+ } catch (error) {
+ console.error('Error deleting note:', error)
+ return { success: false, error: 'Failed to delete note' }
+ }
+}
+
+export async function deleteUserNotes(
+ userId: string
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ return withRLS(userId, async tx => {
+ await tx.delete(notes).where(eq(notes.userId, userId))
+ return { success: true }
+ })
+ } catch (error) {
+ console.error('Error deleting user notes:', error)
+ return { success: false, error: 'Failed to delete user notes' }
+ }
+}
+
/**
* Remove account linkage from feedback while retaining the feedback content.
*/
diff --git a/lib/db/relations.ts b/lib/db/relations.ts
index 9fc2e953..12a66669 100644
--- a/lib/db/relations.ts
+++ b/lib/db/relations.ts
@@ -1,9 +1,10 @@
import { relations } from 'drizzle-orm'
-import { chats, messages, parts } from './schema'
+import { chats, messages, notes, parts } from './schema'
export const chatsRelations = relations(chats, ({ many }) => ({
- messages: many(messages)
+ messages: many(messages),
+ notes: many(notes)
}))
export const messagesRelations = relations(messages, ({ one, many }) => ({
@@ -20,3 +21,10 @@ export const partsRelations = relations(parts, ({ one }) => ({
references: [messages.id]
})
}))
+
+export const notesRelations = relations(notes, ({ one }) => ({
+ chat: one(chats, {
+ fields: [notes.chatId],
+ references: [chats.id]
+ })
+}))
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 804064e3..731a3f5b 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -258,6 +258,48 @@ export const parts = pgTable(
export type Part = InferSelectModel<typeof parts>
export type NewPart = typeof parts.$inferInsert
+// Notes table
+export const notes = pgTable(
+ 'notes',
+ {
+ id: varchar('id', { length: ID_LENGTH })
+ .primaryKey()
+ .$defaultFn(() => generateId()),
+ userId: varchar('user_id', { length: USER_ID_LENGTH }).notNull(),
+ chatId: varchar('chat_id', { length: ID_LENGTH }).references(
+ () => chats.id,
+ { onDelete: 'set null' }
+ ),
+ sourceMessageId: varchar('source_message_id', {
+ length: ID_LENGTH
+ }),
+ title: text('title').notNull(),
+ content: text('content').notNull(),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+ updatedAt: timestamp('updated_at').notNull().defaultNow()
+ },
+ table => [
+ index('notes_user_id_idx').on(table.userId),
+ index('notes_user_id_updated_at_idx').on(
+ table.userId,
+ table.updatedAt.desc()
+ ),
+ index('notes_chat_id_idx').on(table.chatId),
+ index('notes_source_message_id_idx').on(table.sourceMessageId),
+
+ pgPolicy('users_manage_own_notes', {
+ as: 'permissive',
+ for: 'all',
+ to: 'public',
+ using: sql`user_id = current_setting('app.current_user_id', true)`,
+ withCheck: sql`user_id = current_setting('app.current_user_id', true)`
+ })
+ ]
+).enableRLS()
+
+export type Note = InferSelectModel<typeof notes>
+export type NewNote = typeof notes.$inferInsert
+
// Feedback table
export const feedback = pgTable(
'feedback',
diff --git a/lib/streaming/helpers/convert-data-part.ts b/lib/streaming/helpers/convert-data-part.ts
index fae6a563..b328aea7 100644
--- a/lib/streaming/helpers/convert-data-part.ts
+++ b/lib/streaming/helpers/convert-data-part.ts
@@ -25,6 +25,17 @@ export function convertDataPart(part: {
}
}
+ if (part.type === 'data-quotedContext') {
+ const data = part.data as { text?: unknown } | undefined
+ const text = typeof data?.text === 'string' ? data.text : ''
+ if (!text) return undefined
+ const nonce = randomUUID().slice(0, 8)
+ return {
+ type: 'text',
+ text: `[quoted-context ${nonce}]\n${text}\n[/quoted-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/types/ai.ts b/lib/types/ai.ts
index d3ef8911..b3499207 100644
--- a/lib/types/ai.ts
+++ b/lib/types/ai.ts
@@ -29,6 +29,7 @@ export type UIDataTypes = {
sources?: any[]
// User-authored attachments (composer): a pasted text blob and a pasted URL.
pastedContent?: { text: string }
+ quotedContext?: { text: string }
sourceUrl?: { url: string }
}