Skip to content

An AI-powered search engine with a generative UI

feat(draft): save the shown draft version to the Library (#1092)

Yoshiki Miura2b8356aa6cf2
diff --git a/components/__tests__/draft-panel.test.tsx b/components/__tests__/draft-panel.test.tsx
new file mode 100644
index 00000000..07d2afb2
--- /dev/null
+++ b/components/__tests__/draft-panel.test.tsx
@@ -0,0 +1,87 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { saveNote } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
+
+import { DraftPanel } from '../draft/draft-panel'
+import { useLiveDraftBlock } from '../draft/draft-store'
+
+vi.mock('@/lib/analytics/posthog-client', () => ({
+ captureClient: vi.fn()
+}))
+
+vi.mock('@/lib/actions/notes', () => ({
+ saveNote: vi.fn()
+}))
+
+const upsertCachedNote = vi.fn()
+vi.mock('../library/library-context', () => ({
+ useLibrary: () => ({ openLibrary: vi.fn(), upsertCachedNote })
+}))
+
+vi.mock('../artifact/artifact-context', () => ({
+ useArtifact: () => ({ close: vi.fn() })
+}))
+
+vi.mock('../message', () => ({
+ MarkdownMessage: ({ message }: { message: string }) => <div>{message}</div>
+}))
+
+const draft =
+ '````draft\ntitle: Boards\n\n# Cutting boards\n\nOil monthly.\n````'
+const store = {
+ messages: [
+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: draft }] }
+ ],
+ isStreaming: false,
+ quote: null,
+ chatId: 'chat-1',
+ isGuest: false,
+ isCloudDeployment: false,
+ libraryAvailable: true
+}
+vi.mock('../draft/draft-store', () => ({
+ useDraftStore: () => store,
+ useLiveDraftBlock: vi.fn(() => null)
+}))
+
+describe('DraftPanel save', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ test('saves the shown version as a note', async () => {
+ const note = { id: 'n1' }
+ vi.mocked(saveNote).mockResolvedValue({ success: true, note } as never)
+
+ render(<DraftPanel />)
+ fireEvent.click(screen.getByRole('button', { name: 'Save to library' }))
+
+ await waitFor(() => expect(upsertCachedNote).toHaveBeenCalledWith(note))
+ expect(saveNote).toHaveBeenCalledWith({
+ title: 'Cutting boards',
+ content: '# Cutting boards\n\nOil monthly.',
+ chatId: 'chat-1',
+ sourceMessageId: 'a1'
+ })
+ expect(captureClient).toHaveBeenCalledWith(
+ 'note_saved',
+ expect.objectContaining({ source: 'draft_panel', chatId: 'chat-1' })
+ )
+ })
+
+ test('is disabled while a draft is streaming', () => {
+ vi.mocked(useLiveDraftBlock).mockReturnValueOnce({
+ title: 'Boards',
+ content: '# Cutting',
+ closed: false
+ })
+
+ render(<DraftPanel />)
+
+ expect(
+ screen.getByRole('button', { name: 'Save to library' })
+ ).toBeDisabled()
+ })
+})
diff --git a/components/chat.tsx b/components/chat.tsx
index 82e7cc30..10a5266b 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -407,9 +407,22 @@ export function Chat({
messages,
isStreaming: status === 'streaming' || status === 'submitted',
quote: handleQuoteContext,
+ chatId,
+ isGuest,
+ isCloudDeployment,
+ libraryAvailable,
isVisible: () => Boolean(scrollContainerRef.current?.offsetParent)
})
- }, [draftSourceId, messages, status, handleQuoteContext])
+ }, [
+ draftSourceId,
+ messages,
+ status,
+ handleQuoteContext,
+ chatId,
+ isGuest,
+ isCloudDeployment,
+ libraryAvailable
+ ])
useEffect(() => () => unregisterDraftSource(draftSourceId), [draftSourceId])
useEffect(() => {
diff --git a/components/draft/draft-panel.tsx b/components/draft/draft-panel.tsx
index 8b3e4b60..c1151908 100644
--- a/components/draft/draft-panel.tsx
+++ b/components/draft/draft-panel.tsx
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import {
+ IconBookmark as Bookmark,
IconChevronLeft as ChevronLeft,
IconChevronRight as ChevronRight,
IconCopy as Copy,
@@ -10,11 +11,15 @@ import {
} from '@tabler/icons-react'
import { toast } from 'sonner'
+import { saveNote } from '@/lib/actions/notes'
+import { captureClient } from '@/lib/analytics/posthog-client'
import { buildDraftVersions, draftDisplayTitle } from '@/lib/draft/draft'
import { Button } from '@/components/ui/button'
import { useArtifact } from '../artifact/artifact-context'
+import { useLibrary } from '../library/library-context'
+import { SaveNoteAuthDialog } from '../library/save-note-auth-dialog'
import { MarkdownMessage } from '../message'
import { useDraftStore, useLiveDraftBlock } from './draft-store'
@@ -22,8 +27,18 @@ import { useDraftStore, useLiveDraftBlock } from './draft-store'
type SelectionAnchor = { text: string; top: number; left: number }
export function DraftPanel() {
- const { messages, quote } = useDraftStore()
+ const {
+ messages,
+ quote,
+ chatId,
+ isGuest = false,
+ isCloudDeployment = false,
+ libraryAvailable = false
+ } = useDraftStore()
const { close } = useArtifact()
+ const { openLibrary, upsertCachedNote } = useLibrary()
+ const [isSaving, setIsSaving] = useState(false)
+ const [authPromptOpen, setAuthPromptOpen] = useState(false)
const versions = useMemo(() => buildDraftVersions(messages), [messages])
// A draft block still streaming in the latest answer, shown live.
@@ -105,6 +120,79 @@ export function DraftPanel() {
}
}
+ const showSaveButton = libraryAvailable && (!isGuest || isCloudDeployment)
+
+ // Mirrors the answer Save button in message-actions.tsx, saving the
+ // version shown in the panel.
+ const save = async () => {
+ if (isSaving || live || !shown) return
+
+ captureClient('note_save_clicked', {
+ source: 'draft_panel',
+ chatId,
+ chars: content.length,
+ isGuest,
+ isCloudDeployment
+ })
+
+ if (isGuest) {
+ setAuthPromptOpen(true)
+ captureClient('library_auth_prompt_opened', {
+ source: 'draft_panel',
+ chatId
+ })
+ return
+ }
+
+ setIsSaving(true)
+ try {
+ const result = await saveNote({
+ title,
+ content,
+ chatId,
+ sourceMessageId: shown.messageId
+ })
+
+ if (!result.success) {
+ captureClient('note_save_failed', {
+ source: 'draft_panel',
+ chatId,
+ reason: result.error ?? 'unknown'
+ })
+ toast.error(result.error ?? 'Failed to save note')
+ return
+ }
+
+ if (result.note) {
+ upsertCachedNote(result.note)
+ }
+ captureClient('note_saved', {
+ source: 'draft_panel',
+ 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: 'draft_panel',
+ chatId,
+ reason: 'exception'
+ })
+ toast.error('Failed to save note')
+ } finally {
+ setIsSaving(false)
+ }
+ }
+
const status = live
? `Writing… ${content.length.toLocaleString()} characters`
: shown!.interrupted
@@ -133,6 +221,18 @@ export function DraftPanel() {
>
<Copy className="size-4" />
</Button>
+ {showSaveButton && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="-my-2"
+ aria-label="Save to library"
+ disabled={!!live || isSaving}
+ onClick={save}
+ >
+ <Bookmark className="size-4" />
+ </Button>
+ )}
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
{!live && versions.length > 1 && (
@@ -200,6 +300,13 @@ export function DraftPanel() {
)}
<MarkdownMessage message={content} drafts={false} />
</div>
+
+ <SaveNoteAuthDialog
+ open={authPromptOpen}
+ onOpenChange={setAuthPromptOpen}
+ source="draft_panel"
+ chatId={chatId}
+ />
</div>
)
}
diff --git a/components/draft/draft-store.ts b/components/draft/draft-store.ts
index 05c9b540..fe92a9e7 100644
--- a/components/draft/draft-store.ts
+++ b/components/draft/draft-store.ts
@@ -13,6 +13,11 @@ type DraftSource = {
messages: UIMessage[]
isStreaming: boolean
quote: ((text: string) => void) | null
+ // What the panel's Save button needs, matching the answer Save button.
+ chatId?: string
+ isGuest?: boolean
+ isCloudDeployment?: boolean
+ libraryAvailable?: boolean
}
type Registration = DraftSource & { isVisible: () => boolean }
diff --git a/components/library/save-note-auth-dialog.tsx b/components/library/save-note-auth-dialog.tsx
new file mode 100644
index 00000000..a7ae4556
--- /dev/null
+++ b/components/library/save-note-auth-dialog.tsx
@@ -0,0 +1,78 @@
+'use client'
+
+import Link from 'next/link'
+
+import { IconBookmark as Bookmark } from '@tabler/icons-react'
+
+import { captureClient } from '@/lib/analytics/posthog-client'
+
+import { Button } from '../ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '../ui/dialog'
+
+export function SaveNoteAuthDialog({
+ open,
+ onOpenChange,
+ source,
+ chatId
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ source: string
+ chatId?: string
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <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,
+ 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,
+ target: 'sign_in',
+ chatId
+ })
+ }
+ >
+ Sign In
+ </Link>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/message-actions.tsx b/components/message-actions.tsx
index 3d2338d6..f4d08df8 100644
--- a/components/message-actions.tsx
+++ b/components/message-actions.tsx
@@ -1,7 +1,6 @@
'use client'
import { useMemo, useState } from 'react'
-import Link from 'next/link'
import { UseChatHelpers } from '@ai-sdk/react'
import {
@@ -22,15 +21,8 @@ import { cn } from '@/lib/utils'
import { processCitations } from '@/lib/utils/citation'
import { useLibrary } from './library/library-context'
+import { SaveNoteAuthDialog } from './library/save-note-auth-dialog'
import { Button } from './ui/button'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle
-} from './ui/dialog'
import {
Tooltip,
TooltipContent,
@@ -299,52 +291,12 @@ export function MessageActions({
</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>
- <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>
+ <SaveNoteAuthDialog
+ open={authPromptOpen}
+ onOpenChange={setAuthPromptOpen}
+ source="save_button"
+ chatId={chatId}
+ />
</>
)
}