'use client' import type { DocsSearchV2AskAiQuestionSubmittedEvent } from 'common/telemetry-constants' import { SearchInputRow, type SearchDialogProps } from 'docs-search/components' import { FileText } from 'lucide-react' import { useReducedMotion } from 'motion/react' import Link from 'next/link' import { useCallback, useEffect, useRef, useState, type ChangeEvent, type ComponentProps, type FormEvent, type KeyboardEvent, type UIEvent, } from 'react' import { CodeCopyButton } from 'ui-patterns/CodeBlock/CodeBlockControls' import { MessageRole, MessageStatus, useAiChat, type Message, } from 'ui-patterns/CommandMenu/prepackaged/ai' import { Markdown } from 'ui-patterns/Markdown' import { AskAiIcon } from './AskAiIcon' import { CurvedScrollArea } from '@/features/ui/CurvedScrollArea' import { useSendTelemetryEvent } from '@/lib/telemetry' type QuestionSource = DocsSearchV2AskAiQuestionSubmittedEvent['properties']['questionSource'] interface AskAiPanelProps { initialQuestion: string } interface AiMessagesProps { messages: Message[] hasError: boolean } interface AiAnswerMarkdownProps { content: string } interface AiSourcesProps { sources: NonNullable onSourceClick: (sourcePath: string) => void } export const ASK_AI_DIALOG_LABELS: SearchDialogProps['labels'] = { dialogTitle: 'Ask Supabase AI', dialogDescription: 'Ask about the Supabase docs', } export function AskAiPanel({ initialQuestion }: AskAiPanelProps) { const [question, setQuestion] = useState('') const [isLoading, setIsLoading] = useState(false) const sendTelemetryEvent = useSendTelemetryEvent() // the question that search sent is the first one, and every later question is typed const questionSourceRef = useRef(initialQuestion ? 'search' : 'typed') const { submit, reset, messages, isResponding, hasError } = useAiChat({ setIsLoading, onAnswerComplete: ({ durationMs, sourceCount }) => sendTelemetryEvent({ action: 'docs_search_v2_ask_ai_answer_completed', properties: { questionSource: questionSourceRef.current, durationMs, sourceCount }, }), onAnswerError: ({ durationMs }) => sendTelemetryEvent({ action: 'docs_search_v2_ask_ai_answer_failed', properties: { questionSource: questionSourceRef.current, durationMs }, }), }) const inputRef = useRef(null) const isPinnedRef = useRef(true) const lastScrollTopRef = useRef(0) const listRef = useRef(null) const isBusy = isLoading || isResponding const hasConversation = messages.length > 0 const hasAnswer = messages.some( ({ role, content }) => role === MessageRole.Assistant && content !== '' ) // exception: asks the question that search sent on mount. the dialog unmounts this panel // on close, so the cleanup closes the answer stream useEffect(() => { if (initialQuestion) submit(initialQuestion) return reset // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const handleSubmit = (event: FormEvent) => { event.preventDefault() const trimmedQuestion = question.trim() if (!trimmedQuestion || isBusy) return questionSourceRef.current = 'typed' submit(trimmedQuestion) sendTelemetryEvent({ action: 'docs_search_v2_ask_ai_question_submitted', properties: { questionLength: trimmedQuestion.length, questionSource: 'typed', }, }) setQuestion('') isPinnedRef.current = true } const handleListScroll = (event: UIEvent) => { const list = event.currentTarget if (list.scrollHeight - list.scrollTop - list.clientHeight < 32) isPinnedRef.current = true else if (list.scrollTop < lastScrollTopRef.current) isPinnedRef.current = false lastScrollTopRef.current = list.scrollTop } // a stable callback ref, so react does not create the observer again on each render const followConversation = useCallback((content: HTMLDivElement | null) => { if (!content) return const observer = new ResizeObserver(() => { const list = listRef.current if (list && isPinnedRef.current) list.scrollTop = list.scrollHeight }) observer.observe(content) return () => observer.disconnect() }, []) const handleKeyDown = (event: KeyboardEvent) => { // enter confirms an IME composition, so it must not submit if (event.key === 'Enter' && event.nativeEvent.isComposing) event.preventDefault() } const handleQuestionChange = (event: ChangeEvent) => { setQuestion(event.target.value) } // focus stays in the input while the answer renders, so this tells a screen reader what changed. // it never reads the streamed text const getStatusMessage = (): string => { if (hasError) return 'No answer from Supabase AI. Try again in a moment.' if (isLoading) return 'Searching the docs…' if (isResponding) return 'Writing the answer…' if (messages.at(-1)?.status === MessageStatus.Complete) return 'Answer ready.' return '' } // reset() does not clear the loading state that submit sets. the clear button unmounts with // the conversation, so focus goes back to the input const handleClear = () => { reset() setIsLoading(false) setQuestion('') inputRef.current?.focus() } return (
{getStatusMessage()}
{hasConversation ? (
{hasAnswer && !isBusy ? (

Supabase AI can make mistakes. Verify answers before you run them.

) : null}
) : null}
} onClear={hasConversation ? handleClear : undefined} // under a conversation the input is far from the search input, // so a morph would move it across the dialog hasMorph={!hasConversation} className={hasConversation ? 'border-t' : undefined} > {isLoading && !question ? ( Searching the docs … ) : null}
) } function AiMessages({ messages, hasError }: AiMessagesProps) { const sendTelemetryEvent = useSendTelemetryEvent() // the input shows a pending answer. a failed request leaves its answer incomplete. // the last answer failed when an error is set, and an earlier answer failed when it is incomplete const isFailedAnswer = (message: Message, index: number) => message.status !== MessageStatus.Complete && (hasError || index < messages.length - 1) const handleSourceClick = (sourcePath: string) => { sendTelemetryEvent({ action: 'docs_search_v2_ask_ai_source_clicked', properties: { sourcePath }, }) } const handleAnswerCopy = () => { sendTelemetryEvent({ action: 'copy_as_markdown_clicked', properties: { pageType: 'ask_ai_answer' }, }) } return (
    {messages.map((message, index) => message.role === MessageRole.User ? ( // messages have no id and are only ever appended, so the index is stable
  1. {message.content}

  2. ) : message.status === MessageStatus.Pending && !isFailedAnswer(message, index) ? null : (
  3. {message.status === MessageStatus.Pending ? null : ( )} {isFailedAnswer(message, index) ? (

    No answer from Supabase AI. Try again in a moment.

    ) : null} {message.sources?.length ? ( ) : null} {message.status === MessageStatus.Complete ? ( `- ${url}`).join('\n')}` : message.content } label="Copy as Markdown" copiedLabel="Answer copied as Markdown" onCopied={handleAnswerCopy} className="mt-2 border-transparent bg-transparent opacity-0 hover:border-transparent hover:bg-transparent focus-visible:opacity-100 group-hover:opacity-100 pointer-coarse:opacity-100" /> ) : null}
  4. ) )}
) } function AiAnswerMarkdown({ content }: AiAnswerMarkdownProps) { const [visibleLength, setVisibleLength] = useState(0) const isReducedMotion = useReducedMotion() const isCaughtUp = visibleLength >= content.length // exception: chunks arrive in bursts. each animation frame shows 1/12 of the hidden text. // a large backlog drains fast, and a small one shows at a steady rate useEffect(() => { if (isCaughtUp || isReducedMotion) return const frame = requestAnimationFrame(() => setVisibleLength((length) => length + Math.ceil((content.length - length) / 12)) ) return () => cancelAnimationFrame(frame) }, [content.length, isCaughtUp, isReducedMotion, visibleLength]) return ( {isReducedMotion ? content : content.slice(0, visibleLength)} ) } function AiAnswerLink(props: ComponentProps<'a'>) { const sendTelemetryEvent = useSendTelemetryEvent() const handleClick = () => { sendTelemetryEvent({ action: 'docs_search_v2_ask_ai_answer_link_clicked', properties: { href: props.href ?? '' }, }) } return } function AiSources({ sources, onSourceClick }: AiSourcesProps) { return ( ) }