The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
merge cmdk branch and resolve conflicts
Joshen Limc8b431fb6ad7
diff --cc packages/ui/src/components/Command/CommandMenuProvider.tsxindex 7ebd7e9fb2d,8ae991842e4..fee919d5787--- a/packages/ui/src/components/Command/CommandMenuProvider.tsx+++ b/packages/ui/src/components/Command/CommandMenuProvider.tsx@@@ -22,10 -31,10 +31,10 @@@ export interface CommandMenuContextValu// to do: remove this prop// this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package- MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element // to do: remove this. although it breaks our jest tests+ MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element// Optional callback to save a generated SQL output- onSaveGeneratedSQL?: (answer: string, resolve: any) => void+ saveGeneratedSQL?: (answer: string, title: string) => Promise<void>}export const CommandMenuContext = createContext<CommandMenuContextValue | undefined>(undefined)export const useCommandMenu = () => {@@@ -45,11 -54,27 +54,27 @@@ export interface CommandMenuActionsexport interface CommandMenuProviderProps {site: 'studio' | 'docs'projectRef?: string+ /**+ * Project's API keys, for easy access through CMDK+ */apiKeys?: { anon?: string; service?: string }- // to do: remove this prop- // this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package+ /**+ * Opt in flag to use additional metadata in AI prompts+ */+ isOptedInToAI?: boolean+ /**+ * Any additional metadata that CMDK component can use in its AI prompts+ */+ metadata?: { definitions?: string; flags?: { [key: string]: string } }+ /**+ * TODO: remove this prop, temporary hack as ReactMarkdown fails our jest tests+ * if we import the package directly within this UI package+ */MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element+ /**+ * Call back when save SQL snippet button is selected+ */- onSaveGeneratedSQL?: (answer: string, resolve: any) => void+ saveGeneratedSQL?: (answer: string, title: string) => Promise<void>}const CommandMenuProvider = ({@@@ -57,8 -82,10 +82,10 @@@site,projectRef,apiKeys,+ metadata,+ isOptedInToAI = false,MarkdownHandler,- onSaveGeneratedSQL,+ saveGeneratedSQL,}: PropsWithChildren<CommandMenuProviderProps>) => {const [isOpen, setIsOpen] = useState(false)const [isLoading, setIsLoading] = useState(false)@@@ -87,8 -114,10 +114,10 @@@currentPage,site,project,+ metadata,+ isOptedInToAI,MarkdownHandler,- onSaveGeneratedSQL,+ saveGeneratedSQL,}}>{children}diff --cc packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsxindex ca3515ca1f8,9cc7ac826eb..15911a7d4f8--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx@@@ -189,8 -77,13 +77,13 @@@ const GenerateSQL = () =>return (<div onClick={(e) => e.stopPropagation()}>- <div className={cn('relative mb-[62px] py-4 max-h-[720px] overflow-auto')}>+ <div+ className={cn(+ 'relative py-4 max-h-[720px] overflow-auto',+ allowSendingSchemaMetadata ? 'mb-[83px]' : 'mb-[42px]'+ )}+ >- {messages.map((message) => {+ {messages.map((message, i) => {switch (message.role) {case MessageRole.User:return (@@@ -249,8 -146,8 +146,8 @@@>{answer}</CodeBlock>- {!isResponding && (+ {message.status === MessageStatus.Complete && (- <SQLOutputActions answer={answer} />+ <SQLOutputActions answer={answer} messages={messages.slice(0, i + 1)} />)}</div>)}@@@ -329,7 -227,30 +227,30 @@@<div className="[overflow-anchor:auto] h-px w-full"></div></div>+<div className="absolute bottom-0 w-full bg-scale-200 py-3">+ {allowSendingSchemaMetadata && (+ <div className="flex items-center justify-between px-6 py-3">+ <div>+ <p className="text-sm">+ Include table names, column names and their corresponding data types in prompt+ </p>+ <p className="text-sm text-scale-1100">+ This will generate answers that are more relevant to your project's schema+ </p>+ </div>+ <Toggle- disabled={!isOptedInToAI}++ disabled={!isOptedInToAI || isLoading || isResponding}+ checked={includeSchemaMetadata}+ onChange={() =>+ setIncludeSchemaMetadata((prev) => {+ includeSchemaMetadataRef.current = !prev+ return !prev+ })+ }+ />+ </div>+ )}<InputclassName="bg-scale-100 rounded mx-3"autoFocusdiff --cc packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.tsindex 00000000000,8c1164292b2..ca6c7dd128dmode 000000,100644..100644--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts@@@ -1,0 -1,84 +1,101 @@@+ import { stripIndent } from 'common-tags'++ export function getEdgeFunctionUrl() {+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/$/, '')++ if (!supabaseUrl) return undefined++ // https://github.com/supabase/supabase-js/blob/10d3423506cbd56345f7f6ab2ec2093c8db629d4/src/SupabaseClient.ts#L96+ const isPlatform = supabaseUrl.match(/(supabase\.co)|(supabase\.in)/)++ if (isPlatform) {+ const [schemeAndProjectId, domain, tld] = supabaseUrl.split('.')+ return `${schemeAndProjectId}.functions.${domain}.${tld}`+ } else {+ return `${supabaseUrl}/functions/v1`+ }+ }++ export function promptDataReducer(+ state: any[],+ action: {+ index?: number+ answer?: string | undefined+ status?: string+ query?: string | undefined+ type?: 'remove-last-item' | string+ }+ ) {+ // set a standard state to use later+ let current = [...state]++ if (action.type) {+ switch (action.type) {+ case 'remove-last-item':+ current.pop()+ return [...current]+ default:+ break+ }+ }++ // check that an index is present+ if (action.index === undefined) return [...state]++ if (!current[action.index]) {+ current[action.index] = { query: '', answer: '', status: '' }+ }++ current[action.index].answer = action.answer++ if (action.query) {+ current[action.index].query = action.query+ }+ if (action.status) {+ current[action.index].status = action.status+ }++ return [...current]+ }++ export const generatePrompt = (prompt: string, metadata?: any) => {+ const { definitions } = metadata || {}+ return stripIndent`+ ${+ definitions !== undefined+ ? `+ Given the following Postgres SQL tables:+ ${definitions}+ `+ : ''+ }++ Generate a Postgres SQL query based on the following natural language prompt.+ - Only output valid SQL - all explanations must be SQL comments+ - SQL comments should be short+ - Your very last output should be "\`\`\`"+ - For primary keys, always use "integer primary key generated always as identity"++ Natural language prompt:+ ${prompt}++ Postgres SQL query (markdown SQL only):+ `.trim()+ }++++/**++ * Formats a string for use as a title.++ *++ * Removes punctuation and capitalizes each word++ */++export function formatTitle(value: string) {++ let words = value.replace(/\.$/, '').replace(/['"]/g, '').split(' ')++ words = words.map((word) => {++ // Don't capitalize code++ if (/[._\(\)]+/.test(word)) {++ return word++ }++ return word.charAt(0).toUpperCase() + word.slice(1)++ })++ return words.join(' ')++}diff --cc packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsxindex 00000000000,9b661edd4da..fe59affa469mode 000000,100644..100644--- a/packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsx+++ b/packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsx@@@ -1,0 -1,75 +1,115 @@@+ import { useState, useEffect } from 'react'+ import CopyToClipboard from 'react-copy-to-clipboard'-import { Button, IconCheck, IconClipboard, IconSave } from 'ui'++import {++ Button,++ IconCheck,++ IconClipboard,++ IconSave,++ Message,++ MessageRole,++ MessageStatus,++ queryAi,++} from 'ui'+ import { useCommandMenu } from '../CommandMenuProvider'++import { stripIndent } from 'common-tags'++import { formatTitle } from './GenerateSQL.utils'+-const SQLOutputActions = ({ answer }: { answer: string }) => {++export interface SQLOutputActionsProps {++ answer: string++ messages: Message[]++}++++const SQLOutputActions = ({ answer, messages }: SQLOutputActionsProps) => {+ const [showCopied, setShowCopied] = useState(false)+ const [isSaving, setIsSaving] = useState(false)+ const [isSaved, setIsSaved] = useState(false)+- const { project, onSaveGeneratedSQL } = useCommandMenu()-- const applyCallback = () =>- onSaveGeneratedSQL !== undefined- ? new Promise((resolve) => onSaveGeneratedSQL(answer, resolve))- : {}++ const { project, saveGeneratedSQL } = useCommandMenu()++ const onSelectSaveSnippet = async () => {+ setIsSaving(true)- await applyCallback()++++ let suggestedTitle++ try {++ suggestedTitle = await queryAi(++ [++ ...messages,++ {++ role: MessageRole.User,++ content: stripIndent`++ Generate a title for the above SQL snippet following all of these rules:++ - The title is only for the last SQL snippet++ - Focus on the main purposes of this snippet++ - Use as few words as possible++ - Title should be nouns, not verbs++ - Do not include word articles (eg. a, the, for, of)++ - Do not use words like "SQL" or "snippet" or "title"++ - Do not output markdown, quotes, etc++ - Do not be too verbose++ `,++ status: MessageStatus.Complete,++ },++ ],++ 10000++ )++ } catch (error) {++ suggestedTitle = ''++ }++++ const formattedTitle = formatTitle(suggestedTitle)++ await saveGeneratedSQL?.(answer, formattedTitle)+ setIsSaved(true)+ setIsSaving(false)+ }++ useEffect(() => {+ if (!showCopied) return+ const timer = setTimeout(() => setShowCopied(false), 2000)+ return () => clearTimeout(timer)+ }, [showCopied])++ useEffect(() => {+ if (!isSaved) return+ const timer = setTimeout(() => setIsSaved(false), 2000)+ return () => clearTimeout(timer)+ }, [isSaved])++ return (+ <div className="flex items-center justify-end space-x-2">+ <CopyToClipboard text={answer?.replace(/```.*/g, '').trim()}>+ <Button+ type="default"+ icon={+ showCopied ? (+ <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />+ ) : (+ <IconClipboard size="tiny" />+ )+ }+ onClick={() => setShowCopied(true)}+ >+ {showCopied ? 'Copied' : 'Copy SQL'}+ </Button>+ </CopyToClipboard>- {project?.ref !== undefined && onSaveGeneratedSQL !== undefined && (++ {project?.ref !== undefined && saveGeneratedSQL !== undefined && (+ <Button+ type="default"+ loading={isSaving}+ disabled={isSaving}+ icon={+ isSaved ? (+ <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />+ ) : (+ <IconSave size="tiny" />+ )+ }+ onClick={() => onSelectSaveSnippet()}+ >+ {isSaved ? 'Snippet saved!' : 'Save into new snippet'}+ </Button>+ )}+ </div>+ )+ }++ export default SQLOutputActionsdiff --cc studio/components/interfaces/App/CommandMenuWrapper.tsxindex ecaea5fe9bc,7de977954e1..2e0544dbc1c--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx@@@ -13,7 -13,7 +13,8 @@@ import { useSqlEditorStateSnapshot } frimport { useProfileQuery } from 'data/profile/profile-query'import { SqlSnippet } from 'data/content/sql-snippets-query'import { useProjectApiQuery } from 'data/config/project-api-query'+import { codeBlock } from 'common-tags'+ import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {const { ref } = useParams()@@@ -32,7 -36,22 +37,22 @@@service: settings?.autoApiService?.serviceApiKey ?? undefined,}+ const { data } = useEntityDefinitionsQuery(+ {+ projectRef: ui.selectedProject?.ref,+ connectionString: ui.selectedProject?.connectionString,+ },+ { enabled: isOptedInToAI }+ )++ const cmdkMetadata = useMemo(() => {+ return {+ definitions: (data ?? []).map((def) => def.sql.trim()).join('\n\n'),+ flags: { allowCMDKDataOptIn },+ }+ }, [data, allowCMDKDataOptIn])+- const onSaveGeneratedSQL = async (answer: string, resolve: any) => {+ const onSaveGeneratedSQL = async (answer: string, title: string) => {if (!ref) return console.error('Project ref is required')if (!canCreateSQLSnippet) {ui.setNotification({@@@ -79,7 -100,9 +99,9 @@@projectRef={ref}apiKeys={apiKeys}MarkdownHandler={(props) => <ReactMarkdown remarkPlugins={[remarkGfm]} {...props} />}- onSaveGeneratedSQL={onSaveGeneratedSQL}+ metadata={cmdkMetadata}+ isOptedInToAI={allowCMDKDataOptIn && isOptedInToAI}+ saveGeneratedSQL={onSaveGeneratedSQL}>{children}</CommandMenuProvider>