Skip to content

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

feat: add new command menu to studio (#28432)

Charis84732ff44c84
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
new file mode 100644
index 00000000000..a3c3f2909a8
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
@@ -0,0 +1,111 @@
+import { Key } from 'lucide-react'
+import { useMemo } from 'react'
+
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { copyToClipboard } from 'lib/helpers'
+import { Badge } from 'ui'
+import type { ICommand } from 'ui-patterns/CommandMenu'
+import {
+ PageType,
+ useRegisterCommands,
+ useRegisterPage,
+ useSetCommandMenuOpen,
+ useSetPage,
+} from 'ui-patterns/CommandMenu'
+import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
+import { orderCommandSectionsByPriority } from './ordering'
+
+const API_KEYS_PAGE_NAME = 'API Keys'
+
+export function useApiKeysCommands() {
+ const setIsOpen = useSetCommandMenuOpen()
+ const setPage = useSetPage()
+
+ const project = useSelectedProject()
+ const { data: settings } = useProjectApiQuery(
+ { projectRef: project?.ref },
+ { enabled: !!project }
+ )
+ const ref = project?.ref || '_'
+
+ const anonKey = settings?.autoApiService?.defaultApiKey ?? undefined
+ const serviceKey = settings?.autoApiService?.serviceApiKey ?? undefined
+
+ const commands = useMemo(
+ () =>
+ [
+ project &&
+ anonKey && {
+ id: 'anon-key',
+ name: `Copy anonymous API key`,
+ action: () => {
+ copyToClipboard(anonKey ?? '')
+ setIsOpen(false)
+ },
+ badge: () => (
+ <span className="flex items-center gap-2">
+ <Badge>Project: {project?.name}</Badge>
+ <Badge>Public</Badge>
+ </span>
+ ),
+ icon: () => <Key />,
+ },
+ project &&
+ serviceKey && {
+ id: 'service-key',
+ name: `Copy service API key`,
+ action: () => {
+ copyToClipboard(serviceKey ?? '')
+ setIsOpen(false)
+ },
+ badge: () => (
+ <span className="flex items-center gap-2">
+ <Badge>Project: {project?.name}</Badge>
+ <Badge variant="destructive">Secret</Badge>
+ </span>
+ ),
+ icon: () => <Key />,
+ },
+ !(anonKey || serviceKey) && {
+ id: 'api-keys-project-settings',
+ name: 'See API keys in Project Settings',
+ route: `/project/${ref}/settings/api`,
+ icon: () => <Key />,
+ },
+ ].filter(Boolean) as ICommand[],
+ [anonKey, serviceKey, project, setIsOpen]
+ )
+
+ useRegisterPage(
+ API_KEYS_PAGE_NAME,
+ {
+ type: PageType.Commands,
+ sections: [
+ {
+ id: 'api-keys',
+ name: 'API keys',
+ commands,
+ },
+ ],
+ },
+ { deps: [commands], enabled: !!project }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.ACTIONS,
+ [
+ {
+ id: 'api-keys',
+ name: 'Get API keys',
+ action: () => setPage(API_KEYS_PAGE_NAME),
+ icon: () => <Key />,
+ },
+ ],
+ {
+ enabled: !!project,
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 3 },
+ }
+ )
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx b/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx
new file mode 100644
index 00000000000..28b36682981
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx
@@ -0,0 +1,45 @@
+import { Link } from 'lucide-react'
+
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { copyToClipboard } from 'lib/helpers'
+import { Badge } from 'ui'
+import { useRegisterCommands, useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
+import { orderCommandSectionsByPriority } from './ordering'
+
+export function useApiUrlCommand() {
+ const setIsOpen = useSetCommandMenuOpen()
+
+ const project = useSelectedProject()
+ const { data: settings } = useProjectApiQuery(
+ { projectRef: project?.ref },
+ { enabled: !!project }
+ )
+
+ const apiUrl = settings?.autoApiService.endpoint
+ ? `${settings.autoApiService.protocol ?? 'https'}://${settings.autoApiService.endpoint}`
+ : undefined
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.ACTIONS,
+ [
+ {
+ id: 'api-url',
+ name: 'Copy API URL',
+ action: () => {
+ copyToClipboard(apiUrl ?? '')
+ setIsOpen(false)
+ },
+ icon: () => <Link />,
+ badge: () => <Badge>Project: {project?.name}</Badge>,
+ },
+ ],
+ {
+ enabled: !!project,
+ deps: [apiUrl, project],
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 3 },
+ }
+ )
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx
new file mode 100644
index 00000000000..c8ef4b0084d
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx
@@ -0,0 +1,41 @@
+import { IS_PLATFORM } from 'common'
+import { useBranchCommands } from 'components/interfaces/BranchManagement/Branch.Commands'
+import { useGenerateSqlCommand } from 'components/interfaces/SqlGenerator/SqlGenerator.Commands'
+import { useLayoutNavCommands } from 'components/layouts/useLayoutNavCommands'
+import { CommandHeader, CommandInput, CommandList, CommandMenu } from 'ui-patterns/CommandMenu'
+import { useChangelogCommand } from 'ui-patterns/CommandMenu/prepackaged/Changelog'
+import { useDocsAiCommands } from 'ui-patterns/CommandMenu/prepackaged/DocsAi'
+import { useDocsSearchCommands } from 'ui-patterns/CommandMenu/prepackaged/DocsSearch'
+import { useThemeSwitcherCommands } from 'ui-patterns/CommandMenu/prepackaged/ThemeSwitcher'
+import { useApiKeysCommands } from './ApiKeys'
+import { useApiUrlCommand } from './ApiUrl'
+import { useProjectSwitchCommand } from './ProjectSwitcher'
+import { useSupportCommands } from './Support'
+import { orderCommandSectionsByPriority } from './ordering'
+
+export default function StudioCommandMenu() {
+ useGenerateSqlCommand()
+ useApiKeysCommands()
+ useApiUrlCommand()
+ useProjectSwitchCommand()
+ useBranchCommands()
+ useLayoutNavCommands()
+ useDocsSearchCommands({
+ options: { orderSection: orderCommandSectionsByPriority, sectionMeta: { priority: 3 } },
+ })
+ useDocsAiCommands({
+ options: { orderSection: orderCommandSectionsByPriority, sectionMeta: { priority: 3 } },
+ })
+ useSupportCommands()
+ useChangelogCommand({ enabled: IS_PLATFORM })
+ useThemeSwitcherCommands()
+
+ return (
+ <CommandMenu>
+ <CommandHeader>
+ <CommandInput />
+ </CommandHeader>
+ <CommandList />
+ </CommandMenu>
+ )
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts
new file mode 100644
index 00000000000..c80a091d2e6
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts
@@ -0,0 +1,6 @@
+export const COMMAND_MENU_SECTIONS = {
+ ACTIONS: 'Actions',
+ NAVIGATE: 'Navigate',
+ QUERY: 'Query',
+ SUPPORT: 'Support',
+} as const
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ProjectSwitcher.tsx b/apps/studio/components/interfaces/App/CommandMenu/ProjectSwitcher.tsx
new file mode 100644
index 00000000000..2a66f978b91
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/ProjectSwitcher.tsx
@@ -0,0 +1,54 @@
+import { Forward, Wrench } from 'lucide-react'
+import { useMemo } from 'react'
+
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { PageType, useRegisterCommands, useRegisterPage, useSetPage } from 'ui-patterns/CommandMenu'
+import { IS_PLATFORM } from 'common'
+import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
+
+const PROJECT_SWITCHER_PAGE_NAME = 'Switch project'
+
+export function useProjectSwitchCommand() {
+ const setPage = useSetPage()
+
+ const { data: _projects } = useProjectsQuery({ enabled: IS_PLATFORM })
+ const projects = useMemo(
+ () => (_projects ?? []).map(({ name, ref }) => ({ name, ref })),
+ [_projects]
+ )
+
+ useRegisterPage(
+ PROJECT_SWITCHER_PAGE_NAME,
+ {
+ type: PageType.Commands,
+ sections: [
+ {
+ id: 'switch-project',
+ name: 'Switch project',
+ commands: projects.map(({ name, ref }) => ({
+ id: `project-${ref}`,
+ name,
+ value: `${name} (${ref})`,
+ route: `/project/${ref}`,
+ icon: () => <Forward />,
+ })),
+ },
+ ],
+ },
+ { deps: [projects], enabled: !!projects && projects.length > 0 }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.ACTIONS,
+ [
+ {
+ id: 'switch-project',
+ name: 'Switch project',
+ value: 'Switch project, Change project, Select project',
+ action: () => setPage(PROJECT_SWITCHER_PAGE_NAME),
+ icon: () => <Wrench />,
+ },
+ ],
+ { enabled: !!projects && projects.length > 0 }
+ )
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/Support.tsx b/apps/studio/components/interfaces/App/CommandMenu/Support.tsx
new file mode 100644
index 00000000000..771bb9d39f7
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/Support.tsx
@@ -0,0 +1,41 @@
+import { LifeBuoy } from 'lucide-react'
+import { useMemo } from 'react'
+
+import { IS_PLATFORM } from 'common'
+import type { ICommand } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
+
+const useSupportCommands = () => {
+ const commands = useMemo(
+ () =>
+ [
+ {
+ id: 'support',
+ name: 'Support',
+ route: 'https://www.supabase.com/support',
+ icon: () => <LifeBuoy />,
+ },
+ {
+ id: 'system-status',
+ name: 'System Status',
+ value: 'Support: System Status',
+ route: 'https://status.supabase.com',
+ icon: () => <LifeBuoy />,
+ },
+ {
+ id: 'github-discussions',
+ name: 'GitHub Discussions',
+ value: 'Support: GitHub Discussions',
+ route: 'https://github.com/orgs/supabase/discussions',
+ icon: () => <LifeBuoy />,
+ defaultHidden: true,
+ },
+ ] as Array<ICommand>,
+ []
+ )
+
+ useRegisterCommands(COMMAND_MENU_SECTIONS.SUPPORT, commands, { enabled: IS_PLATFORM })
+}
+
+export { useSupportCommands }
diff --git a/apps/studio/components/interfaces/App/CommandMenu/index.tsx b/apps/studio/components/interfaces/App/CommandMenu/index.tsx
new file mode 100644
index 00000000000..1bcc911aac2
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/index.tsx
@@ -0,0 +1,12 @@
+import dynamic from 'next/dynamic'
+
+import { useCommandMenuInitiated } from 'ui-patterns/CommandMenu'
+
+const LazyCommandMenu = dynamic(() => import('./CommandMenu'), { ssr: false })
+
+const StudioCommandMenu = () => {
+ const isInitiated = useCommandMenuInitiated()
+ return isInitiated && <LazyCommandMenu />
+}
+
+export { StudioCommandMenu }
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ordering.ts b/apps/studio/components/interfaces/App/CommandMenu/ordering.ts
new file mode 100644
index 00000000000..b4fa9506f9c
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/ordering.ts
@@ -0,0 +1,21 @@
+import type { ICommandSection } from 'ui-patterns/CommandMenu/internal/CommandSection'
+
+const DEFAULT_PRIORITY = 10
+
+/**
+ * Order sections in the command menu by a numbered priority. The lower the
+ * number, the higher the priority.
+ *
+ * Specify the priority when creating or updating the section by passing the
+ * option `{ sectionMeta: { priority: number } }`.
+ *
+ * The priority rankings are roughly as follows:
+ * 1. Super important, stick to top. Reserved for special cases.
+ * 2. We want to highlight this and encourage people to use it.
+ * 3. Easy access for most important features/commands.
+ */
+export function orderCommandSectionsByPriority(sections: Array<ICommandSection>) {
+ return sections
+ .slice()
+ .sort((a, b) => (a.meta?.priority ?? DEFAULT_PRIORITY) - (b.meta?.priority ?? DEFAULT_PRIORITY))
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenuWrapper.tsx b/apps/studio/components/interfaces/App/CommandMenuWrapper.tsx
deleted file mode 100644
index 701b8d2dfa7..00000000000
--- a/apps/studio/components/interfaces/App/CommandMenuWrapper.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
-import { codeBlock } from 'common-tags'
-import { PropsWithChildren, useMemo } from 'react'
-import toast from 'react-hot-toast'
-import { CommandMenuProvider } from 'ui-patterns/Cmdk'
-
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import type { SqlSnippet } from 'data/content/sql-snippets-query'
-import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { OPT_IN_TAGS } from 'lib/constants'
-import { uuidv4 } from 'lib/helpers'
-import { useProfile } from 'lib/profile'
-import { useSqlEditorStateSnapshot } from 'state/sql-editor'
-import { createSqlSnippetSkeleton } from '../SQLEditor/SQLEditor.utils'
-
-const CommandMenuWrapper = ({ children }: PropsWithChildren<{}>) => {
- const { ref } = useParams()
- const selectedOrganization = useSelectedOrganization()
- const { project: selectedProject } = useProjectContext()
- const opt_in_tags = selectedOrganization?.opt_in_tags
-
- const snap = useSqlEditorStateSnapshot()
- const isOptedInToAI = opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
-
- const { profile } = useProfile()
- const { data: settings } = useProjectApiQuery({ projectRef: ref })
- const canCreateSQLSnippet = useCheckPermissions(PermissionAction.CREATE, 'user_content', {
- resource: { type: 'sql', owner_id: profile?.id },
- subject: { id: profile?.id },
- })
-
- const apiKeys = {
- anon: settings?.autoApiService?.defaultApiKey ?? undefined,
- service: settings?.autoApiService?.serviceApiKey ?? undefined,
- }
- const apiUrl = `${settings?.autoApiService.protocol}://${settings?.autoApiService.endpoint}`
-
- const { data } = useEntityDefinitionsQuery(
- {
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- },
- { enabled: isOptedInToAI }
- )
-
- const cmdkMetadata = useMemo(() => {
- return {
- definitions: (data ?? []).map((def) => def.sql.trim()).join('\n\n'),
- flags: {},
- }
- }, [data])
-
- const onSaveGeneratedSQL = async (answer: string, title: string) => {
- if (!ref) return console.error('Project ref is required')
- if (!canCreateSQLSnippet) {
- toast('Unable to save query as you do not have sufficient permissions for this project')
- return
- }
-
- // Remove markdown syntax from returned answer
- answer = answer.replace(/`/g, '').replace(/sql\n/g, '').trim()
-
- const formattedSql = codeBlock`
- -- Note: This query was generated via Supabase AI, please verify the correctness of the
- -- SQL snippet before running it against your database as we are not able to guarantee it
- -- will do exactly what you requested the AI.
-
- ${answer}
- `
-
- try {
- const snippet = createSqlSnippetSkeleton({
- id: uuidv4(),
- name: title || 'Generated query',
- owner_id: profile?.id,
- project_id: selectedProject?.id,
- sql: formattedSql,
- })
-
- snap.addSnippet(snippet as SqlSnippet, ref)
- toast.success(`Successfully saved snippet!`)
- } catch (error: any) {
- toast.error(`Failed to create new query: ${error.message}`)
- }
- }
-
- return (
- <CommandMenuProvider
- site="studio"
- projectRef={ref}
- apiKeys={apiKeys}
- apiUrl={apiUrl}
- metadata={cmdkMetadata}
- isOptedInToAI={isOptedInToAI}
- saveGeneratedSQL={onSaveGeneratedSQL}
- >
- {children}
- </CommandMenuProvider>
- )
-}
-
-export default CommandMenuWrapper
diff --git a/apps/studio/components/interfaces/App/index.ts b/apps/studio/components/interfaces/App/index.ts
index 885f516f42e..116e6366cc2 100644
--- a/apps/studio/components/interfaces/App/index.ts
+++ b/apps/studio/components/interfaces/App/index.ts
@@ -1,3 +1,2 @@
export { default as AppBannerWrapper } from './AppBannerWrapper'
-export { default as CommandMenuWrapper } from './CommandMenuWrapper'
export { default as RouteValidationWrapper } from './RouteValidationWrapper'
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
index 72bbe031a06..8756576903b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
@@ -5,13 +5,12 @@ import { useEffect, useRef, useState } from 'react'
import { useTelemetryProps } from 'common'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { useProfile } from 'lib/profile'
import { useAppStateSnapshot } from 'state/app-state'
-import { Button, cn } from 'ui'
+import { AiIconAnimation, Button, cn } from 'ui'
import { AssistantChatForm } from 'ui-patterns'
-import { AiIcon } from 'ui-patterns/Cmdk'
import { MessageWithDebug } from './AIPolicyEditorPanel.utils'
import Message from './Message'
@@ -33,14 +32,13 @@ export const AIPolicyChat = ({
const router = useRouter()
const { profile } = useProfile()
const snap = useAppStateSnapshot()
- const organization = useSelectedOrganization()
const bottomRef = useRef<HTMLDivElement>(null)
const telemetryProps = useTelemetryProps()
const [value, setValue] = useState<string>('')
const inputRef = useRef<HTMLTextAreaElement>(null)
- const isOptedInToAI = organization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
@@ -116,7 +114,12 @@ export const AIPolicyChat = ({
textAreaRef={inputRef}
loading={loading}
disabled={loading}
- icon={<AiIcon className="[&>div>div]:border-black dark:[&>div>div]:border-white" />}
+ icon={
+ <AiIconAnimation
+ allowHoverEffect
+ className="[&>div>div]:border-black dark:[&>div>div]:border-white"
+ />
+ }
placeholder="Ask for some changes to your policy"
value={value}
onValueChange={(e) => setValue(e.target.value)}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index 8e653c52ad6..bd11605b0b2 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -40,9 +40,10 @@ import { databasePoliciesKeys } from 'data/database-policies/keys'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { BASE_PATH, OPT_IN_TAGS } from 'lib/constants'
+import { BASE_PATH } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import Telemetry from 'lib/telemetry'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
@@ -120,7 +121,7 @@ export const AIPolicyEditorPanel = memo(function ({
const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
const placeholder = generatePlaceholder(selectedPolicy)
- const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [error, setError] = useState<QueryResponseError>()
const [errorPanelOpen, setErrorPanelOpen] = useState<boolean>(true)
diff --git a/apps/studio/components/interfaces/BranchManagement/Branch.Commands.tsx b/apps/studio/components/interfaces/BranchManagement/Branch.Commands.tsx
new file mode 100644
index 00000000000..6979b223324
--- /dev/null
+++ b/apps/studio/components/interfaces/BranchManagement/Branch.Commands.tsx
@@ -0,0 +1,63 @@
+import { Forward, GitBranch } from 'lucide-react'
+
+import { useBranchesQuery } from 'data/branches/branches-query'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { PageType, useRegisterCommands, useRegisterPage, useSetPage } from 'ui-patterns/CommandMenu'
+import { COMMAND_MENU_SECTIONS } from '../App/CommandMenu/CommandMenu.utils'
+import { orderCommandSectionsByPriority } from '../App/CommandMenu/ordering'
+
+const SWITCH_BRANCH_PAGE_NAME = 'Switch branch'
+const EMPTY_ARRAY = [] as Array<any>
+
+export function useBranchCommands() {
+ const setPage = useSetPage()
+
+ const selectedProject = useSelectedProject()
+ const isBranchingEnabled = selectedProject?.is_branch_enabled === true
+
+ let { data: branches } = useBranchesQuery(
+ {
+ projectRef: selectedProject?.ref,
+ },
+ { enabled: isBranchingEnabled }
+ )
+ branches ??= EMPTY_ARRAY
+
+ useRegisterPage(
+ SWITCH_BRANCH_PAGE_NAME,
+ {
+ type: PageType.Commands,
+ sections: [
+ {
+ id: 'switch-branch',
+ name: 'Switch branch',
+ commands: branches.map((branch) => ({
+ id: `branch-${branch.id}`,
+ name: branch.name,
+ route: `/project/${branch.project_ref}`,
+ icon: () => <Forward />,
+ })),
+ },
+ ],
+ },
+ { enabled: isBranchingEnabled && branches.length > 0, deps: [branches] }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.ACTIONS,
+ [
+ {
+ id: 'switch-branch',
+ name: 'Switch branch',
+ value: 'Switch branch, Change branch, Select branch',
+ action: () => setPage(SWITCH_BRANCH_PAGE_NAME),
+ icon: () => <GitBranch />,
+ },
+ ],
+ {
+ enabled: isBranchingEnabled && branches.length > 0,
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 3 },
+ }
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
index e92c423aec9..eac11057230 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
@@ -14,6 +14,7 @@ import { useOrganizationUpdateMutation } from 'data/organizations/organization-u
import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { OPT_IN_TAGS } from 'lib/constants'
import { Collapsible, Form, IconChevronRight, Input, Toggle, cn } from 'ui'
@@ -24,10 +25,10 @@ const GeneralSettings = () => {
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
const selectedOrganization = useSelectedOrganization()
- const { name, opt_in_tags } = selectedOrganization ?? {}
+ const { name } = selectedOrganization ?? {}
const formId = 'org-general-settings'
- const isOptedIntoAi = opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL)
+ const isOptedIntoAi = useOrgOptedIntoAi()
const initialValues = { name: name ?? '', isOptedIntoAi }
const organizationDeletionEnabled = useIsFeatureEnabled('organizations:delete')
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.Commands.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.Commands.tsx
new file mode 100644
index 00000000000..b64290d75ce
--- /dev/null
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.Commands.tsx
@@ -0,0 +1,40 @@
+import { useParams } from 'common'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+import { COMMAND_MENU_SECTIONS } from '../App/CommandMenu/CommandMenu.utils'
+
+export function useApiDocsGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-api',
+ name: 'Project API Docs',
+ route: `/project/${ref}/api`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-api-auth',
+ name: 'Auth Docs',
+ route: `/project/${ref}/api?page=auth`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-api-user-management',
+ name: 'User Management Docs',
+ route: `/project/${ref}/api?page=users`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-api-graphql',
+ name: 'GraphQL Docs',
+ route: `/project/${ref}/api/graphiql`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx b/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
index a50144561bc..3330368c9a9 100644
--- a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
@@ -3,8 +3,9 @@ import { motion } from 'framer-motion'
import { PropsWithChildren, useEffect, useState } from 'react'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM, OPT_IN_TAGS } from 'lib/constants'
+import { IS_PLATFORM } from 'lib/constants'
import { Button, IconInfo } from 'ui'
export interface AISchemaSuggestionPopoverProps {
@@ -18,7 +19,7 @@ const AISchemaSuggestionPopover = ({
onClickSettings,
}: PropsWithChildren<AISchemaSuggestionPopoverProps>) => {
const selectedOrganization = useSelectedOrganization()
- const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [hasEnabledAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', true)
const [isDelayComplete, setIsDelayComplete] = useState(false)
const [aiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)
diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
index 771abbfa586..6f61226d608 100644
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
@@ -6,13 +6,12 @@ import { useEffect, useRef, useState } from 'react'
import { useTelemetryProps } from 'common'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { useProfile } from 'lib/profile'
import { useAppStateSnapshot } from 'state/app-state'
-import { Button, cn } from 'ui'
+import { AiIconAnimation, Button, cn } from 'ui'
import { AssistantChatForm } from 'ui-patterns'
-import { AiIcon } from 'ui-patterns/Cmdk'
import { DiffType } from '../SQLEditor.types'
import Message from './Message'
@@ -40,14 +39,13 @@ export const AiAssistantPanel = ({
const router = useRouter()
const { profile } = useProfile()
const snap = useAppStateSnapshot()
- const organization = useSelectedOrganization()
const bottomRef = useRef<HTMLDivElement>(null)
const telemetryProps = useTelemetryProps()
const [value, setValue] = useState<string>('')
const inputRef = useRef<HTMLTextAreaElement>(null)
- const isOptedInToAI = organization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
@@ -138,7 +136,12 @@ export const AiAssistantPanel = ({
textAreaRef={inputRef}
loading={loading}
disabled={loading}
- icon={<AiIcon className="[&>div>div]:border-black dark:[&>div>div]:border-white" />}
+ icon={
+ <AiIconAnimation
+ allowHoverEffect
+ className="[&>div>div]:border-black dark:[&>div>div]:border-white"
+ />
+ }
placeholder="Ask a question about your SQL query"
value={value}
onValueChange={(e) => setValue(e.target.value)}
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index d43c6b510a6..4a29cb919aa 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -17,10 +17,11 @@ import { useFormatQueryMutation } from 'data/sql/format-sql-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { isError } from 'data/utils/error-check'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useFlag } from 'hooks/ui/useFlag'
-import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
+import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import { wrapWithRoleImpersonation } from 'lib/role-impersonation'
@@ -31,14 +32,7 @@ import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
import { isRoleImpersonationEnabled, useGetImpersonatedRole } from 'state/role-impersonation-state'
import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'
import { getSqlEditorV2StateSnapshot, useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
-import {
- AiIconAnimation,
- Loading,
- ResizableHandle,
- ResizablePanel,
- ResizablePanelGroup,
- cn,
-} from 'ui'
+import { AiIconAnimation, ResizableHandle, ResizablePanel, ResizablePanelGroup, cn } from 'ui'
import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'
@@ -119,8 +113,7 @@ const SQLEditor = () => {
const [isAiOpen, setIsAiOpen] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_OPEN, true)
const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false)
- const selectedOrganization = useSelectedOrganization()
- const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Alerts.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Alerts.tsx
new file mode 100644
index 00000000000..479c8855f5d
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Alerts.tsx
@@ -0,0 +1,58 @@
+import { AlertTriangle, Info } from 'lucide-react'
+
+import { useAppStateSnapshot } from 'state/app-state'
+import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Button_Shadcn_ } from 'ui'
+
+export function IncludeSchemaAlert() {
+ const { setShowAiSettingsModal } = useAppStateSnapshot()
+
+ return (
+ <Alert_Shadcn_ variant="warning">
+ <AlertTriangle />
+ <AlertTitle_Shadcn_>
+ Project metadata (tables, columns, and data types) is being shared with OpenAI
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ <Button_Shadcn_
+ variant="link"
+ className="h-fit p-0 font-normal"
+ onClick={() => setShowAiSettingsModal(true)}
+ >
+ Change this configuration
+ </Button_Shadcn_>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )
+}
+
+export type AiMetadataSkipReason = 'forbidden' | 'no_project'
+
+export function ExcludeSchemaAlert({
+ metadataSkipReason,
+}: {
+ metadataSkipReason: AiMetadataSkipReason | undefined
+}) {
+ const { setShowAiSettingsModal } = useAppStateSnapshot()
+
+ return (
+ <Alert_Shadcn_>
+ <Info />
+ <AlertTitle_Shadcn_>
+ Project metadata (tables, columns, and data types) is not being shared with OpenAI
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ {metadataSkipReason === 'no_project' ? (
+ 'Switch to a project to change this setting'
+ ) : (
+ <Button_Shadcn_
+ variant="link"
+ className="h-fit p-0 font-normal"
+ onClick={() => setShowAiSettingsModal(true)}
+ >
+ Change this configuration
+ </Button_Shadcn_>
+ )}
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )
+}
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Commands.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Commands.tsx
new file mode 100644
index 00000000000..cf30643e27a
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.Commands.tsx
@@ -0,0 +1,34 @@
+import { useIsLoggedIn } from 'common'
+import { useAppStateSnapshot } from 'state/app-state'
+import { AiIconAnimation } from 'ui'
+import { BadgeExperimental, useRegisterCommands, useSetQuery } from 'ui-patterns/CommandMenu'
+import { orderCommandSectionsByPriority } from '../App/CommandMenu/ordering'
+import { COMMAND_MENU_SECTIONS } from '../App/CommandMenu/CommandMenu.utils'
+
+export function useGenerateSqlCommand() {
+ const isLoggedIn = useIsLoggedIn()
+
+ const { setShowGenerateSqlModal } = useAppStateSnapshot()
+ const setQuery = useSetQuery()
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.QUERY,
+ [
+ {
+ id: 'generate-sql-ai',
+ name: 'Run SQL with Supabase AI',
+ action: () => {
+ setShowGenerateSqlModal(true)
+ setQuery('')
+ },
+ icon: () => <AiIconAnimation allowHoverEffect />,
+ badge: () => <BadgeExperimental />,
+ },
+ ],
+ {
+ enabled: isLoggedIn,
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 2 },
+ }
+ )
+}
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.tsx
new file mode 100644
index 00000000000..137a11f4dd6
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.tsx
@@ -0,0 +1,12 @@
+import dynamic from 'next/dynamic'
+import { memo } from 'react'
+
+import { useCommandMenuInitiated } from 'ui-patterns/CommandMenu'
+
+const LazyGenerateSql = dynamic(() => import('./SqlGeneratorImpl'), { ssr: false })
+
+export const GenerateSql = memo(() => {
+ const isInitiated = useCommandMenuInitiated()
+ return isInitiated && <LazyGenerateSql />
+})
+GenerateSql.displayName = 'GenerateSql'
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.utils.ts b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.utils.ts
new file mode 100644
index 00000000000..4ca094a049c
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGenerator.utils.ts
@@ -0,0 +1,112 @@
+import { stripIndent } from 'common-tags'
+
+type QueryCategory = {
+ category: string
+ queries: string[]
+}
+
+type SampleQueries = QueryCategory[]
+
+export const SAMPLE_QUERIES: SampleQueries = [
+ {
+ category: 'Tables',
+ queries: [
+ 'Create a table that stores a list of cities, and insert 10 rows of sample data into it',
+ 'Create tables (with foreign key relationships) for blog posts and comments',
+ 'Create tables for employees, reviewers, and employee reviews, with columns for employee ID, reviewer ID, and review text',
+ ],
+ },
+ {
+ category: 'Views',
+ queries: [
+ 'Create a view that shows the total revenue for each customer',
+ 'Create a view that shows all orders that were placed in the last week',
+ 'Create a view that shows all products that are currently out of stock',
+ 'Create a materialized view that shows the customer_orders table the total value of orders in a month',
+ ],
+ },
+ {
+ category: 'Indexes',
+ queries: [
+ 'Create an index on the primary key column of my orders table',
+ 'Create a partial index on the orders table:',
+ 'Create an index on the customer_id column of the customer_orders table',
+ ],
+ },
+ {
+ category: 'Select',
+ queries: [
+ 'Retrieve a list of employees from the employees table who have a salary greater than $50,000',
+ 'Retrieve a list of all employees with the title "Manager" from the employees table',
+ 'Retrieve a list of all employees hired in the last 6 months',
+ 'Retrieve the department and average salary of each department from the employees table, group by department',
+ ],
+ },
+ {
+ category: 'Triggers',
+ queries: [
+ 'Create a trigger that updates the updated_at column on the orders table with the current time when the row of the orders table is updated',
+ 'Create a trigger to add a new user to the users table when someone new registers',
+ 'Create a trigger to send an email whenever there is an insert in the orders table',
+ 'Create a trigger to delete all orders placed by a customer when that customer is deleted from the customers table',
+ ],
+ },
+ {
+ category: 'Row Level Security',
+ queries: [
+ 'Create an RLS policy that grants only authenticated access to the profiles table',
+ 'Create an RLS policy that grants SELECT access to the sales_rep role for the customers table, but denies access to all other roles',
+ "Create an RLS policy that grants INSERT access access to the manager role for the employees table, but only for rows where the employee's department_id matches a list of departments that the manager is responsible for",
+ ],
+ },
+ {
+ category: 'Functions',
+ queries: [
+ "Create a function to add a new entry to a user's table when a new user signs up",
+ 'Create an a function to calculate the average price of a product in a given category',
+ 'Create a function to insert a new order and update the inventory for the ordered products',
+ 'Create a function to calculate the total sales for a product given an id',
+ ],
+ },
+]
+
+export function generatePrompt(prompt: string, definitions?: any) {
+ 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 --git a/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx
new file mode 100644
index 00000000000..7c0b3cf8fbb
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx
@@ -0,0 +1,416 @@
+import { AlertTriangle, User } from 'lucide-react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useEffectOnce } from 'react-use'
+import { format } from 'sql-formatter'
+
+import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
+import { useAllowSendAiSchema } from 'hooks/misc/useAllowSendAiSchema'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { useAppStateSnapshot } from 'state/app-state'
+import {
+ AiIconAnimation,
+ Button,
+ CodeBlock,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
+ Input_Shadcn_,
+ Modal,
+ StatusIcon,
+ Tabs_Shadcn_,
+ TabsContent_Shadcn_,
+ TabsList_Shadcn_,
+ TabsTrigger_Shadcn_,
+ cn,
+} from 'ui'
+import {
+ BadgeExperimental,
+ generateCommandClassNames,
+ useHistoryKeys,
+ useQuery,
+ useSetQuery,
+} from 'ui-patterns/CommandMenu'
+import type { UseAiChatOptions } from 'ui-patterns/CommandMenu/prepackaged/ai'
+import {
+ AiWarning,
+ MessageRole,
+ MessageStatus,
+ useAiChat,
+} from 'ui-patterns/CommandMenu/prepackaged/ai'
+import type { AiMetadataSkipReason } from './SqlGenerator.Alerts'
+import { ExcludeSchemaAlert, IncludeSchemaAlert } from './SqlGenerator.Alerts'
+import { SAMPLE_QUERIES, generatePrompt } from './SqlGenerator.utils'
+import { SQLOutputActions } from './SqlOutputActions'
+
+function useSchemaMetadataForAi() {
+ const allowed = useAllowSendAiSchema()
+ const project = useSelectedProject()
+
+ const includeMetadata = allowed && !!project
+ const metadataSkipReason: AiMetadataSkipReason = !project ? 'no_project' : 'forbidden'
+
+ const { data } = useEntityDefinitionsQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ { enabled: includeMetadata }
+ )
+
+ const api = useMemo(
+ () =>
+ includeMetadata
+ ? {
+ includeMetadata,
+ data,
+ }
+ : { includeMetadata, metadataSkipReason },
+ [includeMetadata, data, metadataSkipReason]
+ )
+
+ return api
+}
+
+function useAiSqlGeneration() {
+ const { showGenerateSqlModal } = useAppStateSnapshot()
+
+ const schemaMetadata = useSchemaMetadataForAi()
+ const definitions = useMemo(
+ () => (schemaMetadata.data ?? []).map((def) => def.sql.trim()).join('\n\n'),
+ [schemaMetadata]
+ )
+
+ const query = useQuery()
+ const setQuery = useSetQuery()
+ const [isLoading, setIsLoading] = useState(false)
+
+ const messageTemplate = useCallback<NonNullable<UseAiChatOptions['messageTemplate']>>(
+ (message) => generatePrompt(message, schemaMetadata.includeMetadata ? definitions : undefined),
+ [schemaMetadata, definitions]
+ )
+ const { submit, reset, messages, isResponding, hasError } = useAiChat({
+ messageTemplate,
+ setIsLoading,
+ })
+
+ useHistoryKeys({
+ enable: showGenerateSqlModal && !isResponding,
+ stack: messages.filter(({ role }) => role === MessageRole.User).map(({ content }) => content),
+ })
+
+ const handleSubmit = useCallback(
+ (message: string) => {
+ setQuery('')
+ submit(message)
+ },
+ [setQuery, submit]
+ )
+
+ const handleReset = useCallback(() => {
+ setQuery('')
+ reset()
+ }, [setQuery, reset])
+
+ useEffectOnce(() => {
+ if (query) handleSubmit(query)
+ })
+
+ return {
+ query,
+ setQuery,
+ isLoading,
+ isResponding,
+ hasError,
+ messages,
+ handleSubmit,
+ handleReset,
+ usesMetadata: schemaMetadata.includeMetadata,
+ metadataSkipReason: schemaMetadata.metadataSkipReason,
+ }
+}
+
+export default function SqlGeneratorImpl() {
+ const { showGenerateSqlModal, setShowGenerateSqlModal } = useAppStateSnapshot()
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ const timeoutHandle = useRef<ReturnType<typeof setTimeout>>()
+ useEffect(() => () => clearTimeout(timeoutHandle.current), [])
+
+ const {
+ query,
+ setQuery,
+ isLoading,
+ isResponding,
+ hasError,
+ messages,
+ handleSubmit,
+ handleReset,
+ usesMetadata,
+ metadataSkipReason,
+ } = useAiSqlGeneration()
+
+ return (
+ <Modal
+ header={
+ <span className="flex items-center justify-between gap-2">
+ Generate SQL
+ <BadgeExperimental className="w-fit" />
+ </span>
+ }
+ hideClose
+ hideFooter
+ visible={showGenerateSqlModal}
+ onOpenAutoFocus={() => {
+ timeoutHandle.current = setTimeout(() => inputRef.current?.focus())
+ }}
+ onCancel={() => {
+ if (messages.length > 0) {
+ handleReset()
+ timeoutHandle.current = setTimeout(() => inputRef.current?.focus())
+ } else {
+ setShowGenerateSqlModal(false)
+ }
+ }}
+ className="w-11/12 !max-w-3xl h-4/5 max-h-[800px] grid-rows-[min-content,_1fr] bg-overlay"
+ >
+ <Command_Shadcn_ className="p-4">
+ <div className="flex-grow overflow-auto">
+ {messages.length > 0 && <Messages messages={messages} handleReset={handleReset} />}
+ {messages.length === 0 && !hasError && (
+ <EmptyState query={query} handleSubmit={handleSubmit} />
+ )}
+ {hasError && <ErrorMessage handleReset={handleReset} />}
+ </div>
+ <div className="flex flex-col gap-4">
+ {usesMetadata ? (
+ <IncludeSchemaAlert />
+ ) : (
+ <ExcludeSchemaAlert metadataSkipReason={metadataSkipReason} />
+ )}
+ <Input_Shadcn_
+ ref={inputRef}
+ className="bg-alternative rounded [&_input]:pr-32 md:[&_input]:pr-40"
+ placeholder={
+ isLoading || isResponding
+ ? 'Waiting on an answer...'
+ : 'Describe what you need and Supabase AI will try to generate the relevant SQL statements'
+ }
+ value={query}
+ onChange={(e) => {
+ if (!isLoading || !isResponding) {
+ setQuery(e.target.value)
+ }
+ }}
+ onKeyDown={(e) => {
+ switch (e.key) {
+ case 'Enter':
+ if (!query || isLoading || isResponding) {
+ return
+ }
+ return handleSubmit(query)
+ default:
+ return
+ }
+ }}
+ />
+ </div>
+ </Command_Shadcn_>
+ </Modal>
+ )
+}
+
+function Messages({
+ messages,
+ handleReset,
+}: {
+ messages: ReturnType<typeof useAiChat>['messages']
+ handleReset: () => void
+}) {
+ function formatAnswer(answer: string) {
+ try {
+ return format(answer, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+ } catch {
+ return answer
+ }
+ }
+
+ const X_PADDING = 'px-4'
+
+ const UserAvatar = useCallback(() => {
+ return (
+ <div
+ className={cn(
+ 'w-7 h-7',
+ 'bg-background rounded-full',
+ 'border border-muted',
+ 'flex items-center justify-center',
+ 'text-foreground-lighter',
+ 'shadow-sm'
+ )}
+ >
+ <User strokeWidth={1.5} size={16} />
+ </div>
+ )
+ }, [])
+
+ return messages.map((message, i) => {
+ switch (message.role) {
+ case MessageRole.User:
+ return (
+ <div className={cn('w-full', 'flex gap-6 mb-6', X_PADDING, '[overflow-anchor:none]')}>
+ <UserAvatar />
+ <div className="prose text-foreground-light text-sm">{message.content}</div>
+ </div>
+ )
+ case MessageRole.Assistant:
+ const unformattedAnswer = message.content
+ .replace(/```sql/g, '')
+ .replace(/```.*/gs, '')
+ .replace(/-- End of SQL query\.*/g, '')
+ .trim()
+
+ const answer =
+ message.status === MessageStatus.Complete
+ ? formatAnswer(unformattedAnswer)
+ : unformattedAnswer
+ const cantHelp = answer.replace(/^-- /, '') === "Sorry, I don't know how to help with that."
+
+ return (
+ <div className={cn('w-full', X_PADDING, '[overflow-anchor:none]')}>
+ <div className={cn('w-full', 'flex gap-6 mb-6', '[overflow-anchor:none]')}>
+ <AiIconAnimation
+ allowHoverEffect
+ loading={
+ message.status === MessageStatus.Pending ||
+ message.status === MessageStatus.InProgress
+ }
+ />
+ {message.status === MessageStatus.Pending ? (
+ <div className="bg-border-strong h-[21px] w-[13px] mt-1 animate-bounce"></div>
+ ) : cantHelp ? (
+ <div className="py-6 flex flex-col flex-grow items-center gap-6">
+ <AlertTriangle className="text-amber-900" strokeWidth={1.5} size={21} />
+ <p className="text-lg text-foreground text-center">
+ Sorry, I don't know how to help with that.
+ </p>
+ <Button size="tiny" type="secondary" onClick={handleReset}>
+ Try again?
+ </Button>
+ </div>
+ ) : (
+ <div className="min-w-0 flex-grow flex flex-col">
+ <CodeBlock
+ hideCopy
+ language="sql"
+ className={cn(
+ 'relative',
+ 'prose max-w-[initial]',
+ '!mb-0 !rounded-b-none',
+ 'bg-surface-100'
+ )}
+ >
+ {answer}
+ </CodeBlock>
+ <AiWarning className="!rounded-t-none border-muted" />
+ {message.status === MessageStatus.Complete && (
+ <SQLOutputActions answer={answer} messages={messages} className="mt-2" />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ )
+ }
+ })
+}
+
+function EmptyState({
+ query,
+ handleSubmit,
+}: {
+ query: string
+ handleSubmit: (query: string) => void
+}) {
+ const [activeTab, setActiveTab] = useState(SAMPLE_QUERIES[0].category)
+
+ useEffect(() => {
+ function handleSwitchTab(event: KeyboardEvent) {
+ if (query || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) {
+ return
+ }
+
+ const activeSampleIndex = SAMPLE_QUERIES.findIndex(
+ (samples) => samples.category === activeTab
+ )!
+ const nextIndex =
+ event.key === 'ArrowRight'
+ ? Math.min(activeSampleIndex + 1, SAMPLE_QUERIES.length - 1)
+ : Math.max(0, activeSampleIndex - 1)
+ setActiveTab(SAMPLE_QUERIES[nextIndex].category)
+ }
+
+ document.addEventListener('keydown', handleSwitchTab)
+ return () => document.removeEventListener('keydown', handleSwitchTab)
+ }, [query, activeTab])
+
+ return (
+ <>
+ <h3 className="text-base text-foreground-light">
+ Describe what you need and Supabase AI will try to generate the relevant SQL statements
+ </h3>
+ <p className="text-sm mt-1 text-foreground-light">
+ Here are some example prompts to try out:
+ </p>
+ <hr className="my-4" />
+ <Tabs_Shadcn_
+ value={activeTab}
+ onValueChange={(value) => setActiveTab(value)}
+ className="focus-visible:ring-0"
+ >
+ <TabsList_Shadcn_ className="gap-4">
+ {SAMPLE_QUERIES.map((samples) => (
+ <TabsTrigger_Shadcn_ value={samples.category}>{samples.category}</TabsTrigger_Shadcn_>
+ ))}
+ </TabsList_Shadcn_>
+ <CommandList_Shadcn_>
+ {SAMPLE_QUERIES.map((samples) => (
+ <TabsContent_Shadcn_ value={samples.category}>
+ {samples.queries.map((sampleQuery) => (
+ <CommandItem_Shadcn_
+ key={sampleQuery.replace(/\s+/g, '_')}
+ className={generateCommandClassNames(false)}
+ onSelect={() => {
+ if (!query) {
+ handleSubmit(sampleQuery)
+ }
+ }}
+ >
+ <AiIconAnimation allowHoverEffect />
+ {sampleQuery}
+ </CommandItem_Shadcn_>
+ ))}
+ </TabsContent_Shadcn_>
+ ))}
+ </CommandList_Shadcn_>
+ </Tabs_Shadcn_>
+ </>
+ )
+}
+
+function ErrorMessage({ handleReset }: { handleReset: () => void }) {
+ return (
+ <div className="p-6 flex flex-col items-center gap-6 mt-4">
+ <StatusIcon variant="warning" />
+ <p className="text-sm text-foreground text-center">
+ Sorry, looks like Supabase AI is having a hard time!
+ </p>
+ <p className="text-sm text-foreground-lighter text-center">Please try again in a bit.</p>
+ <Button size="tiny" type="default" onClick={handleReset}>
+ Try again?
+ </Button>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlOutputActions.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlOutputActions.tsx
new file mode 100644
index 00000000000..5daf0680a69
--- /dev/null
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlOutputActions.tsx
@@ -0,0 +1,169 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { codeBlock, stripIndent } from 'common-tags'
+import { Check, Clipboard, Save } from 'lucide-react'
+import { useCallback, useEffect, useState } from 'react'
+import CopyToClipboard from 'react-copy-to-clipboard'
+import toast from 'react-hot-toast'
+
+import { useParams } from 'common'
+import { createSqlSnippetSkeleton } from 'components/interfaces/SQLEditor/SQLEditor.utils'
+import type { SqlSnippet } from 'data/content/sql-snippets-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { uuidv4 } from 'lib/helpers'
+import { useProfile } from 'lib/profile'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import { Button, cn } from 'ui'
+import type { Message } from 'ui-patterns/CommandMenu/prepackaged/ai'
+import { MessageRole, MessageStatus, queryAi } from 'ui-patterns/CommandMenu/prepackaged/ai'
+import { formatTitle } from './SqlGenerator.utils'
+
+const useSaveGeneratedSql = () => {
+ const { ref } = useParams()
+ const { profile } = useProfile()
+ const selectedProject = useSelectedProject()
+ const snap = useSqlEditorStateSnapshot()
+ const canCreateSQLSnippet = useCheckPermissions(PermissionAction.CREATE, 'user_content', {
+ resource: { type: 'sql', owner_id: profile?.id },
+ subject: { id: profile?.id },
+ })
+
+ const saveGeneratedSql = useCallback(
+ (answer: string, title: string) => {
+ if (!ref) return console.error('Project ref is required')
+
+ if (!canCreateSQLSnippet) {
+ toast('Unable to save query as you do not have sufficient permissions for this project')
+ return
+ }
+
+ // Remove markdown syntax from returned answer
+ answer = answer.replace(/`/g, '').replace(/sql\n/g, '').trim()
+
+ const formattedSql = codeBlock`
+ -- Note: This query was generated via Supabase AI, please verify the correctness of the
+ -- SQL snippet before running it against your database as we are not able to guarantee it
+ -- will do exactly what you requested the AI.
+ ${answer}
+ `
+
+ try {
+ const snippet = createSqlSnippetSkeleton({
+ id: uuidv4(),
+ name: title || 'Generated query',
+ owner_id: profile?.id,
+ project_id: selectedProject?.id,
+ sql: formattedSql,
+ })
+
+ snap.addSnippet(snippet as SqlSnippet, ref)
+ toast.success(`Successfully saved snippet!`)
+ } catch (error: any) {
+ toast.error(`Failed to create new query: ${error.message}`)
+ }
+ },
+ [canCreateSQLSnippet, profile?.id, ref, selectedProject?.id, snap]
+ )
+
+ return saveGeneratedSql
+}
+
+export interface SQLOutputActionsProps {
+ answer: string
+ messages: Message[]
+ className?: string
+}
+
+export function SQLOutputActions({ answer, messages, className }: SQLOutputActionsProps) {
+ const { ref } = useParams()
+ const saveGeneratedSql = useSaveGeneratedSql()
+
+ const [showCopied, setShowCopied] = useState(false)
+ const [isSaving, setIsSaving] = useState(false)
+ const [isSaved, setIsSaved] = useState(false)
+
+ const onSelectSaveSnippet = async () => {
+ setIsSaving(true)
+
+ 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={cn('flex items-center justify-end space-x-2', className)}>
+ <CopyToClipboard text={answer?.replace(/```.*/g, '').trim()}>
+ <Button
+ type="default"
+ icon={
+ showCopied ? (
+ <Check size="tiny" className="text-brand" strokeWidth={2} />
+ ) : (
+ <Clipboard size="tiny" />
+ )
+ }
+ onClick={() => setShowCopied(true)}
+ >
+ {showCopied ? 'Copied' : 'Copy SQL'}
+ </Button>
+ </CopyToClipboard>
+ {ref !== undefined && (
+ <Button
+ type="default"
+ loading={isSaving}
+ disabled={isSaving}
+ icon={
+ isSaved ? (
+ <Check size="tiny" className="text-brand" strokeWidth={2} />
+ ) : (
+ <Save size="tiny" />
+ )
+ }
+ onClick={() => onSelectSaveSnippet()}
+ >
+ {isSaved ? 'Snippet saved!' : 'Save into new snippet'}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Support/SupportForm.tsx b/apps/studio/components/interfaces/Support/SupportForm.tsx
index 6038548517c..629ebffdf7c 100644
--- a/apps/studio/components/interfaces/Support/SupportForm.tsx
+++ b/apps/studio/components/interfaces/Support/SupportForm.tsx
@@ -51,8 +51,7 @@ import {
Separator,
cn,
} from 'ui'
-import { useCommandMenu } from 'ui-patterns/Cmdk'
-import { TextHighlighter } from 'ui-patterns/Cmdk/Command.utils'
+import { TextHighlighterBase as TextHighlighter } from 'ui-patterns/CommandMenu'
import MultiSelect from 'ui-patterns/MultiSelectDeprecated'
import DisabledStateForFreeTier from './DisabledStateForFreeTier'
import { CATEGORY_OPTIONS, SERVICE_OPTIONS, SEVERITY_OPTIONS } from './Support.constants'
@@ -180,7 +179,6 @@ const SupportForm = ({ setSentCategory, setSelectedProject }: SupportFormProps)
allowSupportAccess: false,
}
- const { site } = useCommandMenu()
const router = useRouter()
const onFilesUpload = async (event: ChangeEvent<HTMLInputElement>) => {
@@ -318,19 +316,9 @@ const SupportForm = ({ setSentCategory, setSelectedProject }: SupportFormProps)
switch (pageType) {
case PageType.Markdown:
case PageType.Reference:
- if (site === 'docs') {
- return link
- } else if (site === 'website') {
- return `/docs${link}`
- } else {
- return `https://supabase.com/docs${link}`
- }
+ return `https://supabase.com/docs${link}`
case PageType.Integration:
- if (site === 'website') {
- return link
- } else {
- return `https://supabase.com${link}`
- }
+ return `https://supabase.com${link}`
case PageType.GithubDiscussion:
return link
default:
@@ -338,33 +326,6 @@ const SupportForm = ({ setSentCategory, setSelectedProject }: SupportFormProps)
}
}
- async function handleLinkClick(pageType: PageType, link: string) {
- switch (pageType) {
- case PageType.Markdown:
- case PageType.Reference:
- if (site === 'docs') {
- await router.push(link)
- } else if (site === 'website') {
- await router.push(`/docs${link}`)
- } else {
- window.open(`https://supabase.com/docs${link}`, '_blank')
- }
- break
- case PageType.Integration:
- if (site === 'website') {
- router.push(link)
- } else {
- window.open(`https://supabase.com${link}`, '_blank')
- }
- break
- case PageType.GithubDiscussion:
- window.open(link, '_blank')
- break
- default:
- throw new Error(`Unknown page type '${pageType}'`)
- }
- }
-
function formatSectionUrl(page: Page, section: PageSection): string {
switch (page.type) {
case PageType.Markdown:
diff --git a/apps/studio/components/layouts/AdvisorsLayout/Advisors.Commands.tsx b/apps/studio/components/layouts/AdvisorsLayout/Advisors.Commands.tsx
new file mode 100644
index 00000000000..719a387333e
--- /dev/null
+++ b/apps/studio/components/layouts/AdvisorsLayout/Advisors.Commands.tsx
@@ -0,0 +1,28 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useAdvisorsGoToCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-advisors-security',
+ name: 'Security Advisor',
+ route: `/project/${ref}/advisors/security`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-advisors-performance',
+ name: 'Performance Advisor',
+ route: `/project/${ref}/advisors/performance`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx b/apps/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
index c4a41710016..410b3c7504d 100644
--- a/apps/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
+++ b/apps/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
@@ -1,10 +1,11 @@
+import { User } from 'lucide-react'
import Link from 'next/link'
+import { useTheme } from 'next-themes'
import { useRouter } from 'next/router'
import { useState } from 'react'
import { useSignOut } from 'lib/auth'
import { useProfile } from 'lib/profile'
-import { useTheme } from 'next-themes'
import {
DropdownMenu,
DropdownMenuContent,
@@ -19,15 +20,14 @@ import {
singleThemes,
Theme,
} from 'ui'
-import { useCommandMenu } from 'ui-patterns/Cmdk'
-import { User } from 'lucide-react'
+import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
const UserSettingsDropdown = () => {
const signOut = useSignOut()
const router = useRouter()
const [open, setOpen] = useState(false)
const { profile } = useProfile()
- const { setIsOpen: setCommandMenuOpen } = useCommandMenu()
+ const setCommandMenuOpen = useSetCommandMenuOpen()
const { theme, setTheme } = useTheme()
const onClickLogout = async () => {
diff --git a/apps/studio/components/layouts/AuthLayout/Auth.Commands.tsx b/apps/studio/components/layouts/AuthLayout/Auth.Commands.tsx
new file mode 100644
index 00000000000..20f52cd7334
--- /dev/null
+++ b/apps/studio/components/layouts/AuthLayout/Auth.Commands.tsx
@@ -0,0 +1,73 @@
+import { Lock } from 'lucide-react'
+
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+import { orderCommandSectionsByPriority } from 'components/interfaces/App/CommandMenu/ordering'
+import { useParams } from 'common'
+
+export function useAuthGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ 'Actions',
+ [
+ {
+ id: 'create-rls-policy',
+ name: 'Create RLS policy',
+ value: 'Create RLS (Row Level Security) policy',
+ route: `/project/${ref}/auth/policies`,
+ icon: () => <Lock />,
+ },
+ ],
+ {
+ ...options,
+ deps: [ref],
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 3 },
+ }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-auth-users',
+ name: 'Users',
+ value: 'Auth: Users',
+ route: `/project/${ref}/auth/users`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-auth-policies',
+ name: 'Policies',
+ value: 'Auth: Policies (RLS)',
+ route: `/project/${ref}/auth/policies`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-auth-providers',
+ name: 'Providers',
+ value: 'Auth: Providers (Social Login, SSO)',
+ route: `/project/${ref}/auth/providers`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-auth-templates',
+ name: 'Email Templates',
+ value: 'Auth: Email Templates',
+ route: `/project/${ref}/auth/templates`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-auth-url-configuration',
+ name: 'URL Configuration',
+ value: 'Auth: URL Configuration (Site URL, Redirect URLs)',
+ route: `/project/${ref}/auth/url-configuration`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/DatabaseLayout/Database.Commands.tsx b/apps/studio/components/layouts/DatabaseLayout/Database.Commands.tsx
new file mode 100644
index 00000000000..891f526f234
--- /dev/null
+++ b/apps/studio/components/layouts/DatabaseLayout/Database.Commands.tsx
@@ -0,0 +1,107 @@
+import { Code } from 'lucide-react'
+
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+import { useParams } from 'common'
+import { orderCommandSectionsByPriority } from 'components/interfaces/App/CommandMenu/ordering'
+
+export function useDatabaseGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.QUERY,
+ [
+ {
+ id: 'run-sql',
+ name: 'Run SQL',
+ route: `/project/${ref}/sql/new`,
+ icon: () => <Code />,
+ },
+ ],
+ {
+ ...options,
+ deps: [ref],
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 2 },
+ }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-database-tables',
+ name: 'Tables',
+ value: 'Database: Tables',
+ route: `/project/${ref}/database/tables`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-triggers',
+ name: 'Triggers',
+ value: 'Database: Triggers',
+ route: `/project/${ref}/database/triggers`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-functions',
+ name: 'Functions',
+ value: 'Database: Functions',
+ route: `/project/${ref}/database/functions`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-extensions',
+ name: 'Extensions',
+ value: 'Database: Extensions',
+ route: `/project/${ref}/database/extensions`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-roles',
+ name: 'Roles',
+ value: 'Database: Roles',
+ route: `/project/${ref}/database/roles`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-replication',
+ name: 'Replication',
+ value: 'Database: Replication',
+ route: `/project/${ref}/database/replication`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-hooks',
+ name: 'Webhooks',
+ value: 'Database: Webhooks',
+ route: `/project/${ref}/database/hooks`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-backups',
+ name: 'Backups',
+ value: 'Database: Backups',
+ route: `/project/${ref}/database/backups/scheduled`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-wrappers',
+ name: 'Wrappers',
+ value: 'Database: Wrappers',
+ route: `/project/${ref}/database/wrappers`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-database-migrations',
+ name: 'Migrations',
+ value: 'Database: Migrations',
+ route: `/project/${ref}/database/migrations`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/FunctionsLayout/Functions.Commands.tsx b/apps/studio/components/layouts/FunctionsLayout/Functions.Commands.tsx
new file mode 100644
index 00000000000..1c447f1c19e
--- /dev/null
+++ b/apps/studio/components/layouts/FunctionsLayout/Functions.Commands.tsx
@@ -0,0 +1,22 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useFunctionsGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-functions',
+ name: 'Edge Functions',
+ route: `/project/${ref}/functions`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/FunctionsLayout.tsx b/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx
similarity index 97%
rename from apps/studio/components/layouts/FunctionsLayout.tsx
rename to apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx
index 768683b7cb7..1d2feb88dca 100644
--- a/apps/studio/components/layouts/FunctionsLayout.tsx
+++ b/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx
@@ -11,8 +11,8 @@ import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { withAuth } from 'hooks/misc/withAuth'
import { Button, IconCode, IconExternalLink } from 'ui'
-import FunctionsNav from '../interfaces/Functions/FunctionsNav'
-import ProjectLayout from './ProjectLayout/ProjectLayout'
+import FunctionsNav from '../../interfaces/Functions/FunctionsNav'
+import ProjectLayout from '../ProjectLayout/ProjectLayout'
interface FunctionsLayoutProps {
title?: string
diff --git a/apps/studio/components/layouts/LogsLayout/Logs.Commands.tsx b/apps/studio/components/layouts/LogsLayout/Logs.Commands.tsx
new file mode 100644
index 00000000000..e302bb87400
--- /dev/null
+++ b/apps/studio/components/layouts/LogsLayout/Logs.Commands.tsx
@@ -0,0 +1,58 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useLogsGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-logs-explorer',
+ name: 'Logs Explorer',
+ route: `/project/${ref}/logs/explorer`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-postgres',
+ name: 'Postgres Logs',
+ route: `/project/${ref}/logs/postgres-logs`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-postgrest',
+ name: 'PostgREST Logs',
+ route: `/project/${ref}/logs/postgrest-logs`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-pooler',
+ name: 'Pooler Logs',
+ route: `/project/${ref}/logs/pooler-logs`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-auth',
+ name: 'Auth Logs',
+ route: `/project/${ref}/logs/auth-logs`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-storage',
+ name: 'Storage Logs',
+ route: `/project/${ref}/logs/storage-logs`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-logs-realtime',
+ name: 'Realtime Logs',
+ route: `/project/${ref}/logs/realtime-logs`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
index cda0a21ff0e..84b983b94b5 100644
--- a/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
@@ -31,7 +31,7 @@ import {
cn,
singleThemes,
} from 'ui'
-import { useCommandMenu } from 'ui-patterns/Cmdk'
+import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
import { useProjectContext } from '../ProjectContext'
import {
generateOtherRoutes,
@@ -53,7 +53,7 @@ const NavigationBar = () => {
const { project } = useProjectContext()
const { theme, setTheme } = useTheme()
const { ref: projectRef } = useParams()
- const { setIsOpen } = useCommandMenu()
+ const setCommandMenuOpen = useSetCommandMenuOpen()
const snap = useAppStateSnapshot()
const signOut = useSignOut()
@@ -235,7 +235,7 @@ const NavigationBar = () => {
<NavigationIconButton
size="tiny"
onClick={() => {
- setIsOpen(true)
+ setCommandMenuOpen(true)
snap.setNavigationPanelOpen(false)
}}
type="text"
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx
new file mode 100644
index 00000000000..20b432d04ad
--- /dev/null
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx
@@ -0,0 +1,118 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useProjectSettingsGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-project-settings-general',
+ name: 'General Settings',
+ route: `/project/${ref}/settings/general`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-database',
+ name: 'Database Settings',
+ route: `/project/${ref}/settings/database`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-auth',
+ name: 'Auth Settings',
+ route: `/project/${ref}/settings/auth`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-api',
+ name: 'API Settings',
+ route: `/project/${ref}/settings/api`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-storage',
+ name: 'Storage Settings',
+ route: `/project/${ref}/settings/storage`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-custom-domains',
+ name: 'Custom Domains',
+ route: `/project/${ref}/settings/general#custom-domains`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-restart-project',
+ name: 'Restart project',
+ route: `/project/${ref}/settings/general#restart-project`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-pause-project',
+ name: 'Pause project',
+ route: `/project/${ref}/settings/general#pause-project`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-transfer-project',
+ name: 'Transfer project',
+ route: `/project/${ref}/settings/general#transfer-project`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-delete-project',
+ name: 'Delete project',
+ route: `/project/${ref}/settings/general#delete-project`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-database-password',
+ name: 'Database password',
+ route: `/project/${ref}/settings/general#database-password`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-connection-string',
+ name: 'Connection string',
+ route: `/project/${ref}/settings/general#connection-string`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-connection-pooling',
+ name: 'Connection pooling',
+ route: `/project/${ref}/settings/general#connection-pooling`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-ssl-configuration',
+ name: 'SSL configuration',
+ route: `/project/${ref}/settings/general#ssl-configuration`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-network-restrictions',
+ name: 'Network restrictions',
+ route: `/project/${ref}/settings/general#network-restrictions`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-banned-ips',
+ name: 'Banned IPs',
+ route: `/project/${ref}/settings/general#banned-ips`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-project-settings-log-drains',
+ name: 'Log drains',
+ route: `/project/${ref}/settings/log-drains`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx b/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx
new file mode 100644
index 00000000000..22317d162f4
--- /dev/null
+++ b/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx
@@ -0,0 +1,46 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useReportsGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-reports',
+ name: 'Reports',
+ route: `/project/${ref}/reports`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-reports-api',
+ name: 'API Reports',
+ route: `/project/${ref}/reports/api-overview`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-reports-storage',
+ name: 'Storage Reports',
+ route: `/project/${ref}/reports/storage`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-reports-database',
+ name: 'Database Reports',
+ route: `/project/${ref}/reports/database`,
+ defaultHidden: true,
+ },
+ {
+ id: 'nav-reports-query-performance',
+ name: 'Query Performance Reports',
+ route: `/project/${ref}/reports/query-performance`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.tsx b/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.tsx
new file mode 100644
index 00000000000..0a287f6588d
--- /dev/null
+++ b/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.tsx
@@ -0,0 +1,22 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useSqlEditorGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-sql-editor',
+ name: 'SQL Editor',
+ route: `/project/${ref}/sql`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/StorageLayout/Storage.Commands.tsx b/apps/studio/components/layouts/StorageLayout/Storage.Commands.tsx
new file mode 100644
index 00000000000..77f14d49216
--- /dev/null
+++ b/apps/studio/components/layouts/StorageLayout/Storage.Commands.tsx
@@ -0,0 +1,22 @@
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useStorageGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-storage',
+ name: 'Storage',
+ route: `/project/${ref}/storage`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditor.Commands.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditor.Commands.tsx
new file mode 100644
index 00000000000..f365ab88d16
--- /dev/null
+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditor.Commands.tsx
@@ -0,0 +1,43 @@
+import { Table } from 'lucide-react'
+
+import { useParams } from 'common'
+import { COMMAND_MENU_SECTIONS } from 'components/interfaces/App/CommandMenu/CommandMenu.utils'
+import { orderCommandSectionsByPriority } from 'components/interfaces/App/CommandMenu/ordering'
+import type { CommandOptions } from 'ui-patterns/CommandMenu'
+import { useRegisterCommands } from 'ui-patterns/CommandMenu'
+
+export function useTableEditorGotoCommands(options?: CommandOptions) {
+ let { ref } = useParams()
+ ref ||= '_'
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.ACTIONS,
+ [
+ {
+ id: 'view-data',
+ name: 'View your data',
+ route: `/project/${ref}/editor`,
+ icon: () => <Table />,
+ },
+ ],
+ {
+ ...options,
+ deps: [ref],
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 3 },
+ }
+ )
+
+ useRegisterCommands(
+ COMMAND_MENU_SECTIONS.NAVIGATE,
+ [
+ {
+ id: 'nav-table-editor',
+ name: 'Table Editor',
+ route: `/project/${ref}/editor`,
+ defaultHidden: true,
+ },
+ ],
+ { ...options, deps: [ref] }
+ )
+}
diff --git a/apps/studio/components/layouts/useLayoutNavCommands.ts b/apps/studio/components/layouts/useLayoutNavCommands.ts
new file mode 100644
index 00000000000..d67bbec45f6
--- /dev/null
+++ b/apps/studio/components/layouts/useLayoutNavCommands.ts
@@ -0,0 +1,28 @@
+import { useApiDocsGotoCommands } from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs.Commands'
+import { useAdvisorsGoToCommands } from './AdvisorsLayout/Advisors.Commands'
+import { useAuthGotoCommands } from './AuthLayout/Auth.Commands'
+import { useDatabaseGotoCommands } from './DatabaseLayout/Database.Commands'
+import { useFunctionsGotoCommands } from './FunctionsLayout/Functions.Commands'
+import { useLogsGotoCommands } from './LogsLayout/Logs.Commands'
+import { useProjectSettingsGotoCommands } from './ProjectSettingsLayout/ProjectSettings.Commands'
+import { useReportsGotoCommands } from './ReportsLayout/Reports.Commands'
+import { useStorageGotoCommands } from './StorageLayout/Storage.Commands'
+import { useSqlEditorGotoCommands } from './SQLEditorLayout/SqlEditor.Commands'
+import { useTableEditorGotoCommands } from './TableEditorLayout/TableEditor.Commands'
+import { useIsLoggedIn } from 'common'
+
+export function useLayoutNavCommands() {
+ const isLoggedIn = useIsLoggedIn()
+
+ useTableEditorGotoCommands({ enabled: isLoggedIn })
+ useSqlEditorGotoCommands({ enabled: isLoggedIn })
+ useDatabaseGotoCommands({ enabled: isLoggedIn })
+ useAuthGotoCommands({ enabled: isLoggedIn })
+ useAdvisorsGoToCommands({ enabled: isLoggedIn })
+ useStorageGotoCommands({ enabled: isLoggedIn })
+ useFunctionsGotoCommands({ enabled: isLoggedIn })
+ useLogsGotoCommands({ enabled: isLoggedIn })
+ useReportsGotoCommands({ enabled: isLoggedIn })
+ useApiDocsGotoCommands({ enabled: isLoggedIn })
+ useProjectSettingsGotoCommands({ enabled: isLoggedIn })
+}
diff --git a/apps/studio/components/ui/AISettingsModal.tsx b/apps/studio/components/ui/AISettingsModal.tsx
index b0b3e9ae82b..fc7303c4daf 100644
--- a/apps/studio/components/ui/AISettingsModal.tsx
+++ b/apps/studio/components/ui/AISettingsModal.tsx
@@ -2,8 +2,9 @@ import Link from 'next/link'
import toast from 'react-hot-toast'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
+import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { useAppStateSnapshot } from 'state/app-state'
import {
AlertDescription_Shadcn_,
@@ -18,7 +19,7 @@ import {
const AISettingsModal = () => {
const snap = useAppStateSnapshot()
const selectedOrganization = useSelectedOrganization()
- const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+ const isOptedInToAI = useOrgOptedIntoAi()
const [hasEnabledAISchema, setHasEnabledAISchema] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA,
diff --git a/apps/studio/hooks/misc/useAllowSendAiSchema.ts b/apps/studio/hooks/misc/useAllowSendAiSchema.ts
new file mode 100644
index 00000000000..780ca55c269
--- /dev/null
+++ b/apps/studio/hooks/misc/useAllowSendAiSchema.ts
@@ -0,0 +1,12 @@
+import { IS_PLATFORM } from 'common'
+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { LOCAL_STORAGE_KEYS } from 'lib/constants'
+
+export function useAllowSendAiSchema() {
+ const isOptedIntoAI = useOrgOptedIntoAi()
+ const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
+ const includeSchemaMetadata = (isOptedIntoAI || !IS_PLATFORM) && hasEnabledAISchema
+
+ return includeSchemaMetadata
+}
diff --git a/apps/studio/hooks/misc/useDisallowHipaa.ts b/apps/studio/hooks/misc/useDisallowHipaa.ts
new file mode 100644
index 00000000000..5958b82fb33
--- /dev/null
+++ b/apps/studio/hooks/misc/useDisallowHipaa.ts
@@ -0,0 +1,20 @@
+import { useCallback } from 'react'
+
+import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+
+export function useDisallowHipaa() {
+ const selectedOrganization = useSelectedOrganization()
+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrganization?.slug })
+ const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
+
+ const disallowHipaa = useCallback(
+ (allowed: boolean) => {
+ return hasHipaaAddon ? false : allowed
+ },
+ [hasHipaaAddon]
+ )
+
+ return disallowHipaa
+}
diff --git a/apps/studio/hooks/misc/useOrgOptedIntoAi.ts b/apps/studio/hooks/misc/useOrgOptedIntoAi.ts
new file mode 100644
index 00000000000..49f2c1ec937
--- /dev/null
+++ b/apps/studio/hooks/misc/useOrgOptedIntoAi.ts
@@ -0,0 +1,12 @@
+import { useDisallowHipaa } from 'hooks/misc/useDisallowHipaa'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { OPT_IN_TAGS } from 'lib/constants'
+
+export function useOrgOptedIntoAi() {
+ const selectedOrganization = useSelectedOrganization()
+ const optInTags = selectedOrganization?.opt_in_tags
+ const isOptedIntoAI = optInTags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
+
+ const disallowHipaa = useDisallowHipaa()
+ return disallowHipaa(isOptedIntoAI)
+}
diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsx
index 300e65caea1..51c6847bdf1 100644
--- a/apps/studio/pages/_app.tsx
+++ b/apps/studio/pages/_app.tsx
@@ -35,17 +35,16 @@ import { ErrorInfo, useEffect, useMemo, useRef, useState } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import toast from 'react-hot-toast'
import { PortalToast, Toaster } from 'ui'
+import { CommandProvider } from 'ui-patterns/CommandMenu'
import { ConsentToast } from 'ui-patterns/ConsentToast'
import MetaFaviconsPagesRouter from 'common/MetaFavicons/pages-router'
-import {
- AppBannerWrapper,
- CommandMenuWrapper,
- RouteValidationWrapper,
-} from 'components/interfaces/App'
+import { AppBannerWrapper, RouteValidationWrapper } from 'components/interfaces/App'
+import { StudioCommandMenu } from 'components/interfaces/App/CommandMenu'
import { AppBannerContextProvider } from 'components/interfaces/App/AppBannerWrapperContext'
import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import FeaturePreviewModal from 'components/interfaces/App/FeaturePreview/FeaturePreviewModal'
+import { GenerateSql } from 'components/interfaces/SqlGenerator/SqlGenerator'
import { ErrorBoundaryState } from 'components/ui/ErrorBoundaryState'
import FlagProvider from 'components/ui/Flag/FlagProvider'
import PageTelemetry from 'components/ui/PageTelemetry'
@@ -174,14 +173,16 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
disableTransitionOnChange
>
<AppBannerContextProvider>
- <CommandMenuWrapper>
+ <CommandProvider>
<AppBannerWrapper>
<FeaturePreviewContextProvider>
{getLayout(<Component {...pageProps} />)}
+ <StudioCommandMenu />
+ <GenerateSql />
<FeaturePreviewModal />
</FeaturePreviewContextProvider>
</AppBannerWrapper>
- </CommandMenuWrapper>
+ </CommandProvider>
</AppBannerContextProvider>
</ThemeProvider>
</RouteValidationWrapper>
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
index 88e563b343f..893b8efb3ed 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
@@ -1,5 +1,5 @@
import { EdgeFunctionDetails } from 'components/interfaces/Functions'
-import FunctionsLayout from 'components/layouts/FunctionsLayout'
+import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import type { NextPageWithLayout } from 'types'
const PageLayout: NextPageWithLayout = () => <EdgeFunctionDetails />
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
index d305ac3490c..053397213a9 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
@@ -7,7 +7,7 @@ import { useRouter } from 'next/router'
import { useMemo, useState } from 'react'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
-import FunctionsLayout from 'components/layouts/FunctionsLayout'
+import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import AreaChart from 'components/ui/Charts/AreaChart'
import StackedBarChart from 'components/ui/Charts/StackedBarChart'
import NoPermission from 'components/ui/NoPermission'
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
index 94d90a18b09..29c2e48d83b 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
@@ -1,7 +1,7 @@
import { useParams } from 'common'
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
-import FunctionsLayout from 'components/layouts/FunctionsLayout'
+import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import type { NextPageWithLayout } from 'types'
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
index cb20fc4d122..c3d5282e6d9 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
@@ -1,6 +1,6 @@
import { useParams } from 'common/hooks'
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
-import FunctionsLayout from 'components/layouts/FunctionsLayout'
+import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import type { NextPageWithLayout } from 'types'
diff --git a/apps/studio/pages/project/[ref]/functions/index.tsx b/apps/studio/pages/project/[ref]/functions/index.tsx
index 740ac23c1fa..9a819b83a6f 100644
--- a/apps/studio/pages/project/[ref]/functions/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/index.tsx
@@ -17,7 +17,7 @@ import {
FunctionsEmptyState,
TerminalInstructions,
} from 'components/interfaces/Functions'
-import FunctionsLayout from 'components/layouts/FunctionsLayout'
+import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.ts
index 8fc8d0d976c..4aa575e3702 100644
--- a/apps/studio/state/app-state.ts
+++ b/apps/studio/state/app-state.ts
@@ -58,6 +58,10 @@ export const appState = proxy({
setShowAiSettingsModal: (value: boolean) => {
appState.showAiSettingsModal = value
},
+ showGenerateSqlModal: false,
+ setShowGenerateSqlModal: (value: boolean) => {
+ appState.showGenerateSqlModal = value
+ },
navigationPanelOpen: false,
navigationPanelJustClosed: false,
diff --git a/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx b/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
index 79749b2f09c..ab52fac28b1 100644
--- a/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
+++ b/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
@@ -5,6 +5,7 @@ type ICommandSection = {
name: string
commands: Array<ICommand>
forceMount?: boolean
+ meta?: any
}
const toSectionId = (str: string) => str.toLowerCase().replace(/\s+/g, '-')
diff --git a/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts b/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
index ad91bfa268c..9c53e8afa89 100644
--- a/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
+++ b/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
@@ -11,6 +11,7 @@ type CommandOptions = {
deps?: any[]
enabled?: boolean
forceMountSection?: boolean
+ sectionMeta?: any
orderSection?: OrderSectionInstruction
orderCommands?: OrderCommandsInstruction
}
@@ -32,6 +33,14 @@ const initCommandsState = () => {
if (editIndex === -1) editIndex = state.commandSections.length
state.commandSections[editIndex] ??= section$new(sectionName)
+ if (options?.sectionMeta) {
+ const oldMeta = state.commandSections[editIndex].meta
+ if (!!oldMeta && typeof oldMeta === 'object' && typeof options.sectionMeta === 'object') {
+ state.commandSections[editIndex].meta = { ...oldMeta, ...options.sectionMeta }
+ } else {
+ state.commandSections[editIndex].meta = options.sectionMeta
+ }
+ }
if (options?.forceMountSection) state.commandSections[editIndex].forceMount = true
diff --git a/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx b/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx
index 5b8f56fe44b..2827eccd9f3 100644
--- a/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx
+++ b/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx
@@ -3,15 +3,19 @@ import { Inbox } from 'lucide-react'
import { useRegisterCommands } from '..'
import { BASE_PATH } from './shared/constants'
-const useChangelogCommand = () => {
- useRegisterCommands('Updates', [
- {
- id: 'changelog',
- name: 'Changelog',
- route: BASE_PATH ? 'https://supabase.com/changelog' : '/changelog',
- icon: () => <Inbox />,
- },
- ])
+const useChangelogCommand = ({ enabled = true }: { enabled?: boolean } = {}) => {
+ useRegisterCommands(
+ 'Updates',
+ [
+ {
+ id: 'changelog',
+ name: 'Changelog',
+ route: BASE_PATH ? 'https://supabase.com/changelog' : '/changelog',
+ icon: () => <Inbox />,
+ },
+ ],
+ { enabled }
+ )
}
export { useChangelogCommand }
diff --git a/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx
index 469a9b4d62d..b7215873082 100644
--- a/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx
+++ b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx
@@ -31,7 +31,6 @@ const useDocsAiCommands = ({
setCommandPage(DOCS_AI_COMMANDS.PAGE_NAME, true)
},
icon: () => <AiIconAnimation />,
- className: 'text-brand',
},
].map(modify),
options
diff --git a/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx b/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx
index 119d7ac035c..b7d9bf3530c 100644
--- a/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx
+++ b/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx
@@ -4,7 +4,7 @@ import { useMemo } from 'react'
import { useRegisterCommands, useSetCommandMenuOpen, type ICommand } from '..'
import { BASE_PATH } from './shared/constants'
-const useSupportCommands = () => {
+const useSupportCommands = ({ enabled = true }: { enabled?: boolean } = {}) => {
const setOpen = useSetCommandMenuOpen()
const commands = useMemo(
@@ -41,7 +41,7 @@ const useSupportCommands = () => {
[setOpen]
)
- useRegisterCommands('Support', commands)
+ useRegisterCommands('Support', commands, { enabled })
}
export { useSupportCommands }
diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts b/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts
index f2af9154855..87d9e92316b 100644
--- a/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts
+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts
@@ -172,6 +172,7 @@ const useAiChat = ({ messageTemplate = (message) => message, setIsLoading }: Use
eventSourceRef.current = undefined
setIsResponding(false)
setHasError(false)
+ setCurrentMessageIndex(1)
dispatchMessage({
type: 'reset',
})