The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Assistant refinements (#30759)
Saxon Fletcherfcfc1cf38faf
diff --git a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx b/apps/studio/components/layouts/AppLayout/AssistantButton.tsxindex c5711c9c02a..2854c85248c 100644--- a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx+++ b/apps/studio/components/layouts/AppLayout/AssistantButton.tsx@@ -9,6 +9,7 @@ const AssistantButton = () => {type="text"size="tiny"id="assistant-trigger"+ className="h-full w-full rounded-none"onClick={() => {setAiAssistantPanel({ open: !aiAssistantPanel.open })}}diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsxindex 13a481d1a35..6285bcc5761 100644--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx@@ -47,83 +47,91 @@ const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder =return (<div- className={`flex h-12 max-h-12 min-h-12 items-center justify-between py-2 px-5 bg-dash-sidebar ${+ className={`flex h-12 max-h-12 min-h-12 items-center bg-dash-sidebar ${headerBorder ? 'border-b border-default' : ''}`}>- <div className="-ml-2 flex items-center text-sm">- {/* Organization is selected */}- {projectRef && (- <>- <OrganizationDropdown />+ <div className="flex items-center justify-between py-2 px-3 flex-1">+ <div className="flex items-center text-sm">+ {/* Organization is selected */}+ {projectRef && (+ <>+ <OrganizationDropdown />- {projectRef && (- <>- <span className="text-border-stronger">- <svg- viewBox="0 0 24 24"- width="16"- height="16"- stroke="currentColor"- strokeWidth="1"- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- shapeRendering="geometricPrecision"- >- <path d="M16 3.549L7.12 20.600"></path>- </svg>- </span>+ {projectRef && (+ <>+ <span className="text-border-stronger">+ <svg+ viewBox="0 0 24 24"+ width="16"+ height="16"+ stroke="currentColor"+ strokeWidth="1"+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ shapeRendering="geometricPrecision"+ >+ <path d="M16 3.549L7.12 20.600"></path>+ </svg>+ </span>- <ProjectDropdown />+ <ProjectDropdown />- {exceedingLimits && (- <div className="ml-2">- <Link href={`/org/${selectedOrganization?.slug}/usage`}>- <Badge variant="destructive">Exceeding usage limits</Badge>- </Link>- </div>- )}- </>- )}+ {exceedingLimits && (+ <div className="ml-2">+ <Link href={`/org/${selectedOrganization?.slug}/usage`}>+ <Badge variant="destructive">Exceeding usage limits</Badge>+ </Link>+ </div>+ )}+ </>+ )}- {selectedProject && (+ {selectedProject && (+ <>+ <span className="text-border-stronger">+ <svg+ viewBox="0 0 24 24"+ width="16"+ height="16"+ stroke="currentColor"+ strokeWidth="1"+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ shapeRendering="geometricPrecision"+ >+ <path d="M16 3.549L7.12 20.600"></path>+ </svg>+ </span>+ {isBranchingEnabled ? <BranchDropdown /> : <EnableBranchingButton />}+ </>+ )}+ </>+ )}++ {/* Additional breadcrumbs are supplied */}+ <BreadcrumbsView defaultValue={breadcrumbs} />+ </div>+ <div className="flex items-center gap-x-2">+ <div className="flex items-center gap-x-2">+ {customHeaderComponents && customHeaderComponents}+ {IS_PLATFORM && (<>- <span className="text-border-stronger">- <svg- viewBox="0 0 24 24"- width="16"- height="16"- stroke="currentColor"- strokeWidth="1"- strokeLinecap="round"- strokeLinejoin="round"- fill="none"- shapeRendering="geometricPrecision"- >- <path d="M16 3.549L7.12 20.600"></path>- </svg>- </span>- {isBranchingEnabled ? <BranchDropdown /> : <EnableBranchingButton />}+ <FeedbackDropdown />+ <NotificationsPopoverV2 />+ <HelpPopover /></>)}- </>- )}-- {/* Additional breadcrumbs are supplied */}- <BreadcrumbsView defaultValue={breadcrumbs} />- </div>- <div className="flex items-center gap-x-2">- {customHeaderComponents && customHeaderComponents}- {IS_PLATFORM && (- <>- <FeedbackDropdown />- <NotificationsPopoverV2 />- <HelpPopover />- {isAssistantV2Enabled && !!projectRef && <AssistantButton />}- </>- )}+ </div>+ </div></div>+ {isAssistantV2Enabled && !!projectRef && (+ <div className="border-l flex-0 h-full">+ <AssistantButton />+ </div>+ )}</div>)}diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.tsnew file mode 100644index 00000000000..abe0881783d--- /dev/null+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts@@ -0,0 +1,62 @@+import { isReadOnlySelect } from './AIAssistant.utils'++describe('AIAssistant.utils.ts:isReadOnlySelect', () => {+ test('Should return true for SQL that only contains SELECT operation', () => {+ const sql = 'select * from countries where id > 100 order by id asc;'+ const result = isReadOnlySelect(sql)+ expect(result).toBe(true)+ })+ test('Should return false for SQL that contains INSERT operation', () => {+ const sql = `insert into countries (id, name) values (1, 'hello');`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains UPDATE operation', () => {+ const sql = `update countries set name = 'hello' where id = 2;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains DELETE operation', () => {+ const sql = `delete from countries where id = 2;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains ALTER operation', () => {+ const sql = `alter table countries drop column id if exists;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains DROP operation', () => {+ const sql = `drop table if exists countries;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains CREATE operation', () => {+ const sql = `create schema test_schema;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that contains REPLACE operation', () => {+ const sql = `create or replace view test_view as select * from countries where id > 500;`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return false for SQL that calls a function not whitelisted', () => {+ const sql = `select create_new_user();`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(false)+ })+ test('Should return true for SQL that calls a function that is whitelisted', () => {+ const sql = `select count(select * from countries);`+ const result = isReadOnlySelect(sql)+ expect(result).toBe(true)+ })+ test('Should return false for SQL that contains a write operation with a read operation', () => {+ const sql1 = `select count(select * from countries); create schema joshen;`+ const result1 = isReadOnlySelect(sql1)+ expect(result1).toBe(false)+ const sql2 = `create schema joshen; select count(select * from countries);`+ const result2 = isReadOnlySelect(sql2)+ expect(result2).toBe(false)+ })+})diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.tsindex 5bbc060d26e..a9b12a7ffb4 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts@@ -117,39 +117,61 @@ export const isReadOnlySelect = (query: string): boolean => {return false}- // List of keywords that indicate write operations or function calls- const disallowedPatterns = [- // Write operations- 'insert',- 'update',- 'delete',- 'alter',- 'drop',- 'create',- 'truncate',- 'replace',- 'with',-- // Function patterns- 'function',- 'procedure',+ // List of keywords that indicate write operations+ const writeOperations = ['insert', 'update', 'delete', 'alter', 'drop', 'create', 'replace']++ // Safe read-only SQL functions+ const readOnlyFunctions = [+ 'count(',+ 'sum(',+ 'avg(',+ 'min(',+ 'max(',+ 'coalesce(',+ 'nullif(',+ 'current_timestamp',+ 'current_date',+ 'length(',+ 'lower(',+ 'upper(',+ 'trim(',+ 'substring(',+ 'to_char(',+ 'to_date(',+ 'extract(',+ 'date_trunc(',]- const allowedPatterns = ['created', 'inserted', 'updated', 'deleted']+ // Words that may appear in column names etc+ const allowedPatterns = ['created', 'inserted', 'updated', 'deleted', 'truncate']- // Check if query contains any disallowed patterns, but allow if part of allowedPatterns- return !disallowedPatterns.some((pattern) => {- // Check if the found disallowed pattern is actually part of an allowed pattern- const isPartOfAllowedPattern = allowedPatterns.some(- (allowed) => normalizedQuery.includes(allowed) && allowed.includes(pattern)+ // Check for any write operations+ const hasWriteOperation = writeOperations.some((op) => {+ // Ignore if part of allowed pattern+ const isAllowed = allowedPatterns.some(+ (allowed) => normalizedQuery.includes(allowed) && allowed.includes(op))+ return !isAllowed && normalizedQuery.includes(op)+ })++ if (hasWriteOperation) {+ return false+ }- if (isPartOfAllowedPattern) {- return false+ // Check for function calls that aren't in the safe list+ const functionCallRegex = /\w+\s*\(/g+ const functionCalls = normalizedQuery.match(functionCallRegex) || []++ for (const func of functionCalls) {+ const isReadOnlyFunc = readOnlyFunctions.some(+ (safeFunc) => func.trim().toLowerCase() === safeFunc+ )+ if (!isReadOnlyFunc) {+ return false // Unknown function call - assume not read-only}+ }- return normalizedQuery.includes(pattern)- })+ return true}const getContextKey = (pathname: string) => {diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsxindex a4e3852e65d..bcd29442f04 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx@@ -35,10 +35,11 @@ export const Message = function Message({return (<motion.divlayout="position"- initial={{ y: 5, opacity: 0, scale: 0.99 }}- animate={{ y: 0, opacity: 1, scale: 1 }}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}className={cn('mb-5 text-foreground-light text-sm',+ isUser && 'text-foreground',variant === 'warning' && 'bg-warning-200')}>diff --git a/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsx b/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsxindex 9e162427f3b..502cd0efaec 100644--- a/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsx@@ -167,7 +167,7 @@ export const SqlCard = ({}, [sql, readOnly, isLoading])return (- <div className="overflow-hidden rounded border w-auto">+ <div className="overflow-hidden rounded border w-auto bg-surface-100"><div className={cn('flex items-center gap-2', showWarning ? '' : 'px-3 pr-1 py-1')}>{showWarning ? (<Admonition type="warning" className="mb-0 rounded-none border-0">diff --git a/apps/studio/pages/api/ai/sql/generate-v3.ts b/apps/studio/pages/api/ai/sql/generate-v3.tsindex 0e4f60b6af7..50aee1ef7a6 100644--- a/apps/studio/pages/api/ai/sql/generate-v3.ts+++ b/apps/studio/pages/api/ai/sql/generate-v3.ts@@ -77,10 +77,12 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {- Output as markdown- Always include code snippets if available- If a code snippet is SQL, the first line of the snippet should always be -- props: {"title": "Query title", "isChart": "true", "xAxis": "columnOrAlias", "yAxis": "columnOrAlias"}+ - Only include one line of comment props per markdown snippet, even if the snippet has multiple queries- Only set chart to true if the query makes sense as a chart. xAxis and yAxis need to be columns or aliases returned by the query.- Explain what the snippet does in a sentence or two before showing it- Use vector(384) data type for any embedding/vector related query- When debugging, retrieve sql schema details to ensure sql is correct+ - In Supabase, the auth schema already has a users table which is used to store users. It is common practice to create a profiles table in the public schema that links to auth.users to store user information instead. You don't need to create a new users table.When generating tables, do the following:- For primary keys, always use "id bigint primary key generated always as identity" (not serial)@@ -109,8 +111,10 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {# You convert sql to supabase-js client codeUse the convertSqlToSupabaseJs tool to convert select sql to supabase-js client code. Only provide js code snippets if explicitly asked. If conversion isn't supported, build a postgres function instead and suggest using supabase-js to call it via "const { data, error } = await supabase.rpc('echo', { say: '👋'})"- Follow these instructions:- - First look at the list of provided schemas and if needed, get more information about a schema. You will almost always need to retrieve information about the public schema before answering a question. If the question is about users, also retrieve the auth schema.+ # For all your abilities, follow these instructions:+ - First look at the list of provided schemas and if needed, get more information about a schema. You will almost always need to retrieve information about the public schema before answering a question.+ - If the question is about users or involves creating a users table, also retrieve the auth schema.+Here are the existing database schema names you can retrieve: ${schemas}