The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Resolve AI opt-in and tracing settings server-side (#48855)
Ali Waseemb04d14856ab0
diff --git a/apps/studio/lib/ai/ai-details.test.ts b/apps/studio/lib/ai/ai-details.test.tsindex 6102aaf445d..56e4b61b3a2 100644--- a/apps/studio/lib/ai/ai-details.test.ts+++ b/apps/studio/lib/ai/ai-details.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { getOrgAIDetails, getProjectAIDetails } from './ai-details'+import { getAIDetails } from './ai-details'vi.mock('@/data/organizations/organizations-query', () => ({getOrganizations: vi.fn(),@@ -32,10 +32,14 @@ vi.mock('@/data/entitlements/entitlements-query', () => ({const AUTH = 'Bearer token'const HEADERS = { 'Content-Type': 'application/json', Authorization: AUTH }+const ORG_SLUG = 'test-org'+const PROJECT_REF = 'test-project'-describe('getOrgAIDetails', () => {+describe('getAIDetails', () => {let mockGetOrganizations: ReturnType<typeof vi.fn>let mockGetOrgSubscription: ReturnType<typeof vi.fn>+ let mockGetProjectDetail: ReturnType<typeof vi.fn>+ let mockGetProjectSettings: ReturnType<typeof vi.fn>let mockGetAiOptInLevel: ReturnType<typeof vi.fn>let mockSubscriptionHasHipaaAddon: ReturnType<typeof vi.fn>let mockCheckEntitlement: ReturnType<typeof vi.fn>@@ -45,6 +49,8 @@ describe('getOrgAIDetails', () => {const orgsQuery = await import('@/data/organizations/organizations-query')const subscriptionQuery = await import('@/data/subscriptions/org-subscription-query')+ const projectQuery = await import('@/data/projects/project-detail-query')+ const settingsQuery = await import('@/data/config/project-settings-v2-query')const aiHook = await import('@/hooks/misc/useOrgOptedIntoAi')const subscriptionUtils =await import('@/components/interfaces/Billing/Subscription/Subscription.utils')@@ -52,22 +58,33 @@ describe('getOrgAIDetails', () => {mockGetOrganizations = vi.mocked(orgsQuery.getOrganizations)mockGetOrgSubscription = vi.mocked(subscriptionQuery.getOrgSubscription)+ mockGetProjectDetail = vi.mocked(projectQuery.getProjectDetail)+ mockGetProjectSettings = vi.mocked(settingsQuery.getProjectSettings)mockGetAiOptInLevel = vi.mocked(aiHook.getAiOptInLevel)mockSubscriptionHasHipaaAddon = vi.mocked(subscriptionUtils.subscriptionHasHipaaAddon)mockCheckEntitlement = vi.mocked(entitlementsQuery.checkEntitlement)+ mockGetOrganizations.mockResolvedValue([+ { id: 1, slug: ORG_SLUG, plan: { id: 'pro' }, opt_in_tags: [] },+ ])+ mockGetProjectDetail.mockResolvedValue({+ ref: PROJECT_REF,+ region: 'us-east-1',+ organization_id: 1,+ })+ mockGetProjectSettings.mockResolvedValue({ is_sensitive: false })mockGetOrgSubscription.mockResolvedValue({ addons: [] })mockSubscriptionHasHipaaAddon.mockReturnValue(false)mockCheckEntitlement.mockResolvedValue({ hasAccess: false })- })-- it('returns org-level fields', async () => {- mockGetOrganizations.mockResolvedValue([- { id: 1, slug: 'test-org', plan: { id: 'pro' }, opt_in_tags: [] },- ])mockGetAiOptInLevel.mockReturnValue('schema')+ })- const result = await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })+ it('returns the resolved posture when the project belongs to the org', async () => {+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })expect(result).toEqual({aiOptInLevel: 'schema',@@ -75,132 +92,199 @@ describe('getOrgAIDetails', () => {hasHipaaAddon: false,orgId: 1,planId: 'pro',+ region: 'us-east-1',+ isSensitive: false,})})- it('returns hasAccessToAdvanceModel true when entitlement grants access', async () => {- mockGetOrganizations.mockResolvedValue([- { id: 1, slug: 'test-org', plan: { id: 'pro' }, opt_in_tags: [] },- ])- mockGetAiOptInLevel.mockReturnValue('schema')- mockCheckEntitlement.mockResolvedValue({ hasAccess: true })-- const result = await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })-- expect(result.hasAccessToAdvanceModel).toBe(true)- })-- it('returns hasHipaaAddon from subscription', async () => {- mockGetOrganizations.mockResolvedValue([- { id: 1, slug: 'test-org', plan: { id: 'enterprise' }, opt_in_tags: [] },- ])- mockGetAiOptInLevel.mockReturnValue('schema')- mockSubscriptionHasHipaaAddon.mockReturnValue(true)-- const result = await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })-- expect(result.hasHipaaAddon).toBe(true)- })-it('calls getAiOptInLevel with the matched org opt_in_tags', async () => {const opt_in_tags = ['AI_SQL_GENERATOR_OPT_IN']mockGetOrganizations.mockResolvedValue([- { id: 1, slug: 'test-org', plan: { id: 'pro' }, opt_in_tags },+ { id: 1, slug: ORG_SLUG, plan: { id: 'pro' }, opt_in_tags },])- mockGetAiOptInLevel.mockReturnValue('schema')- await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })+ await getAIDetails({ orgSlug: ORG_SLUG, projectRef: PROJECT_REF, authorization: AUTH })expect(mockGetAiOptInLevel).toHaveBeenCalledWith(opt_in_tags)})- it('forwards authorization headers to all fetches', async () => {- mockGetOrganizations.mockResolvedValue([- { id: 1, slug: 'test-org', plan: { id: 'pro' }, opt_in_tags: [] },- ])- mockGetAiOptInLevel.mockReturnValue('schema')+ it('returns hasAccessToAdvanceModel true when the entitlement grants access', async () => {+ mockCheckEntitlement.mockResolvedValue({ hasAccess: true })- await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })- expect(mockGetOrganizations).toHaveBeenCalledWith({ headers: HEADERS })- expect(mockGetOrgSubscription).toHaveBeenCalledWith({ orgSlug: 'test-org' }, undefined, HEADERS)+ expect(result.hasAccessToAdvanceModel).toBe(true)})it('finds the correct org when multiple orgs are returned', async () => {mockGetOrganizations.mockResolvedValue([{ id: 1, slug: 'org-1', plan: { id: 'free' }, opt_in_tags: [] },- { id: 2, slug: 'test-org', plan: { id: 'pro' }, opt_in_tags: [] },+ { id: 2, slug: ORG_SLUG, plan: { id: 'pro' }, opt_in_tags: [] },])- mockGetAiOptInLevel.mockReturnValue('schema')+ mockGetProjectDetail.mockResolvedValue({+ ref: PROJECT_REF,+ region: 'us-east-1',+ organization_id: 2,+ })- const result = await getOrgAIDetails({ orgSlug: 'test-org', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })expect(result.orgId).toBe(2)expect(result.planId).toBe('pro')})-})-describe('getProjectAIDetails', () => {- let mockGetProjectDetail: ReturnType<typeof vi.fn>- let mockGetProjectSettings: ReturnType<typeof vi.fn>+ it('forwards authorization headers to all fetches', async () => {+ await getAIDetails({ orgSlug: ORG_SLUG, projectRef: PROJECT_REF, authorization: AUTH })- beforeEach(async () => {- vi.clearAllMocks()+ expect(mockGetOrganizations).toHaveBeenCalledWith({ headers: HEADERS })+ expect(mockGetOrgSubscription).toHaveBeenCalledWith({ orgSlug: ORG_SLUG }, undefined, HEADERS)+ expect(mockCheckEntitlement).toHaveBeenCalledWith(+ ORG_SLUG,+ 'assistant.advance_model',+ undefined,+ HEADERS+ )+ expect(mockGetProjectDetail).toHaveBeenCalledWith(+ { ref: PROJECT_REF, skipWake: true },+ undefined,+ HEADERS+ )+ expect(mockGetProjectSettings).toHaveBeenCalledWith(+ { projectRef: PROJECT_REF },+ undefined,+ HEADERS+ )+ })- const projectQuery = await import('@/data/projects/project-detail-query')- const settingsQuery = await import('@/data/config/project-settings-v2-query')+ describe('when the project does not belong to the org', () => {+ beforeEach(() => {+ mockGetOrganizations.mockResolvedValue([+ { id: 1, slug: ORG_SLUG, plan: { id: 'pro' }, opt_in_tags: ['AI_SQL_GENERATOR_OPT_IN'] },+ { id: 2, slug: 'other-org', plan: { id: 'free' }, opt_in_tags: [] },+ ])+ mockGetProjectDetail.mockResolvedValue({+ ref: PROJECT_REF,+ region: 'us-east-1',+ organization_id: 2,+ })+ mockGetAiOptInLevel.mockReturnValue('schema_and_log_and_data')+ mockCheckEntitlement.mockResolvedValue({ hasAccess: true })+ })- mockGetProjectDetail = vi.mocked(projectQuery.getProjectDetail)- mockGetProjectSettings = vi.mocked(settingsQuery.getProjectSettings)- })+ it('falls back to the most restrictive posture', async () => {+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })++ expect(result.aiOptInLevel).toBe('disabled')+ expect(result.hasAccessToAdvanceModel).toBe(false)+ expect(result.orgId).toBeUndefined()+ expect(result.planId).toBeUndefined()+ })- it('returns region and isSensitive', async () => {- mockGetProjectDetail.mockResolvedValue({ ref: 'test-project', region: 'us-east-1' })- mockGetProjectSettings.mockResolvedValue({ is_sensitive: false })+ it('leaves hasHipaaAddon undefined so tracing checks fail closed', async () => {+ mockSubscriptionHasHipaaAddon.mockReturnValue(false)- const result = await getProjectAIDetails({ projectRef: 'test-project', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })- expect(result).toEqual({ region: 'us-east-1', isSensitive: false })+ expect(result.hasHipaaAddon).toBeUndefined()+ })})- it('returns isSensitive true when project is marked sensitive', async () => {- mockGetProjectDetail.mockResolvedValue({ ref: 'test-project', region: 'us-east-1' })- mockGetProjectSettings.mockResolvedValue({ is_sensitive: true })+ it('falls back to the most restrictive posture when the org slug matches no org', async () => {+ mockGetOrganizations.mockResolvedValue([])- const result = await getProjectAIDetails({ projectRef: 'test-project', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })- expect(result.isSensitive).toBe(true)+ expect(result.aiOptInLevel).toBe('disabled')+ expect(result.orgId).toBeUndefined()})- it('returns isSensitive undefined when project settings are unavailable', async () => {- mockGetProjectDetail.mockResolvedValue({ ref: 'test-project', region: 'us-east-1' })- mockGetProjectSettings.mockResolvedValue(undefined)+ it('falls back to the most restrictive posture when project detail is unavailable', async () => {+ mockGetProjectDetail.mockResolvedValue(undefined)- const result = await getProjectAIDetails({ projectRef: 'test-project', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })- expect(result.isSensitive).toBeUndefined()+ expect(result.aiOptInLevel).toBe('disabled')+ expect(result.region).toBeUndefined()})- it('returns region undefined when project detail is unavailable', async () => {- mockGetProjectDetail.mockResolvedValue(undefined)- mockGetProjectSettings.mockResolvedValue({ is_sensitive: false })+ describe('HIPAA organizations', () => {+ beforeEach(() => {+ mockSubscriptionHasHipaaAddon.mockReturnValue(true)+ mockGetAiOptInLevel.mockReturnValue('schema_and_log_and_data')+ })- const result = await getProjectAIDetails({ projectRef: 'test-project', authorization: AUTH })+ it('disables the opt-in level for a sensitive project', async () => {+ mockGetProjectSettings.mockResolvedValue({ is_sensitive: true })- expect(result.region).toBeUndefined()+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })++ expect(result.aiOptInLevel).toBe('disabled')+ expect(result.hasHipaaAddon).toBe(true)+ })++ it('disables the opt-in level when project sensitivity is unknown', async () => {+ mockGetProjectSettings.mockResolvedValue(undefined)++ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })++ expect(result.aiOptInLevel).toBe('disabled')+ })++ it('keeps the opt-in level for a project explicitly marked not sensitive', async () => {+ mockGetProjectSettings.mockResolvedValue({ is_sensitive: false })++ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })++ expect(result.aiOptInLevel).toBe('schema_and_log_and_data')+ })})- it('forwards authorization headers to all fetches', async () => {- mockGetProjectDetail.mockResolvedValue({ ref: 'test-project', region: 'us-east-1' })- mockGetProjectSettings.mockResolvedValue({ is_sensitive: false })+ it('keeps the opt-in level for a sensitive project outside a HIPAA org', async () => {+ mockSubscriptionHasHipaaAddon.mockReturnValue(false)+ mockGetProjectSettings.mockResolvedValue({ is_sensitive: true })- await getProjectAIDetails({ projectRef: 'test-project', authorization: AUTH })+ const result = await getAIDetails({+ orgSlug: ORG_SLUG,+ projectRef: PROJECT_REF,+ authorization: AUTH,+ })- expect(mockGetProjectDetail).toHaveBeenCalledWith({ ref: 'test-project' }, undefined, HEADERS)- expect(mockGetProjectSettings).toHaveBeenCalledWith(- { projectRef: 'test-project' },- undefined,- HEADERS- )+ expect(result.aiOptInLevel).toBe('schema')})})diff --git a/apps/studio/lib/ai/ai-details.ts b/apps/studio/lib/ai/ai-details.tsindex 026fd852b5b..be61660368d 100644--- a/apps/studio/lib/ai/ai-details.ts+++ b/apps/studio/lib/ai/ai-details.ts@@ -4,56 +4,76 @@ import { checkEntitlement } from '@/data/entitlements/entitlements-query'import { getOrganizations } from '@/data/organizations/organizations-query'import { getProjectDetail } from '@/data/projects/project-detail-query'import { getOrgSubscription } from '@/data/subscriptions/org-subscription-query'-import { getAiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'+import { getAiOptInLevel, type AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'-export const getOrgAIDetails = async ({+export type AIDetails = {+ aiOptInLevel: AiOptInLevel+ hasAccessToAdvanceModel: boolean+ hasHipaaAddon: boolean | undefined+ orgId: number | undefined+ planId: string | undefined+ region: string | undefined+ isSensitive: boolean | null | undefined+}++// Resolves the AI opt-in level, model access and tracing inputs for one org/project pair.+// Both identifiers come from the request body, so an unconfirmed pairing resolves to the+// most restrictive posture rather than the requested one.+export const getAIDetails = async ({orgSlug,+ projectRef,authorization,}: {orgSlug: string+ projectRef: stringauthorization: string-}) => {+}): Promise<AIDetails> => {const headers = {'Content-Type': 'application/json',...(authorization && { Authorization: authorization }),}- const [organizations, subscription, advanceModelAccess] = await Promise.all([- getOrganizations({ headers }),- getOrgSubscription({ orgSlug }, undefined, headers),- checkEntitlement(orgSlug, 'assistant.advance_model', undefined, headers),- ])+ const [organizations, subscription, advanceModelAccess, project, projectSettings] =+ await Promise.all([+ getOrganizations({ headers }),+ getOrgSubscription({ orgSlug }, undefined, headers),+ checkEntitlement(orgSlug, 'assistant.advance_model', undefined, headers),+ // skipWake: only organization_id and region are needed, neither requires a running project+ getProjectDetail({ ref: projectRef, skipWake: true }, undefined, headers),+ getProjectSettings({ projectRef }, undefined, headers),+ ])const selectedOrg = organizations.find((org) => org.slug === orgSlug)+ const region = project?.region+ const isSensitive = projectSettings?.is_sensitive- return {- aiOptInLevel: getAiOptInLevel(selectedOrg?.opt_in_tags),- hasAccessToAdvanceModel: advanceModelAccess.hasAccess,- hasHipaaAddon: subscriptionHasHipaaAddon(subscription),- orgId: selectedOrg?.id,- planId: selectedOrg?.plan.id,- }-}+ const isProjectInOrg = selectedOrg !== undefined && project?.organization_id === selectedOrg.id-export const getProjectAIDetails = async ({- projectRef,- authorization,-}: {- projectRef: string- authorization: string-}) => {- const headers = {- 'Content-Type': 'application/json',- ...(authorization && { Authorization: authorization }),+ if (!isProjectInOrg) {+ return {+ aiOptInLevel: 'disabled',+ hasAccessToAdvanceModel: false,+ // Undefined rather than false so isTracingAllowed fails closed+ hasHipaaAddon: undefined,+ orgId: undefined,+ planId: undefined,+ region,+ isSensitive,+ }}- const [selectedProject, projectSettings] = await Promise.all([- getProjectDetail({ ref: projectRef }, undefined, headers),- getProjectSettings({ projectRef }, undefined, headers),- ])+ const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)++ // Mirrors the client-side gate in useOrgAiOptInLevel, which had no server-side equivalent+ const isRestrictedByHipaa = hasHipaaAddon && isSensitive !== falsereturn {- region: selectedProject?.region,- isSensitive: projectSettings?.is_sensitive,+ aiOptInLevel: isRestrictedByHipaa ? 'disabled' : getAiOptInLevel(selectedOrg.opt_in_tags),+ hasAccessToAdvanceModel: advanceModelAccess.hasAccess,+ hasHipaaAddon,+ orgId: selectedOrg.id,+ planId: selectedOrg.plan.id,+ region,+ isSensitive,}}diff --git a/apps/studio/lib/api/generate-v4.test.ts b/apps/studio/lib/api/generate-v4.test.tsindex e7326ca57d0..5fa54d62980 100644--- a/apps/studio/lib/api/generate-v4.test.ts+++ b/apps/studio/lib/api/generate-v4.test.ts@@ -48,11 +48,10 @@ test('generateV4 calls the tool sanitizer', async () => {}vi.mock('@/lib/ai/ai-details', () => ({- getOrgAIDetails: vi.fn().mockResolvedValue({+ getAIDetails: vi.fn().mockResolvedValue({aiOptInLevel: 'schema_and_log_and_data',hasAccessToAdvanceModel: true,- }),- getProjectAIDetails: vi.fn().mockResolvedValue({+ hasHipaaAddon: false,region: 'us-east-1',isSensitive: false,}),diff --git a/apps/studio/lib/api/rate.test.ts b/apps/studio/lib/api/rate.test.tsindex cb6b55b13d8..37347234c5d 100644--- a/apps/studio/lib/api/rate.test.ts+++ b/apps/studio/lib/api/rate.test.ts@@ -44,12 +44,10 @@ test('rate calls the tool sanitizer', async () => {}vi.mock('@/lib/ai/ai-details', () => ({- getOrgAIDetails: vi.fn().mockResolvedValue({+ getAIDetails: vi.fn().mockResolvedValue({aiOptInLevel: 'schema_and_log_and_data',hasAccessToAdvanceModel: true,- isDpaSigned: false,- }),- getProjectAIDetails: vi.fn().mockResolvedValue({+ hasHipaaAddon: false,region: 'us-east-1',isSensitive: false,}),diff --git a/apps/studio/pages/api/ai/code/complete.ts b/apps/studio/pages/api/ai/code/complete.tsindex 84b9eff76b6..a4b9ff7f20c 100644--- a/apps/studio/pages/api/ai/code/complete.ts+++ b/apps/studio/pages/api/ai/code/complete.ts@@ -7,7 +7,7 @@ import z from 'zod'import { executeSql } from '@/data/sql/execute-sql-mutation'import { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'-import { getOrgAIDetails } from '@/lib/ai/ai-details'+import { getAIDetails } from '@/lib/ai/ai-details'import {buildClickhouseLogsSchemaSection,CLICKHOUSE_LOGS_COMPLETION_INSTRUCTIONS,@@ -176,11 +176,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {let aiOptInLevel: AiOptInLevel = IS_PLATFORM ? 'disabled' : 'schema'if (IS_PLATFORM && orgSlug && authorization && projectRef) {- const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({- orgSlug,- authorization,- })- aiOptInLevel = orgAIOptInLevel+ const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })+ aiOptInLevel = aiDetails.aiOptInLevel}const {diff --git a/apps/studio/pages/api/ai/feedback/rate.ts b/apps/studio/pages/api/ai/feedback/rate.tsindex 9842828342b..8483d4de15d 100644--- a/apps/studio/pages/api/ai/feedback/rate.ts+++ b/apps/studio/pages/api/ai/feedback/rate.ts@@ -6,7 +6,7 @@ import { z } from 'zod'import { rateMessageResponseSchema } from '@/components/ui/AIAssistantPanel/Message.utils'import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'-import { getOrgAIDetails, getProjectAIDetails } from '@/lib/ai/ai-details'+import { getAIDetails } from '@/lib/ai/ai-details'import { IS_TRACING_ENABLED, isTracingAllowed } from '@/lib/ai/braintrust-logger'import { getModel } from '@/lib/ai/model'import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'@@ -56,7 +56,7 @@ export async function handlePost(req: NextApiRequest, res: NextApiResponse) {let aiOptInLevel: AiOptInLevel = 'disabled'let orgHasHipaaAddon: boolean | undefined- let projectIsSensitive: boolean | undefined+ let projectIsSensitive: boolean | null | undefinedlet projectRegion: string | undefinedif (!IS_PLATFORM) {@@ -65,15 +65,12 @@ export async function handlePost(req: NextApiRequest, res: NextApiResponse) {if (IS_PLATFORM && orgSlug && authorization && projectRef) {try {- const [orgDetails, projectDetails] = await Promise.all([- getOrgAIDetails({ orgSlug, authorization }),- getProjectAIDetails({ projectRef, authorization }),- ])-- aiOptInLevel = orgDetails.aiOptInLevel- orgHasHipaaAddon = orgDetails.hasHipaaAddon- projectIsSensitive = projectDetails.isSensitive- projectRegion = projectDetails.region+ const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })++ aiOptInLevel = aiDetails.aiOptInLevel+ orgHasHipaaAddon = aiDetails.hasHipaaAddon+ projectIsSensitive = aiDetails.isSensitive+ projectRegion = aiDetails.region} catch (error) {return res.status(400).json({error: 'There was an error fetching your organization details',diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.tsindex 5535ce02c60..407131986eb 100644--- a/apps/studio/pages/api/ai/sql/generate-v4.ts+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts@@ -7,7 +7,7 @@ import z from 'zod'import { executeSql } from '@/data/sql/execute-sql-mutation'import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'-import { getOrgAIDetails, getProjectAIDetails } from '@/lib/ai/ai-details'+import { getAIDetails } from '@/lib/ai/ai-details'import { NO_SCHEMA_ACCESS_MESSAGE } from '@/lib/ai/assistant-context'import {assistantMessageMetadataSchema,@@ -120,7 +120,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jwlet aiOptInLevel: AiOptInLevel = 'disabled'let hasAccessToAdvanceModel = falselet orgHasHipaaAddon: boolean | undefined- let projectIsSensitive: boolean | undefined+ let projectIsSensitive: boolean | null | undefinedlet projectRegion: string | undefinedlet orgId: number | undefinedlet planId: string | undefined@@ -132,18 +132,15 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jwif (IS_PLATFORM && orgSlug && authorization && projectRef) {try {- const [orgDetails, projectDetails] = await Promise.all([- getOrgAIDetails({ orgSlug, authorization }),- getProjectAIDetails({ projectRef, authorization }),- ])-- aiOptInLevel = orgDetails.aiOptInLevel- hasAccessToAdvanceModel = orgDetails.hasAccessToAdvanceModel- orgHasHipaaAddon = orgDetails.hasHipaaAddon- orgId = orgDetails.orgId- planId = orgDetails.planId- projectIsSensitive = projectDetails.isSensitive- projectRegion = projectDetails.region+ const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })++ aiOptInLevel = aiDetails.aiOptInLevel+ hasAccessToAdvanceModel = aiDetails.hasAccessToAdvanceModel+ orgHasHipaaAddon = aiDetails.hasHipaaAddon+ orgId = aiDetails.orgId+ planId = aiDetails.planId+ projectIsSensitive = aiDetails.isSensitive+ projectRegion = aiDetails.region} catch (error) {return res.status(400).json({error: 'There was an error fetching your organization details',diff --git a/apps/studio/pages/api/ai/sql/policy.ts b/apps/studio/pages/api/ai/sql/policy.tsindex c5d6e40cd1f..f394b534b3b 100644--- a/apps/studio/pages/api/ai/sql/policy.ts+++ b/apps/studio/pages/api/ai/sql/policy.ts@@ -5,7 +5,7 @@ import { NextApiRequest, NextApiResponse } from 'next'import { z } from 'zod'import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'-import { getOrgAIDetails } from '@/lib/ai/ai-details'+import { getAIDetails } from '@/lib/ai/ai-details'import { getModel } from '@/lib/ai/model'import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'import { RLS_PROMPT } from '@/lib/ai/prompts'@@ -75,14 +75,11 @@ export async function handlePost(req: NextApiRequest, res: NextApiResponse) {aiOptInLevel = 'schema'}- if (IS_PLATFORM && orgSlug && authorization) {+ if (IS_PLATFORM && orgSlug && authorization && projectRef) {try {- const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({- orgSlug,- authorization,- })+ const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })- aiOptInLevel = orgAIOptInLevel+ aiOptInLevel = aiDetails.aiOptInLevel} catch (error) {return res.status(400).json({error: 'There was an error fetching your organization details',