An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat(draft): write and edit drafts in a side panel (#1091)
Yoshiki Miura5b9fbd857c4e
diff --git a/components/artifact/artifact-content.tsx b/components/artifact/artifact-content.tsxindex 4ef9b537..d02259a2 100644--- a/components/artifact/artifact-content.tsx+++ b/components/artifact/artifact-content.tsx@@ -2,6 +2,8 @@import { Part, ToolPart } from '@/lib/types/ai'+import { DraftPanel } from '../draft/draft-panel'+import { ReasoningContent } from './reasoning-content'import { TodoInvocationContent } from './todo-invocation-content'import { ToolInvocationContent } from './tool-invocation-content'@@ -26,6 +28,8 @@ export function ArtifactContent({ part }: { part: Part | null }) {return nullcase 'reasoning':return <ReasoningContent reasoning={part.text} />+ case 'draft':+ return <DraftPanel />default:return (<div className="p-4">Details for this part type are not available</div>diff --git a/components/chat.tsx b/components/chat.tsxindex 06328747..82e7cc30 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -1,6 +1,6 @@'use client'-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'import { useRouter } from 'next/navigation'import { useChat } from '@ai-sdk/react'@@ -36,6 +36,7 @@ import { getTextFromParts } from '@/lib/utils/message-utils'import { useFileDropzone } from '@/hooks/use-file-dropzone'+import { registerDraftSource, unregisterDraftSource } from './draft/draft-store'import { ChatMessages } from './chat-messages'import { ChatPanel } from './chat-panel'import { DragOverlay } from './drag-overlay'@@ -397,6 +398,20 @@ export function Chat({messagesRef.current = messages}, [messages])+ // The draft panel sits outside this component, so register what it reads.+ // The layout mounts a desktop and a mobile Chat; the store hands the panel+ // whichever one is visible.+ const draftSourceId = useId()+ useEffect(() => {+ registerDraftSource(draftSourceId, {+ messages,+ isStreaming: status === 'streaming' || status === 'submitted',+ quote: handleQuoteContext,+ isVisible: () => Boolean(scrollContainerRef.current?.offsetParent)+ })+ }, [draftSourceId, messages, status, handleQuoteContext])+ useEffect(() => () => unregisterDraftSource(draftSourceId), [draftSourceId])+useEffect(() => {const handleCopyMessage = (e: Event) => {if (e.defaultPrevented) returndiff --git a/components/draft/draft-card.tsx b/components/draft/draft-card.tsxnew file mode 100644index 00000000..d52721ec--- /dev/null+++ b/components/draft/draft-card.tsx@@ -0,0 +1,120 @@+'use client'++import { useEffect, useRef } from 'react'++import {+ IconFileText as FileText,+ IconLoader2 as Loader+} from '@tabler/icons-react'++import { draftDisplayTitle, parseDraftFenceBody } from '@/lib/draft/draft'+import type { ToolPart } from '@/lib/types/ai'++import { useArtifact } from '../artifact/artifact-context'++import { useLiveDraftBlock } from './draft-store'++function useOpenDraft() {+ const { open } = useArtifact()+ return () => open({ type: 'draft' })+}++function CardShell({+ title,+ detail,+ busy,+ onOpen+}: {+ title: string+ detail: string+ busy: boolean+ onOpen: () => void+}) {+ return (+ <button+ type="button"+ onClick={onOpen}+ className="not-prose my-3 flex w-full items-center gap-3 rounded-lg border bg-card p-3 text-left transition-colors hover:bg-muted/50"+ >+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted">+ {busy ? (+ <Loader className="size-4 animate-spin text-muted-foreground" />+ ) : (+ <FileText className="size-4 text-muted-foreground" />+ )}+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium">{title}</span>+ <span className="text-xs text-muted-foreground">{detail}</span>+ </span>+ <span className="ml-auto shrink-0 text-xs text-muted-foreground">+ Open+ </span>+ </button>+ )+}++/** Stands in for a ````draft block in the answer; the content lives in the panel. */+export function DraftFenceCard({ code }: { code: string }) {+ const openDraft = useOpenDraft()+ const live = useLiveDraftBlock()+ const draft = parseDraftFenceBody(code)+ const { content } = draft+ const title = draftDisplayTitle(draft)+ // Streamdown does not flag a four-backtick fence as incomplete, so the+ // streaming state comes from the latest answer's still-open block.+ const writing =+ live !== null && live.content.startsWith(content.slice(0, 200))+ const autoOpened = useRef(false)++ // Open the panel as a draft starts streaming, not when history loads.+ useEffect(() => {+ if (writing && !autoOpened.current) {+ autoOpened.current = true+ openDraft()+ }+ }, [writing, openDraft])++ return (+ <CardShell+ title={title || 'Draft'}+ detail={+ writing+ ? `Writing… ${content.length.toLocaleString()} characters`+ : `${content.length.toLocaleString()} characters`+ }+ busy={writing}+ onOpen={openDraft}+ />+ )+}++type EditOutput = { applied?: number; failed?: unknown[]; message?: string }++/** Shown in the answer where the model edited the draft. */+export function DraftEditNotice({ part }: { part: ToolPart }) {+ const openDraft = useOpenDraft()+ const output = part.output as EditOutput | undefined+ const busy =+ part.state === 'input-streaming' || part.state === 'input-available'++ let detail = 'Editing…'+ if (part.state === 'output-error') detail = 'The edit failed'+ else if (part.state === 'output-available') {+ const applied = output?.applied ?? 0+ const failed = output?.failed?.length ?? 0+ detail =+ applied === 0+ ? 'No changes applied'+ : `${applied} change${applied === 1 ? '' : 's'}${failed ? `, ${failed} skipped` : ''}`+ }++ return (+ <CardShell+ title="Edited the draft"+ detail={detail}+ busy={busy}+ onOpen={openDraft}+ />+ )+}diff --git a/components/draft/draft-panel.tsx b/components/draft/draft-panel.tsxnew file mode 100644index 00000000..8b3e4b60--- /dev/null+++ b/components/draft/draft-panel.tsx@@ -0,0 +1,205 @@+'use client'++import { useEffect, useMemo, useRef, useState } from 'react'++import {+ IconChevronLeft as ChevronLeft,+ IconChevronRight as ChevronRight,+ IconCopy as Copy,+ IconPencil as Pencil+} from '@tabler/icons-react'+import { toast } from 'sonner'++import { buildDraftVersions, draftDisplayTitle } from '@/lib/draft/draft'++import { Button } from '@/components/ui/button'++import { useArtifact } from '../artifact/artifact-context'+import { MarkdownMessage } from '../message'++import { useDraftStore, useLiveDraftBlock } from './draft-store'++type SelectionAnchor = { text: string; top: number; left: number }++export function DraftPanel() {+ const { messages, quote } = useDraftStore()+ const { close } = useArtifact()+ const versions = useMemo(() => buildDraftVersions(messages), [messages])++ // A draft block still streaming in the latest answer, shown live.+ const live = useLiveDraftBlock()++ // A picked version is remembered with the chat and the count it was picked+ // at, so a new version or another chat switches the panel back to the latest.+ const chatKey = versions[0]?.messageId+ const [picked, setPicked] = useState<{+ index: number+ total: number+ chatKey?: string+ }>()+ const index =+ picked && picked.total === versions.length && picked.chatKey === chatKey+ ? picked.index+ : null+ const setIndex = (next: number | null) =>+ setPicked(+ next === null+ ? undefined+ : { index: next, total: versions.length, chatKey }+ )++ const shown = index === null ? versions.at(-1) : versions[index]+ const position = index === null ? versions.length - 1 : index++ const bodyRef = useRef<HTMLDivElement>(null)+ const [anchor, setAnchor] = useState<SelectionAnchor | null>(null)++ // selectionchange covers touch long-press selection, which fires no+ // mouseup. Clearing waits briefly: tapping the button collapses the+ // selection on touch devices before the tap lands.+ useEffect(() => {+ let clearTimer: ReturnType<typeof setTimeout> | undefined+ const update = () => {+ const selection = window.getSelection()+ const text = selection?.toString().trim()+ const body = bodyRef.current+ const range = selection?.rangeCount ? selection.getRangeAt(0) : null+ if (!text || !range || !body?.contains(range.commonAncestorContainer)) {+ clearTimeout(clearTimer)+ clearTimer = setTimeout(() => setAnchor(null), 300)+ return+ }+ clearTimeout(clearTimer)+ const rect = range.getBoundingClientRect()+ const bodyRect = body.getBoundingClientRect()+ setAnchor({+ text,+ top: rect.top - bodyRect.top - 36,+ left: Math.max(0, rect.left - bodyRect.left)+ })+ }+ document.addEventListener('selectionchange', update)+ return () => {+ clearTimeout(clearTimer)+ document.removeEventListener('selectionchange', update)+ }+ }, [])++ if (!live && !shown) {+ return (+ <p className="text-sm text-muted-foreground">+ No draft in this chat yet.+ </p>+ )+ }++ const title = draftDisplayTitle(live ?? shown!)+ const content = live ? live.content : shown!.content++ const copy = async () => {+ try {+ await navigator.clipboard.writeText(content)+ toast.success('Draft copied')+ } catch {+ toast.error('Could not copy the draft')+ }+ }++ const status = live+ ? `Writing… ${content.length.toLocaleString()} characters`+ : shown!.interrupted+ ? `Interrupted · ${content.length.toLocaleString()} characters`+ : shown!.kind === 'edit'+ ? `Edited · ${shown!.applied} change${shown!.applied === 1 ? '' : 's'}`+ : `${content.length.toLocaleString()} characters`++ return (+ <div className="flex flex-col">+ {/* Panel chrome, kept visually apart from the document below it. */}+ <div className="sticky -top-4 z-20 -mx-4 -mt-4 mb-4 flex flex-col gap-1.5 border-b bg-muted px-4 py-2">+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-sm font-medium">+ {title || 'Draft'}+ </span>+ <Button+ variant="ghost"+ size="icon"+ // Same size as the panel's close button so the two icons line+ // up; the negative margin keeps the row compact.+ className="-my-2"+ aria-label="Copy draft"+ disabled={!!live}+ onClick={copy}+ >+ <Copy 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 && (+ <span className="flex items-center gap-0.5">+ <Button+ variant="ghost"+ size="icon"+ className="size-5"+ aria-label="Previous version"+ disabled={position <= 0}+ onClick={() => setIndex(Math.max(0, position - 1))}+ >+ <ChevronLeft className="size-3.5" />+ </Button>+ <span className="tabular-nums">+ v{position + 1} / {versions.length}+ </span>+ <Button+ variant="ghost"+ size="icon"+ className="size-5"+ aria-label="Next version"+ disabled={position >= versions.length - 1}+ onClick={() =>+ setIndex(+ position + 1 >= versions.length - 1 ? null : position + 1+ )+ }+ >+ <ChevronRight className="size-3.5" />+ </Button>+ </span>+ )}+ <span className="rounded bg-background px-1.5 py-0.5 tabular-nums">+ {status}+ </span>+ {!live && (+ <span className="flex items-center gap-1">+ <Pencil className="size-3" />+ Select text to edit it+ </span>+ )}+ </div>+ </div>++ <div ref={bodyRef} className="relative">+ {anchor && quote && !live && (+ <Button+ size="sm"+ variant="secondary"+ className="absolute z-10 h-7 gap-1 shadow-sm"+ style={{ top: anchor.top, left: anchor.left }}+ onMouseDown={event => event.preventDefault()}+ onClick={() => {+ quote(anchor.text)+ window.getSelection()?.removeAllRanges()+ setAnchor(null)+ // The mobile drawer covers the composer the quote went to.+ if (window.matchMedia('(max-width: 767px)').matches) close()+ }}+ >+ <Pencil className="size-3.5" />+ Edit this+ </Button>+ )}+ <MarkdownMessage message={content} drafts={false} />+ </div>+ </div>+ )+}diff --git a/components/draft/draft-store.ts b/components/draft/draft-store.tsnew file mode 100644index 00000000..05c9b540--- /dev/null+++ b/components/draft/draft-store.ts@@ -0,0 +1,81 @@+'use client'++import { useMemo, useSyncExternalStore } from 'react'++import { type DraftBlock, parseDraftBlocks } from '@/lib/draft/draft'+import type { UIMessage } from '@/lib/types/ai'++// The draft panel lives in the layout-level inspector, outside the chat that+// owns the messages, so each chat registers what the panel needs here. The+// layout mounts a desktop and a mobile chat; the panel reads the visible one,+// chosen when the store is read rather than by which chat wrote last.+type DraftSource = {+ messages: UIMessage[]+ isStreaming: boolean+ quote: ((text: string) => void) | null+}++type Registration = DraftSource & { isVisible: () => boolean }++const EMPTY: DraftSource = { messages: [], isStreaming: false, quote: null }++const sources = new Map<string, Registration>()+const listeners = new Set<() => void>()+let snapshot: DraftSource = EMPTY++function pick(): DraftSource {+ for (const source of sources.values()) {+ if (source.isVisible()) return source+ }+ return EMPTY+}++function emit() {+ const next = pick()+ if (next === snapshot) return+ snapshot = next+ for (const listener of listeners) listener()+}++export function registerDraftSource(id: string, source: Registration) {+ sources.set(id, source)+ emit()+}++export function unregisterDraftSource(id: string) {+ if (!sources.delete(id)) return+ emit()+}++function subscribe(listener: () => void) {+ listeners.add(listener)+ // A resize can swap which chat is visible without either one writing.+ if (listeners.size === 1) window.addEventListener('resize', emit)+ return () => {+ listeners.delete(listener)+ if (listeners.size === 0) window.removeEventListener('resize', emit)+ }+}++export function useDraftStore(): DraftSource {+ return useSyncExternalStore(+ subscribe,+ () => snapshot,+ () => EMPTY+ )+}++/** The draft block still being written in the latest answer, if any. */+export function useLiveDraftBlock(): DraftBlock | null {+ const { messages, isStreaming } = useDraftStore()+ return useMemo(() => {+ const last = messages.at(-1)+ if (!isStreaming || last?.role !== 'assistant') return null+ for (const part of [...(last.parts ?? [])].reverse()) {+ if (part.type !== 'text') continue+ const block = parseDraftBlocks(part.text).at(-1)+ if (block && !block.closed) return block+ }+ return null+ }, [messages, isStreaming])+}diff --git a/components/inspector/inspector-drawer.tsx b/components/inspector/inspector-drawer.tsxindex f3d6d363..857a8699 100644--- a/components/inspector/inspector-drawer.tsx+++ b/components/inspector/inspector-drawer.tsx@@ -34,6 +34,8 @@ export function InspectorDrawer() {return 'Thoughts'case 'text':return 'Text'+ case 'draft':+ return 'Draft'default:return 'Content'}diff --git a/components/inspector/inspector-panel.tsx b/components/inspector/inspector-panel.tsxindex b824c95c..96293608 100644--- a/components/inspector/inspector-panel.tsx+++ b/components/inspector/inspector-panel.tsx@@ -2,6 +2,7 @@import {IconBulb as LightbulbIcon,+ IconFileText as FileText,IconListCheck as ListTodo,IconMessage as MessageSquare,IconSearch as Search,@@ -40,6 +41,11 @@ export function InspectorPanel() {icon: <LightbulbIcon size={18} />,title: 'Thoughts'}+ case 'draft':+ return {+ icon: <FileText size={18} />,+ title: 'Draft'+ }case 'text':return {icon: <MessageSquare size={18} />,diff --git a/components/message.tsx b/components/message.tsxindex e8247886..812f5da9 100644--- a/components/message.tsx+++ b/components/message.tsx@@ -9,6 +9,7 @@ import {type StreamdownProps} from 'streamdown'+import { normalizeDraftFences } from '@/lib/draft/draft'import { mergeStreamdownSpecRenderer } from '@/lib/render/streamdown-spec'import type { SearchResultItem } from '@/lib/types'import { cn } from '@/lib/utils'@@ -28,21 +29,27 @@ const customComponents = {export function MarkdownMessage({message,className,- citationMaps+ citationMaps,+ drafts = true}: {message: stringclassName?: stringcitationMaps?: Record<string, Record<number, SearchResultItem>>+ /** False inside the draft panel, where a draft fence is an example to show. */+ drafts?: boolean}) {// Process citations to replace [number](#toolCallId) with [number](actual-url)- const processedMessage = processCitations(message || '', citationMaps || {})+ const processedMessage = processCitations(+ drafts ? normalizeDraftFences(message || '') : message || '',+ citationMaps || {}+ )const streamdownProps = useMemo<Partial<StreamdownProps>>(() => ({mode: 'streaming' as const,- plugins: mergeStreamdownSpecRenderer({ math })+ plugins: mergeStreamdownSpecRenderer({ math }, { drafts })}),- []+ [drafts])return (diff --git a/components/render-message.tsx b/components/render-message.tsxindex e1b3d0df..4416de70 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -2,6 +2,7 @@ import { UseChatHelpers } from '@ai-sdk/react'import type { SearchResultItem } from '@/lib/types'import type {+ ToolPart,UIDataTypes,UIMessage,UIMessageMetadata,@@ -9,6 +10,7 @@ import type {} from '@/lib/types/ai'import type { DynamicToolPart } from '@/lib/types/dynamic-tools'+import { DraftEditNotice } from './draft/draft-card'import { AnswerSection } from './answer-section'import { DynamicToolDisplay } from './dynamic-tool-display'import ResearchProcessSection from './research-process-section'@@ -188,6 +190,14 @@ export function RenderMessage({onQuoteContext={onQuoteContext}/>)+ } else if (part.type === 'tool-editDraft') {+ flushBuffer(`seg-${index}`)+ elements.push(+ <DraftEditNotice+ key={`${messageId}-draft-edit-${index}`}+ part={part as ToolPart}+ />+ )} else if (part.type === 'reasoning' || part.type?.startsWith?.('tool-')) {buffer.push(part)} else if (part.type === 'dynamic-tool') {diff --git a/lib/agents/prompts/search-mode-prompts.ts b/lib/agents/prompts/search-mode-prompts.tsindex 37249133..dfb0a259 100644--- a/lib/agents/prompts/search-mode-prompts.ts+++ b/lib/agents/prompts/search-mode-prompts.ts@@ -1,3 +1,4 @@+import { getDraftPrompt } from '@/lib/draft/prompt'import {getImageSpecPrompt,getRelatedQuestionsSpecPrompt,@@ -172,6 +173,8 @@ Example approach:End with a synthesizing conclusion that ties the main points together into a clear overall picture.+${getDraftPrompt()}+${getImageSpecPrompt()}${getSourceCardsSpecPrompt()}@@ -349,6 +352,8 @@ Flexible example:Conclude with a brief synthesis that ties together the main insights into a clear overall understanding.+${getDraftPrompt()}+${getImageSpecPrompt()}${getSourceCardsSpecPrompt()}diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex 8cf6f8a4..8a3337e3 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -1,11 +1,13 @@import { isStepCount, tool, ToolLoopAgent } from 'ai'+import type { DraftVersion } from '@/lib/draft/draft'import type {ResearcherRuntimeContext,ResearcherTools} from '@/lib/types/agent'import { type Model } from '@/lib/types/models'+import { createDraftTools } from '../tools/draft'import { createFetchTool } from '../tools/fetch'import { createQuestionTool } from '../tools/question'import { createSearchTool } from '../tools/search'@@ -76,13 +78,15 @@ export function createResearcher({modelConfig,chatId,searchMode = 'adaptive',- citationLabelSeed+ citationLabelSeed,+ currentDraft = null}: {model: stringmodelConfig?: ModelchatId?: stringsearchMode?: SearchModecitationLabelSeed?: number+ currentDraft?: DraftVersion | null}) {try {// Date only: a second-precision timestamp sits at the head of the prompt@@ -97,6 +101,7 @@ export function createResearcher({const fetchTool = createFetchTool({ labelAllocator })const askQuestionTool = createQuestionTool(model)const todoTools = createTodoTools()+ const draftTools = createDraftTools(currentDraft)let systemPrompt: stringlet activeToolsList: (keyof ResearcherTools)[] = []@@ -107,10 +112,10 @@ export function createResearcher({switch (searchMode) {case 'quick':console.log(- '[Researcher] Quick mode: maxSteps=20, tools=[search, fetch]'+ '[Researcher] Quick mode: maxSteps=20, tools=[search, fetch, editDraft]')systemPrompt = QUICK_MODE_PROMPT- activeToolsList = ['search', 'fetch']+ activeToolsList = ['search', 'fetch', 'editDraft']maxSteps = 20searchTool = wrapSearchToolForQuickMode(originalSearchTool)break@@ -118,7 +123,7 @@ export function createResearcher({case 'adaptive':default:systemPrompt = getAdaptiveModePrompt()- activeToolsList = ['search', 'fetch', 'todoWrite']+ activeToolsList = ['search', 'fetch', 'todoWrite', 'editDraft']console.log(`[Researcher] Adaptive mode: maxSteps=50, tools=[${activeToolsList.join(', ')}]`)@@ -132,7 +137,8 @@ export function createResearcher({search: searchTool,fetch: fetchTool,askQuestion: askQuestionTool,- ...todoTools+ ...todoTools,+ ...draftTools} as ResearcherToolsconst providerOptions =diff --git a/lib/draft/__tests__/draft.test.ts b/lib/draft/__tests__/draft.test.tsnew file mode 100644index 00000000..cd797c91--- /dev/null+++ b/lib/draft/__tests__/draft.test.ts@@ -0,0 +1,480 @@+import { describe, expect, test } from 'vitest'++import {+ applyDraftChange,+ applyDraftEdits,+ buildDraftVersions,+ compactDraftBlocks,+ currentDraftVersion,+ formatCurrentDraft,+ normalizeDraftFences,+ parseDraftBlocks,+ parseDraftFenceBody+} from '../draft'++const BLOCK = [+ 'Here is your draft.',+ '',+ '````draft',+ 'title: Cutting boards',+ '',+ '# Cutting boards',+ '',+ '```text',+ 'oil monthly',+ '```',+ '',+ 'End.',+ '````',+ '',+ 'Want changes?'+].join('\n')++describe('parseDraftBlocks', () => {+ test('reads title and content, keeping inner code fences', () => {+ const [block] = parseDraftBlocks(BLOCK)+ expect(block.closed).toBe(true)+ expect(block.title).toBe('Cutting boards')+ expect(block.content).toContain('```text\noil monthly\n```')+ expect(block.content.endsWith('End.')).toBe(true)+ })++ test('reports a streaming block as open', () => {+ const [block] = parseDraftBlocks(+ 'Intro\n\n````draft\ntitle: X\n\n# Partial'+ )+ expect(block).toEqual({ title: 'X', content: '# Partial', closed: false })+ })++ test('returns nothing for text without a draft', () => {+ expect(parseDraftBlocks('```ts\nconst a = 1\n```')).toEqual([])+ })+})++describe('applyDraftEdits', () => {+ test('applies unique edits in order', () => {+ const result = applyDraftEdits('alpha beta gamma', [+ { find: 'beta', replace: 'BETA' },+ { find: 'gamma', replace: 'delta' }+ ])+ expect(result).toEqual({+ content: 'alpha BETA delta',+ applied: 2,+ failed: []+ })+ })++ test('skips missing and ambiguous finds', () => {+ const result = applyDraftEdits('a b a', [+ { find: 'a', replace: 'x' },+ { find: 'zzz', replace: 'y' },+ { find: 'b', replace: 'B' }+ ])+ expect(result.content).toBe('a B a')+ expect(result.failed.map(f => f.reason)).toEqual([+ 'not unique',+ 'not found'+ ])+ })+})++describe('buildDraftVersions', () => {+ test('tracks writes and completed edits across messages', () => {+ const versions = buildDraftVersions([+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'write it' }] },+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: BLOCK }] },+ {+ id: 'a2',+ role: 'assistant',+ parts: [+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { edits: [{ find: 'End.', replace: 'The end.' }] },+ output: {}+ },+ {+ type: 'tool-editDraft',+ state: 'input-streaming',+ input: { edits: [{ find: 'The end.', replace: 'ignored' }] }+ }+ ]+ }+ ])++ expect(versions.map(v => [v.version, v.kind])).toEqual([+ [1, 'write'],+ [2, 'edit']+ ])+ expect(versions[1].content.endsWith('The end.')).toBe(true)+ expect(versions[1].title).toBe('Cutting boards')+ })++ test('keeps a block an answer stopped inside as an interrupted version', () => {+ const versions = buildDraftVersions([+ {+ id: 'a1',+ role: 'assistant',+ parts: [{ type: 'text', text: '````draft\ntitle: Note\n\nHalf a sent' }]+ }+ ])+ expect(versions).toHaveLength(1)+ expect(versions[0]).toMatchObject({+ content: 'Half a sent',+ interrupted: true+ })+ })++ test('drops an interrupted block with no text', () => {+ const versions = buildDraftVersions([+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: BLOCK }] },+ {+ id: 'a2',+ role: 'assistant',+ parts: [{ type: 'text', text: '````draft\ntitle: Revision\n\n' }]+ }+ ])+ expect(versions).toHaveLength(1)+ })++ test('edits the last completed version, not an interrupted one', () => {+ const versions = buildDraftVersions([+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: BLOCK }] },+ {+ id: 'a2',+ role: 'assistant',+ parts: [{ type: 'text', text: '````draft\ntitle: Revision\n\nPart' }]+ },+ {+ id: 'a3',+ role: 'assistant',+ parts: [+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { edits: [{ find: 'End.', replace: 'The end.' }] },+ output: { applied: 1, failed: [] }+ }+ ]+ }+ ])+ expect(versions.map(v => v.kind)).toEqual(['write', 'write', 'edit'])+ expect(versions[2].title).toBe('Cutting boards')+ expect(currentDraftVersion(versions.slice(0, 2))?.version).toBe(1)+ })++ test('replays a title change', () => {+ const versions = buildDraftVersions([+ {+ id: 'a1',+ role: 'assistant',+ parts: [{ type: 'text', text: '````draft\ntitle: Old\n\nHi.\n````' }]+ },+ {+ id: 'a2',+ role: 'assistant',+ parts: [+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { title: 'New' },+ output: { applied: 1, failed: [] }+ }+ ]+ }+ ])+ expect(versions.at(-1)).toMatchObject({ title: 'New', content: 'Hi.' })+ })++ test('skips an edit the tool rejected', () => {+ const versions = buildDraftVersions([+ { id: 'a1', role: 'assistant', parts: [{ type: 'text', text: BLOCK }] },+ {+ id: 'a2',+ role: 'assistant',+ parts: [+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { edits: [{ find: 'End.', replace: 'The end.' }] },+ output: { applied: 0, failed: [] }+ }+ ]+ }+ ])+ expect(versions).toHaveLength(1)+ })++ test('skips an edit after a block written in the same answer', () => {+ const versions = buildDraftVersions([+ {+ id: 'a1',+ role: 'assistant',+ parts: [+ { type: 'text', text: BLOCK },+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { edits: [{ find: 'End.', replace: 'The end.' }] },+ output: { applied: 1, failed: [] }+ }+ ]+ }+ ])+ expect(versions.map(v => v.kind)).toEqual(['write'])+ })++ test('ignores an edit before any draft exists', () => {+ expect(+ buildDraftVersions([+ {+ id: 'a1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-editDraft',+ state: 'output-available',+ input: { edits: [{ find: 'x', replace: 'y' }] }+ }+ ]+ }+ ])+ ).toEqual([])+ })+})++describe('applyDraftChange', () => {+ test('counts a new title as one change and ignores the same title', () => {+ const draft = { title: 'Old', content: 'Hi.' }+ expect(applyDraftChange(draft, { title: 'New' }).applied).toBe(1)+ expect(applyDraftChange(draft, { title: 'Old' }).applied).toBe(0)+ })+})++describe('compactDraftBlocks', () => {+ test('stubs a block an answer stopped inside', () => {+ const out = compactDraftBlocks('Here.\n\n````draft\ntitle: Note\n\nHalf')+ expect(out).toBe(+ 'Here.\n\n[Draft "Note" written here (4 characters). The current version is attached to the latest user message.]'+ )+ })++ test('replaces closed blocks with a stub and keeps the rest', () => {+ const out = compactDraftBlocks(BLOCK)+ expect(out).not.toContain('````draft')+ expect(out).toContain('[Draft "Cutting boards" written here')+ expect(out.startsWith('Here is your draft.')).toBe(true)+ expect(out.endsWith('Want changes?')).toBe(true)+ })++ test('leaves text without a draft untouched', () => {+ const text = 'Plain answer.'+ expect(compactDraftBlocks(text)).toBe(text)+ })+})++describe('formatCurrentDraft', () => {+ test('wraps the content with title and version', () => {+ const text = formatCurrentDraft({+ version: 2,+ title: 'A "quoted" title',+ content: 'Body',+ kind: 'edit',+ messageId: 'a1'+ })+ expect(text).toBe(+ `<current_draft title="A 'quoted' title" version="2">\nBody\n</current_draft>`+ )+ })+})++describe('normalizeDraftFences', () => {+ test('closes a short-closed draft with four backticks and keeps the rest', () => {+ const text = '````draft\ntitle: A\n\nBody\n```\n\nWant changes?'+ expect(normalizeDraftFences(text)).toBe(+ '````draft\ntitle: A\n\nBody\n````\n\nWant changes?'+ )+ })++ test('leaves a correctly closed draft alone', () => {+ const text = '````draft\ntitle: A\n\nBody\n````\nAfter.'+ expect(normalizeDraftFences(text)).toBe(text)+ })+})++describe('three-backtick opener', () => {+ test('reads a block opened and closed with three backticks', () => {+ const text = '```draft\ntitle: Post\n\nJoin us!\n```'+ expect(parseDraftBlocks(text)).toEqual([+ { title: 'Post', content: 'Join us!', closed: true }+ ])+ expect(compactDraftBlocks(text)).toContain('[Draft "Post" written here')+ })++ test('accepts a longer close', () => {+ expect(parseDraftBlocks('```draft\ntitle: Post\n\nHi\n````')[0]).toEqual({+ title: 'Post',+ content: 'Hi',+ closed: true+ })+ })++ test('leaves it open until the bare fence arrives', () => {+ expect(parseDraftBlocks('```draft\ntitle: Post\n\nJoin')[0].closed).toBe(+ false+ )+ })+})++describe('three-backtick close', () => {+ test('closes when a sentence follows on the next line', () => {+ const [block] = parseDraftBlocks(+ '````draft\ntitle: Note\n\nHello\n```\nWant changes?'+ )+ expect(block).toMatchObject({ content: 'Hello', closed: true })+ })++ test('stops at a next opener with trailing spaces', () => {+ const text =+ '````draft\ntitle: A\n\nOne\n```\n\n````draft \ntitle: B\n\nTwo\n````'+ expect(parseDraftBlocks(text).map(b => [b.title, b.content])).toEqual([+ ['A', 'One'],+ ['B', 'Two']+ ])+ })++ test('keeps a three-backtick draft example inside a draft', () => {+ const text = [+ '````draft',+ 'title: Guide',+ '',+ 'Example:',+ '```draft',+ 'title: Inner',+ '```',+ 'End.',+ '````'+ ].join('\n')+ const blocks = parseDraftBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].closed).toBe(true)+ expect(blocks[0].content).toContain('End.')+ })++ test('stops at the draft close when a spec fence follows', () => {+ const text = [+ '````draft',+ 'title: Note',+ '',+ 'Body.',+ '```',+ '',+ 'Related:',+ '```spec',+ '{"op":"add"}',+ '```'+ ].join('\n')+ const [block] = parseDraftBlocks(text)+ expect(block).toMatchObject({ content: 'Body.', closed: true })+ expect(compactDraftBlocks(text)).toContain('```spec')+ })++ test('keeps an unlabeled code block inside the draft', () => {+ const text = [+ '````draft',+ 'title: Readme',+ '',+ 'Run:',+ '```',+ 'npm start',+ '```',+ 'Done.',+ '```',+ '',+ 'Related:',+ '```spec',+ '{"op":"add"}',+ '```'+ ].join('\n')+ const [block] = parseDraftBlocks(text)+ expect(block.closed).toBe(true)+ expect(block.content).toBe('Run:\n```\nnpm start\n```\nDone.')+ })++ test('leaves a block open when it stopped inside an unlabeled code block', () => {+ const text =+ '````draft\ntitle: Setup\n\nRun this:\n```\nnpm install\nnpm start'+ const [block] = parseDraftBlocks(text)+ expect(block.closed).toBe(false)+ expect(block.content).toContain('npm start')+ })++ test('leaves a block open while its unlabeled code block streams', () => {+ const text = '````draft\ntitle: Readme\n\nRun:\n```\nnpm start\n```'+ expect(parseDraftBlocks(text)[0].closed).toBe(false)+ })++ test('does not take the next draft opener as a close', () => {+ const text =+ '````draft\ntitle: A\n\nOne.\n```\n\n````draft\ntitle: B\n\nTwo.\n````'+ expect(parseDraftBlocks(text).map(b => [b.title, b.content])).toEqual([+ ['A', 'One.'],+ ['B', 'Two.']+ ])+ })++ test('closes a block whose close has three backticks', () => {+ const text = '````draft\ntitle: T\n\nBody\n```\n\nAfter.'+ const [block] = parseDraftBlocks(text)+ expect(block).toEqual({ title: 'T', content: 'Body', closed: true })+ })++ test('keeps inner code fences and closes on the unpaired one', () => {+ const text = [+ '````draft',+ 'title: T',+ '',+ 'Intro',+ '```ts',+ 'const a = 1',+ '```',+ 'Outro',+ '```'+ ].join('\n')+ const [block] = parseDraftBlocks(text)+ expect(block.closed).toBe(true)+ expect(block.content).toBe('Intro\n```ts\nconst a = 1\n```\nOutro')+ })++ test('stays open while an inner code fence is only paired so far', () => {+ const text = '````draft\ntitle: T\n\nIntro\n```ts\ncode\n```\nmore'+ expect(parseDraftBlocks(text)[0].closed).toBe(false)+ })++ test('compacts and versions a block closed with three backticks', () => {+ const text = 'Here.\n\n````draft\ntitle: T\n\nBody\n```'+ expect(compactDraftBlocks(text)).toBe(+ 'Here.\n\n[Draft "T" written here (4 characters). The current version is attached to the latest user message.]'+ )+ expect(+ buildDraftVersions([+ { id: 'a', role: 'assistant', parts: [{ type: 'text', text }] }+ ])+ ).toHaveLength(1)+ })+})++describe('parseDraftFenceBody', () => {+ test('drops a stray three-backtick close and the text after it', () => {+ expect(+ parseDraftFenceBody('title: T\n\nBody\n```\n\nWant changes?\n')+ ).toEqual({ title: 'T', content: 'Body' })+ })++ test('reads a normal fence body', () => {+ expect(parseDraftFenceBody('title: T\n\nBody\n')).toEqual({+ title: 'T',+ content: 'Body'+ })+ })+})diff --git a/lib/draft/draft.ts b/lib/draft/draft.tsnew file mode 100644index 00000000..28a977bf--- /dev/null+++ b/lib/draft/draft.ts@@ -0,0 +1,414 @@+/**+ * Drafts are written as a ````draft fenced block in the answer text and edited+ * with the editDraft tool. Four backticks let the content hold ordinary code+ * fences. The first line inside the block is "title: ...".+ *+ * Everything here is pure: the server rebuilds the current draft from history+ * on each turn, and the client rebuilds the same versions for the panel.+ */++const FENCE_OPEN = '````draft\n'+// Models sometimes open with three backticks; that block ends at the first+// bare fence, as markdown reads it.+const OPENER = /(?:^|\n)(`{3,4})draft[ \t]*\n/g+const NEXT_DRAFT = /\n````draft[ \t]*\n/g+const FENCE_CLOSE = '\n````'+const TITLE_LINE = /^title:[ \t]*(.*)\n?/++export const EDIT_DRAFT_TOOL = 'editDraft'++export type DraftBlock = {+ title: string+ content: string+ /** False while the block is still streaming. */+ closed: boolean+}++export type DraftEdit = { find: string; replace: string }++export type DraftEditFailure = {+ find: string+ reason: 'not found' | 'not unique'+}++export type DraftVersion = {+ version: number+ title: string+ content: string+ kind: 'write' | 'edit'+ messageId: string+ /** Set on edit versions: how many edits applied and which failed. */+ applied?: number+ failed?: DraftEditFailure[]+ /** Set on a write whose block never closed because the answer stopped. */+ interrupted?: boolean+}++function parseBody(body: string): { title: string; content: string } {+ const title = TITLE_LINE.exec(body)+ if (!title) return { title: '', content: body }+ return {+ title: title[1].trim(),+ content: body.slice(title[0].length).replace(/^\n/, '')+ }+}++type BlockLocation = {+ open: number+ bodyStart: number+ bodyEnd: number+ /** Offset just past the closing fence, or the text length while open. */+ end: number+ closed: boolean+ ticks: number+}++const STRICT_CLOSE = /\n````[ \t]*(?=\n|$)/g+const FENCE_LINE = /^`{3,}/+const BARE_THREE = /^```[ \t]*$/+const SENTENCE = /^\p{L}.*[.?!。?!]$/u++/**+ * Whether a line can follow a draft close: nothing yet, a blank line, a+ * labeled block, or a sentence. Code right after a bare fence, which rarely+ * ends like a sentence, is an inner block's content.+ */+function followsLikeClose(line: string | undefined) {+ return (+ line === undefined ||+ !line.trim() ||+ (FENCE_LINE.test(line) && !BARE_THREE.test(line)) ||+ SENTENCE.test(line.trim())+ )+}++/** Whether text after a draft close opens no unlabeled fence, as answers do. */+function opensNoBareFence(lines: string[]) {+ let inFence = false+ for (const line of lines) {+ if (!FENCE_LINE.test(line)) continue+ if (inFence) {+ if (BARE_THREE.test(line)) inFence = false+ } else if (BARE_THREE.test(line)) {+ return false+ } else {+ inFence = true+ }+ }+ return true+}++/**+ * Where a block closes, searched only up to the next draft opener. Models+ * sometimes close a ````draft block with three backticks, which reads the same+ * as an unlabeled code fence opening inside the draft. A bare ``` line outside+ * any inner fence is taken as the close only when what follows it looks like+ * the rest of an answer: a blank line or a labeled block such as spec next,+ * and no unlabeled fence later, which the rest of an inner code block would+ * open.+ */+function findClose(text: string, bodyStart: number, ticks: number) {+ // A three-backtick block cannot hold fences, so it ends at the first bare+ // one; a ```draft line inside it is content, as markdown reads it.+ if (ticks === 3) {+ const bare = /(?:^|\n)`{3,}[ \t]*(?=\n|$)/g+ bare.lastIndex = bodyStart - 1+ const close = bare.exec(text)+ if (!close) return null+ return {+ bodyEnd: Math.max(bodyStart, close.index),+ end: close.index + close[0].length+ }+ }++ // Only a four-backtick opener starts the next draft. A ```draft fence inside+ // this one is an example in its content.+ NEXT_DRAFT.lastIndex = bodyStart - 1+ const next = NEXT_DRAFT.exec(text)+ const limit = next ? next.index : text.length++ STRICT_CLOSE.lastIndex = bodyStart - 1+ const strict = STRICT_CLOSE.exec(text)+ if (strict && strict.index < limit) {+ return { bodyEnd: strict.index, end: strict.index + strict[0].length }+ }++ const lines = text.slice(bodyStart, limit).split('\n')+ let inFence = false+ let offset = bodyStart+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]+ if (FENCE_LINE.test(line)) {+ const bare = BARE_THREE.test(line)+ if (+ !inFence &&+ bare &&+ followsLikeClose(lines[i + 1]) &&+ opensNoBareFence(lines.slice(i + 1))+ ) {+ const bodyEnd = Math.max(bodyStart, offset - 1)+ return { bodyEnd, end: offset + line.length }+ }+ inFence = inFence ? !bare : true+ }+ offset += line.length + 1+ }+ return null+}++function locateDraftBlocks(text: string): BlockLocation[] {+ const blocks: BlockLocation[] = []+ let from = 0+ while (true) {+ OPENER.lastIndex = from+ const opener = OPENER.exec(text)+ if (!opener) break+ const open = opener.index + (opener[0].startsWith('\n') ? 1 : 0)+ const bodyStart = opener.index + opener[0].length+ const close = findClose(text, bodyStart, opener[1].length)+ if (!close) {+ blocks.push({+ open,+ bodyStart,+ bodyEnd: text.length,+ end: text.length,+ closed: false,+ ticks: opener[1].length+ })+ break+ }+ blocks.push({+ open,+ bodyStart,+ ...close,+ closed: true,+ ticks: opener[1].length+ })+ from = close.end+ }+ return blocks+}++/** Every draft block in a text, in order. The last one may still be open. */+export function parseDraftBlocks(text: string): DraftBlock[] {+ return locateDraftBlocks(text).map(block => ({+ ...parseBody(text.slice(block.bodyStart, block.bodyEnd)),+ closed: block.closed+ }))+}++/**+ * Replace each draft block with what the callback returns. An unclosed block+ * runs to the end of the text; in history it is one an answer stopped inside.+ */+export function replaceDraftBlocks(+ text: string,+ replace: (draft: { title: string; content: string }) => string+): string {+ if (!text.includes('```draft')) return text+ let out = ''+ let from = 0+ for (const block of locateDraftBlocks(text)) {+ out +=+ text.slice(from, block.open) ++ replace(parseBody(text.slice(block.bodyStart, block.bodyEnd)))+ from = block.end+ }+ return out + text.slice(from)+}++/**+ * Rewrite a ````draft block closed with three backticks to close with four, so+ * markdown ends the fence where the draft ends and renders the rest of the+ * answer after it instead of inside the fence.+ */+export function normalizeDraftFences(text: string): string {+ if (!text.includes('````draft')) return text+ let out = ''+ let from = 0+ for (const block of locateDraftBlocks(text)) {+ if (!block.closed || block.ticks !== 4) continue+ if (text.startsWith(FENCE_CLOSE, block.bodyEnd)) continue+ out += text.slice(from, block.bodyEnd) + FENCE_CLOSE+ from = block.end+ }+ return out + text.slice(from)+}++/**+ * Parse the inside of a draft fence as a markdown code renderer receives it.+ * A block closed with three backticks reaches the renderer unclosed, with the+ * stray close and any text after it in the body, so it goes through the same+ * close detection as the rest of the text.+ */+export function parseDraftFenceBody(body: string): {+ title: string+ content: string+} {+ const [block] = parseDraftBlocks(FENCE_OPEN + body.replace(/\n$/, ''))+ return block+ ? { title: block.title, content: block.content }+ : parseBody(body)+}++/** The draft's own top-level heading, which edits keep current, else its title. */+export function draftDisplayTitle(draft: { title: string; content: string }) {+ const heading = /^#[ \t]+(.+)$/m.exec(draft.content)+ return heading?.[1].trim() || draft.title+}++/**+ * Apply edits in order. An edit whose find text is missing or appears more+ * than once is skipped and reported, so the server and the client, applying+ * the same edits to the same text, always reach the same result.+ */+export function applyDraftEdits(+ content: string,+ edits: DraftEdit[]+): { content: string; applied: number; failed: DraftEditFailure[] } {+ let out = content+ let applied = 0+ const failed: DraftEditFailure[] = []+ for (const edit of edits) {+ if (!edit.find) {+ failed.push({ find: edit.find, reason: 'not found' })+ continue+ }+ const first = out.indexOf(edit.find)+ if (first < 0) {+ failed.push({ find: edit.find, reason: 'not found' })+ continue+ }+ if (out.indexOf(edit.find, first + 1) >= 0) {+ failed.push({ find: edit.find, reason: 'not unique' })+ continue+ }+ out =+ out.slice(0, first) + edit.replace + out.slice(first + edit.find.length)+ applied+++ }+ return { content: out, applied, failed }+}++export type DraftChange = { title?: string; edits?: DraftEdit[] }++/**+ * Apply an editDraft call to a draft. A new title counts as one change; it is+ * for drafts without a top-level heading, whose title lives outside the text.+ */+export function applyDraftChange(+ draft: { title: string; content: string },+ change: DraftChange+): {+ title: string+ content: string+ applied: number+ failed: DraftEditFailure[]+} {+ const result = applyDraftEdits(+ draft.content,+ Array.isArray(change.edits) ? change.edits : []+ )+ const title = change.title?.trim()+ const renamed = Boolean(title) && title !== draft.title+ return {+ title: renamed ? title! : draft.title,+ content: result.content,+ applied: result.applied + (renamed ? 1 : 0),+ failed: result.failed+ }+}++/** The version later turns edit: the latest one whose block was completed. */+export function currentDraftVersion(+ versions: DraftVersion[]+): DraftVersion | null {+ for (let i = versions.length - 1; i >= 0; i--) {+ if (!versions[i].interrupted) return versions[i]+ }+ return null+}++type MessageLike = {+ id: string+ role: string+ parts?: Array<Record<string, unknown> & { type: string }>+}++/**+ * Rebuild every version of the chat's draft from its messages. A draft block+ * starts a new version; a completed editDraft call edits the current one.+ * One draft per chat: a new block replaces the previous draft.+ *+ * A block an answer stopped inside is kept as an interrupted version, so its+ * partial text stays readable, but it never becomes the draft later turns+ * edit. An edit replays only when the tool saw the same draft: the tool holds+ * the turn-start version, so an edit after a block written in the same answer,+ * or one the tool rejected, is skipped.+ */+export function buildDraftVersions(messages: MessageLike[]): DraftVersion[] {+ const versions: DraftVersion[] = []+ for (const message of messages) {+ if (message.role !== 'assistant') continue+ let wroteHere = false+ for (const part of message.parts ?? []) {+ if (part.type === 'text' && typeof part.text === 'string') {+ for (const block of parseDraftBlocks(part.text)) {+ wroteHere = true+ if (!block.closed && !block.content.trim()) continue+ versions.push({+ version: versions.length + 1,+ title: block.title,+ content: block.content,+ kind: 'write',+ messageId: message.id,+ ...(!block.closed && { interrupted: true })+ })+ }+ } else if (+ part.type === `tool-${EDIT_DRAFT_TOOL}` &&+ part.state === 'output-available'+ ) {+ const current = currentDraftVersion(versions)+ const input = part.input as DraftChange | undefined+ const output = part.output as { applied?: unknown } | undefined+ if (!current || wroteHere || !input) continue+ if (output?.applied === 0) continue+ const result = applyDraftChange(current, input)+ if (result.applied === 0) continue+ versions.push({+ version: versions.length + 1,+ title: result.title,+ content: result.content,+ kind: 'edit',+ messageId: message.id,+ applied: result.applied,+ failed: result.failed+ })+ }+ }+ }+ return versions+}++/**+ * Replace draft blocks in a historical answer with a one-line stub. The+ * stub depends only on the block, so a message replays identically on every+ * turn and the prompt-cache prefix holds.+ */+export function compactDraftBlocks(text: string): string {+ return replaceDraftBlocks(+ text,+ ({ title, content }) =>+ `[Draft "${title}" written here (${content.length} characters). The current version is attached to the latest user message.]`+ )+}++/** The current draft, as attached to the latest user message for the model. */+export function formatCurrentDraft(version: DraftVersion): string {+ return [+ `<current_draft title="${version.title.replace(/"/g, "'")}" version="${version.version}">`,+ version.content,+ '</current_draft>'+ ].join('\n')+}diff --git a/lib/draft/prompt.ts b/lib/draft/prompt.tsnew file mode 100644index 00000000..1cf636d9--- /dev/null+++ b/lib/draft/prompt.ts@@ -0,0 +1,38 @@+export const EXAMPLE_DRAFT_BLOCK = `\`\`\`\`draft+title: Welcome email for new members++# Welcome to the club++Hi {name},+...+\`\`\`\``++/**+ * Returns the prompt section that instructs the LLM to put content the user+ * will take away in a draft block, shown in a side panel, and to change it+ * with the editDraft tool.+ */+export function getDraftPrompt(): string {+ return `+DRAFTS (only for writing requests; every other answer follows the format above unchanged):+When the user asks you to write or transform content for their own use (an article, post, email, message, script, story,+resume, translation of text they provided, or any document longer than a few sentences), put the complete content in a+draft block. The draft opens in a side panel where the user reads, copies, and revises it. Short items (a title, a+one-line caption, a single sentence) stay inline as normal text.++Draft block format: open it with FOUR backticks and the language "draft", and close it with FOUR backticks too. The+first line inside is "title: <short title>", then a blank line, then the content as markdown. Ordinary three-backtick code+fences inside the content are fine.++${EXAMPLE_DRAFT_BLOCK}++DRAFT RULES:+1. In a draft answer, the text outside the block is one or two sentences saying what you wrote or changed; never+ repeat the draft's content outside the block.+2. Do not put citation markers inside the draft. If the draft relies on search results, cite them in the sentence+ outside the block.+3. One draft per chat. When a draft exists, the latest message carries it in <current_draft>; change it with editDraft,+ or for a change across the whole draft (shorten, change the tone, restructure, translate), write a new complete+ draft block.+`+}diff --git a/lib/render/__tests__/strip-spec-blocks.test.ts b/lib/render/__tests__/strip-spec-blocks.test.tsindex 2f3b90ed..fd33886b 100644--- a/lib/render/__tests__/strip-spec-blocks.test.ts+++ b/lib/render/__tests__/strip-spec-blocks.test.ts@@ -68,3 +68,27 @@ describe('stripSpecBlocks', () => {expect(result).not.toContain('```spec')})})++describe('stripSpecBlocks with drafts', () => {+ test('unwraps a draft block to its content', () => {+ const input = [+ 'Here is the draft.',+ '',+ '````draft',+ 'title: Note',+ '',+ '# Note',+ '',+ '```ts',+ 'const x = 1',+ '```',+ '````'+ ].join('\n')++ const result = stripSpecBlocks(input)+ expect(result).not.toContain('````')+ expect(result).not.toContain('title: Note')+ expect(result).toContain('# Note')+ expect(result).toContain('```ts\nconst x = 1\n```')+ })+})diff --git a/lib/render/streamdown-spec.tsx b/lib/render/streamdown-spec.tsxindex 0d0021eb..d5130075 100644--- a/lib/render/streamdown-spec.tsx+++ b/lib/render/streamdown-spec.tsx@@ -2,6 +2,7 @@import type { CustomRenderer, PluginConfig } from 'streamdown'+import { DraftFenceCard } from '@/components/draft/draft-card'import { SpecFenceBlock } from '@/components/spec-fence-block'export function createStreamdownSpecRenderer(): CustomRenderer {@@ -13,19 +14,34 @@ export function createStreamdownSpecRenderer(): CustomRenderer {}}+// A draft's content shows in the side panel; the answer keeps a card.+export function createStreamdownDraftRenderer(): CustomRenderer {+ return {+ language: 'draft',+ component({ code }) {+ return <DraftFenceCard code={code} />+ }+ }+}+export function mergeStreamdownSpecRenderer(- plugins?: PluginConfig+ plugins?: PluginConfig,+ { drafts = true }: { drafts?: boolean } = {}): PluginConfig {const userRenderers = plugins?.renderers ?? []const filteredRenderers = userRenderers.filter(renderer => {const languages = Array.isArray(renderer.language)? renderer.language: [renderer.language]- return !languages.includes('spec')+ return !languages.includes('spec') && !languages.includes('draft')})return {...plugins,- renderers: [createStreamdownSpecRenderer(), ...filteredRenderers]+ renderers: [+ createStreamdownSpecRenderer(),+ ...(drafts ? [createStreamdownDraftRenderer()] : []),+ ...filteredRenderers+ ]}}diff --git a/lib/render/strip-spec-blocks.ts b/lib/render/strip-spec-blocks.tsindex 5d65500c..1ab9bcab 100644--- a/lib/render/strip-spec-blocks.ts+++ b/lib/render/strip-spec-blocks.ts@@ -1,12 +1,14 @@+import { replaceDraftBlocks } from '@/lib/draft/draft'+import { linkedCardsFenceToMarkdown } from './linked-cards-markdown'/*** Remove ```spec fenced blocks from text content, keeping linked Card items as- * a markdown list.+ * a markdown list, and unwrap ````draft blocks to their content.* Used when copying message text to clipboard.*/export function stripSpecBlocks(text: string): string {- return text+ return replaceDraftBlocks(text, ({ content }) => content).replace(/```spec[\s\S]*?```/g, block => {return linkedCardsFenceToMarkdown(block) ?? ''})diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex 28fc07f2..47686088 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -4,6 +4,7 @@ import type { StreamTextOnErrorCallback } from 'ai'import { consumeStream, convertToModelMessages, smoothStream } from 'ai'import { researcher } from '@/lib/agents/researcher'+import { buildDraftVersions, currentDraftVersion } from '@/lib/draft/draft'import {createPublicErrorResponse,serializePublicError@@ -35,6 +36,10 @@ import { convertDataPart } from './helpers/convert-data-part'import { assignDataPartNonces } from './helpers/data-part-nonce'import { dedupeAttachments } from './helpers/dedupe-attachments'import { describeTurnInput } from './helpers/describe-turn-input'+import {+ attachCurrentDraft,+ compactDraftsInMessages+} from './helpers/draft-context'import { hasAnswerAfterToolFailure } from './helpers/has-answer-after-tool-failure'import { hasResponseContentPart } from './helpers/has-response-content'import {@@ -216,6 +221,11 @@ export async function createChatStreamResponse()}+ // The chat's draft as of this turn, rebuilt from history+ const currentDraft = currentDraftVersion(+ buildDraftVersions(messagesToModel)+ )+// Get the researcher agent with search modestreamErrorStage = 'build-agent'const researchAgent = researcher({@@ -223,12 +233,15 @@ export async function createChatStreamResponse(modelConfig: model,chatId,searchMode,- citationLabelSeed: nextCitationLabelNumber(messagesToModel)+ citationLabelSeed: nextCitationLabelNumber(messagesToModel),+ currentDraft})streamErrorStage = 'transform-messages'const messagesWithNonces = assignDataPartNonces(messagesToModel)- const messagesWithoutSpec = stripSpecFromMessages(messagesWithNonces)+ const messagesWithoutSpec = compactDraftsInMessages(+ stripSpecFromMessages(messagesWithNonces)+ )const messagesWithAttachmentSizes = await resolveAttachmentSizes(messagesWithoutSpec,userId@@ -258,9 +271,10 @@ export async function createChatStreamResponse(// Convert to model messages and apply context window managementstreamErrorStage = 'convert-messages'- let modelMessages = await convertToModelMessages(messagesToConvert, {- convertDataPart- })+ let modelMessages = await convertToModelMessages(+ attachCurrentDraft(messagesToConvert, currentDraft),+ { convertDataPart }+ )streamErrorStage = 'truncate-messages'if (diff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.tsindex b66843e7..24c6d5bc 100644--- a/lib/streaming/create-ephemeral-chat-stream-response.ts+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts@@ -4,6 +4,7 @@ import type { StreamTextOnErrorCallback, UIMessage } from 'ai'import { consumeStream, convertToModelMessages, smoothStream } from 'ai'import { researcher } from '@/lib/agents/researcher'+import { buildDraftVersions, currentDraftVersion } from '@/lib/draft/draft'import {createPublicErrorResponse,serializePublicError@@ -31,6 +32,10 @@ import { convertDataPart } from './helpers/convert-data-part'import { assignDataPartNonces } from './helpers/data-part-nonce'import { dedupeAttachments } from './helpers/dedupe-attachments'import { describeTurnInput } from './helpers/describe-turn-input'+import {+ attachCurrentDraft,+ compactDraftsInMessages+} from './helpers/draft-context'import {EMPTY_RESPONSE_STATUS_MESSAGE,isEmptyResponse@@ -133,8 +138,12 @@ export async function createEphemeralChatStreamResponse(}try {+ // The chat's draft as of this turn, rebuilt from history+ const currentDraft = currentDraftVersion(buildDraftVersions(messages))const messagesWithNonces = assignDataPartNonces(messages)- const messagesWithoutSpec = stripSpecFromMessages(messagesWithNonces)+ const messagesWithoutSpec = compactDraftsInMessages(+ stripSpecFromMessages(messagesWithNonces)+ )const messagesToConvert = dedupeAttachments(capHistoricalPastedContent(capHistoricalAttachments(@@ -147,9 +156,10 @@ export async function createEphemeralChatStreamResponse(buildAttachmentTokenEstimates(messagesToConvert)streamErrorStage = 'convert-messages'- let modelMessages = await convertToModelMessages(messagesToConvert, {- convertDataPart- })+ let modelMessages = await convertToModelMessages(+ attachCurrentDraft(messagesToConvert, currentDraft),+ { convertDataPart }+ )streamErrorStage = 'truncate-messages'if (@@ -171,7 +181,8 @@ export async function createEphemeralChatStreamResponse(modelConfig: model,chatId,searchMode,- citationLabelSeed: nextCitationLabelNumber(messages)+ citationLabelSeed: nextCitationLabelNumber(messages),+ currentDraft})const modelId = `${model.providerId}:${model.id}`diff --git a/lib/streaming/helpers/__tests__/draft-context.test.ts b/lib/streaming/helpers/__tests__/draft-context.test.tsnew file mode 100644index 00000000..a6ac9604--- /dev/null+++ b/lib/streaming/helpers/__tests__/draft-context.test.ts@@ -0,0 +1,60 @@+import type { UIMessage } from 'ai'+import { describe, expect, it } from 'vitest'++import { attachCurrentDraft, compactDraftsInMessages } from '../draft-context'++const DRAFT = ['Done.', '', '````draft', 'title: T', '', 'Body', '````'].join(+ '\n'+)++function message(role: 'user' | 'assistant', text: string, id: string = role) {+ return { id, role, parts: [{ type: 'text', text }] } as unknown as UIMessage+}++function textOf(msg: UIMessage, i = 0): string {+ const part = msg.parts[i]+ return part.type === 'text' ? part.text : ''+}++describe('compactDraftsInMessages', () => {+ it('stubs draft blocks in assistant messages only', () => {+ const user = message('user', DRAFT)+ const [u, a] = compactDraftsInMessages([user, message('assistant', DRAFT)])++ expect(u).toBe(user)+ expect(textOf(a)).not.toContain('````draft')+ expect(textOf(a)).toContain('[Draft "T" written here (4 characters)')+ })++ it('returns the same message object when nothing changes', () => {+ const plain = message('assistant', 'No draft')+ expect(compactDraftsInMessages([plain])[0]).toBe(plain)+ })+})++describe('attachCurrentDraft', () => {+ const draft = {+ version: 1,+ title: 'T',+ content: 'Body',+ kind: 'write' as const,+ messageId: 'a'+ }++ it('appends the draft to the latest user message only', () => {+ const first = message('user', 'one', 'u1')+ const result = attachCurrentDraft(+ [first, message('assistant', 'reply'), message('user', 'two', 'u2')],+ draft+ )++ expect(result[0]).toBe(first)+ expect(result[2].parts).toHaveLength(2)+ expect(textOf(result[2], 1)).toContain('<current_draft title="T"')+ })++ it('leaves messages alone without a draft', () => {+ const messages = [message('user', 'one')]+ expect(attachCurrentDraft(messages, null)).toBe(messages)+ })+})diff --git a/lib/streaming/helpers/draft-context.ts b/lib/streaming/helpers/draft-context.tsnew file mode 100644index 00000000..150398dd--- /dev/null+++ b/lib/streaming/helpers/draft-context.ts@@ -0,0 +1,55 @@+import { UIMessage } from 'ai'++import {+ compactDraftBlocks,+ type DraftVersion,+ formatCurrentDraft+} from '@/lib/draft/draft'++/**+ * Replaces draft blocks in assistant text with a one-line stub. Every version+ * would otherwise replay in full on each later turn. The stub depends only on+ * the message, so the prompt-cache prefix stays stable.+ */+export function compactDraftsInMessages(messages: UIMessage[]): UIMessage[] {+ return messages.map(msg => {+ if (msg.role !== 'assistant' || !msg.parts) return msg++ let changed = false+ const parts = msg.parts.map(part => {+ if (part.type !== 'text' || typeof part.text !== 'string') return part+ const text = compactDraftBlocks(part.text)+ if (text === part.text) return part+ changed = true+ return { ...part, text }+ })++ return changed ? { ...msg, parts } : msg+ })+}++/**+ * Attaches the current draft to the latest user message, the tail of the+ * prompt, so it never sits inside the cached prefix. The model needs the exact+ * text to write editDraft find strings.+ */+export function attachCurrentDraft(+ messages: UIMessage[],+ currentDraft: DraftVersion | null+): UIMessage[] {+ if (!currentDraft) return messages++ const index = messages.findLastIndex(msg => msg.role === 'user')+ if (index < 0) return messages++ const target = messages[index]+ const withDraft = {+ ...target,+ parts: [+ ...(target.parts ?? []),+ { type: 'text' as const, text: formatCurrentDraft(currentDraft) }+ ]+ }++ return [...messages.slice(0, index), withDraft, ...messages.slice(index + 1)]+}diff --git a/lib/tools/draft.ts b/lib/tools/draft.tsnew file mode 100644index 00000000..178fcf32--- /dev/null+++ b/lib/tools/draft.ts@@ -0,0 +1,78 @@+import { tool } from 'ai'+import { z } from 'zod'++import { applyDraftChange, type DraftVersion } from '@/lib/draft/draft'++export const editDraftInputSchema = z.object({+ title: z+ .string()+ .optional()+ .describe(+ 'A new title, only for a draft without a top-level heading. When the draft has one, edit the heading instead.'+ ),+ edits: z+ .array(+ z.object({+ find: z+ .string()+ .describe(+ 'Exact text copied from the current draft. It must appear exactly once; include enough surrounding text to make it unique.'+ ),+ replace: z.string().describe('The text that replaces it')+ })+ )+ .optional()+ .describe('Edits applied in order')+})++/**+ * Edit the chat's current draft in place. The draft is rebuilt from history+ * before the turn, so this only ever sees the version the model was shown.+ */+export function createDraftTools(currentDraft: DraftVersion | null) {+ let current = currentDraft++ const editDraft = tool({+ description: `Make local changes to the current draft (a sentence, a paragraph, the title, one section, a passage the user quoted) with exact find/replace edits.+- Copy each find exactly from <current_draft>. It must appear exactly once; include enough surrounding text to make it unique. If edits are reported as failed, retry only those with corrected find text.+- When the user's message quotes text from the draft (a quoted-context block), that text is what "this" refers to: change only it, and make sure each find contains it.+- For a change across the whole draft, or more than about five places, write a new complete draft block instead.+- Never call this in the same answer that writes a draft block: it only sees the draft from before this answer.+- To rename a draft without a top-level heading, pass the new title; otherwise edit the heading.`,+ inputSchema: editDraftInputSchema,+ execute: async ({ title, edits }) => {+ if (!current) {+ return {+ applied: 0,+ failed: [],+ message:+ 'There is no draft in this chat yet. Write one in a draft block first.'+ }+ }++ const result = applyDraftChange(current, { title, edits })+ if (result.applied > 0) {+ current = {+ ...current,+ version: current.version + 1,+ title: result.title,+ content: result.content,+ kind: 'edit'+ }+ }++ return {+ applied: result.applied,+ failed: result.failed,+ version: current.version,+ characters: current.content.length,+ ...(result.failed.length > 0 && {+ message:+ 'Some edits were skipped because their find text was missing or not unique. Copy the exact text from the current draft and retry only those.'+ })+ }+ }+ })++ return { editDraft }+}diff --git a/lib/types/agent.ts b/lib/types/agent.tsindex 413e1a23..17a0ea38 100644--- a/lib/types/agent.ts+++ b/lib/types/agent.ts@@ -6,6 +6,7 @@ import type {UIToolInvocation} from 'ai'+import type { createDraftTools } from '../tools/draft'import type { fetchTool } from '../tools/fetch'import type { createQuestionTool } from '../tools/question'import type { createSearchTool } from '../tools/search'@@ -18,7 +19,8 @@ export type ResearcherTools = {search: ReturnType<typeof createSearchTool>fetch: typeof fetchToolaskQuestion: ReturnType<typeof createQuestionTool>-} & ReturnType<typeof createTodoTools>+} & ReturnType<typeof createTodoTools> &+ ReturnType<typeof createDraftTools>// Runtime context carried through the generation lifecycle. Included in// telemetry so each observation keeps the metadata v6 attached viadiff --git a/lib/types/ai.ts b/lib/types/ai.tsindex 7d9341f1..14e79f08 100644--- a/lib/types/ai.ts+++ b/lib/types/ai.ts@@ -61,4 +61,7 @@ export type ToolPart<T extends keyof UITools = keyof UITools> = {errorText?: string}-export type Part = TextPart | ReasoningPart | ToolPart+// Opens the chat's draft in the inspector panel; not a message part.+export type DraftPanelPart = { type: 'draft' }++export type Part = TextPart | ReasoningPart | ToolPart | DraftPanelPartdiff --git a/lib/utils/__tests__/message-mapping.test.ts b/lib/utils/__tests__/message-mapping.test.tsindex 7b9f3d9f..fe4fac94 100644--- a/lib/utils/__tests__/message-mapping.test.ts+++ b/lib/utils/__tests__/message-mapping.test.ts@@ -3,7 +3,10 @@ import { describe, expect, it } from 'vitest'import { DeterministicPreparationError } from '@/lib/errors/deterministic-preparation-error'import type { DBMessagePartSelect } from '@/lib/types/message-persistence'-import { mapDBPartToUIMessagePart } from '../message-mapping'+import {+ mapDBPartToUIMessagePart,+ mapUIMessagePartsToDBParts+} from '../message-mapping'function persistedPart(values: Partial<DBMessagePartSelect>@@ -26,3 +29,24 @@ describe('mapDBPartToUIMessagePart', () => {).toThrow(DeterministicPreparationError)})})++describe('editDraft tool parts', () => {+ it('round-trips through the dynamic tool columns', () => {+ const uiPart = {+ type: 'tool-editDraft',+ toolCallId: 'call-1',+ state: 'output-available',+ input: { edits: [{ find: 'a', replace: 'b' }] },+ output: { applied: 1, failed: [] }+ }+ const [dbPart] = mapUIMessagePartsToDBParts([uiPart] as never, 'msg-1')++ expect(dbPart.type).toBe('tool-dynamic')+ expect(dbPart.tool_dynamic_type).toBe('draft')++ const restored = mapDBPartToUIMessagePart(+ persistedPart(dbPart as Partial<DBMessagePartSelect>)+ )+ expect(restored).toMatchObject(uiPart)+ })+})diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.tsindex 51d9949e..907e39bf 100644--- a/lib/utils/message-mapping.ts+++ b/lib/utils/message-mapping.ts@@ -314,6 +314,25 @@ export function mapUIMessagePartsToDBParts(}return createToolPartMapping(basePart, part, 'todoRead')+ // Stored in the dynamic tool columns, so drafts need no schema change.+ // Read back as tool-editDraft by the 'draft' dynamic type.+ case 'tool-editDraft':+ if (!isExtendedToolPart(part)) {+ console.error('Invalid extended tool part:', part)+ return null+ }+ return {+ ...basePart,+ type: 'tool-dynamic',+ tool_toolCallId: part.toolCallId || generateId(),+ tool_state: part.state || ('input-available' as ToolState),+ tool_dynamic_name: 'editDraft',+ tool_dynamic_type: 'draft',+ tool_dynamic_input: part.input,+ tool_dynamic_output: part.output,+ tool_errorText: part.errorText+ }+// Data partsdefault:if (part.type.startsWith('data-')) {@@ -399,6 +418,16 @@ export function mapDBPartToUIMessagePart(`tool_${toolName}_output` as keyof DBMessagePartSelect// Special handling for dynamic tools+ if (toolName === 'dynamic' && part.tool_dynamic_type === 'draft') {+ return {+ type: `tool-${part.tool_dynamic_name}`,+ toolCallId: part.tool_toolCallId || '',+ state: part.tool_state as any,+ input: part.tool_dynamic_input,+ output: part.tool_dynamic_output,+ errorText: part.tool_errorText+ } as any+ }if (toolName === 'dynamic') {return {type: 'dynamic-tool',