Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

opt in tags (#36885)

Terry Sutton4d15119c2982
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index c7704c870c9..72383a6e61f 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -1,6 +1,5 @@
import type { Message as MessageType } from 'ai/react'
import { useChat } from 'ai/react'
-
import { AnimatePresence, motion } from 'framer-motion'
import { ArrowDown, FileText, Info, RefreshCw, X } from 'lucide-react'
import { useRouter } from 'next/router'
@@ -199,6 +198,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
includeSchemaMetadata: !useBedrockAssistant
? !IS_PLATFORM || aiOptInLevel !== 'disabled'
: undefined,
+ orgSlug: selectedOrganization?.slug,
})
},
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
diff --git a/apps/studio/data/organizations/organizations-query.ts b/apps/studio/data/organizations/organizations-query.ts
index 85f32ab775c..1e6b8d1c35d 100644
--- a/apps/studio/data/organizations/organizations-query.ts
+++ b/apps/studio/data/organizations/organizations-query.ts
@@ -17,8 +17,14 @@ export function castOrganizationResponseToOrganization(org: OrganizationBase): O
}
}
-export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {
- const { data, error } = await get('/platform/organizations', { signal })
+export async function getOrganizations({
+ signal,
+ headers,
+}: {
+ signal?: AbortSignal
+ headers?: Record<string, string>
+}): Promise<Organization[]> {
+ const { data, error } = await get('/platform/organizations', { signal, headers })
if (error) handleError(error)
if (!Array.isArray(data)) return []
@@ -38,7 +44,7 @@ export const useOrganizationsQuery = <TData = OrganizationsData>({
const { profile } = useProfile()
return useQuery<OrganizationsData, OrganizationsError, TData>(
organizationKeys.list(),
- ({ signal }) => getOrganizations(signal),
+ ({ signal }) => getOrganizations({ signal }),
{ enabled: enabled && profile !== undefined, ...options, staleTime: 30 * 60 * 1000 }
)
}
diff --git a/apps/studio/data/projects/projects-query.ts b/apps/studio/data/projects/projects-query.ts
index 3cf64b8c422..5059f538adf 100644
--- a/apps/studio/data/projects/projects-query.ts
+++ b/apps/studio/data/projects/projects-query.ts
@@ -14,8 +14,14 @@ export type ProjectsVariables = {
export type ProjectInfo = components['schemas']['ProjectInfo']
-export async function getProjects(signal?: AbortSignal) {
- const { data, error } = await get('/platform/projects', { signal })
+export async function getProjects({
+ signal,
+ headers,
+}: {
+ signal?: AbortSignal
+ headers?: Record<string, string>
+}) {
+ const { data, error } = await get('/platform/projects', { signal, headers })
if (error) handleError(error)
return data as ProjectInfo[]
@@ -31,7 +37,7 @@ export const useProjectsQuery = <TData = ProjectsData>({
const { profile } = useProfile()
return useQuery<ProjectsData, ProjectsError, TData>(
projectKeys.list(),
- ({ signal }) => getProjects(signal),
+ ({ signal }) => getProjects({ signal }),
{
enabled: enabled && profile !== undefined,
staleTime: 30 * 60 * 1000, // 30 minutes
@@ -41,7 +47,7 @@ export const useProjectsQuery = <TData = ProjectsData>({
}
export function prefetchProjects(client: QueryClient) {
- return client.prefetchQuery(projectKeys.list(), ({ signal }) => getProjects(signal))
+ return client.prefetchQuery(projectKeys.list(), ({ signal }) => getProjects({ signal }))
}
export function useProjectsPrefetch() {
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index 820fbba3f9e..862bd19d8f7 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -1,13 +1,15 @@
import pgMeta from '@supabase/pg-meta'
+import { streamText, tool, ToolSet } from 'ai'
+import { source } from 'common-tags'
import crypto from 'crypto'
import { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
-import { streamText, tool, ToolSet } from 'ai'
import { IS_PLATFORM } from 'common'
-import { source } from 'common-tags'
+import { getOrganizations } from 'data/organizations/organizations-query'
+import { getProjects } from 'data/projects/projects-query'
import { executeSql } from 'data/sql/execute-sql-query'
-import { aiOptInLevelSchema } from 'hooks/misc/useOrgOptedIntoAi'
+import { getAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'
import { getModel } from 'lib/ai/model'
import apiWrapper from 'lib/api/apiWrapper'
import { queryPgMetaSelfHosted } from 'lib/self-hosted'
@@ -45,10 +47,10 @@ export default wrapper
const requestBodySchema = z.object({
messages: z.array(z.any()),
projectRef: z.string(),
- aiOptInLevel: aiOptInLevelSchema,
connectionString: z.string(),
schema: z.string().optional(),
table: z.string().optional(),
+ orgSlug: z.string().optional(),
})
async function handlePost(req: NextApiRequest, res: NextApiResponse) {
@@ -66,7 +68,33 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
}
- const { messages, projectRef, connectionString, aiOptInLevel } = data
+ const { messages, projectRef, connectionString, orgSlug } = data
+
+ // Get organizations and compute opt in level server-side
+ const [organizations, projects] = await Promise.all([
+ getOrganizations({
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(authorization && { Authorization: authorization }),
+ },
+ }),
+ getProjects({
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(authorization && { Authorization: authorization }),
+ },
+ }),
+ ])
+
+ const selectedOrg = organizations.find((org) => org.slug === orgSlug)
+ const selectedProject = projects.find((project) => project.ref === projectRef)
+
+ // If the project is not in the organization specific by the org slug, return an error
+ if (selectedProject?.organization_slug !== selectedOrg?.slug) {
+ return res.status(400).json({ error: 'Project and organization do not match' })
+ }
+
+ const aiOptInLevel = getAiOptInLevel(selectedOrg?.opt_in_tags)
const { model, error: modelError } = await getModel(projectRef) // use project ref as routing key