The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Sidebar manager (#39795)
Saxon Fletcher738c568e6ba1
diff --git a/apps/studio/components/interfaces/Account/Preferences/HotkeySettings.tsx b/apps/studio/components/interfaces/Account/Preferences/HotkeySettings.tsxindex 851df04e4c0..4d92c83a137 100644--- a/apps/studio/components/interfaces/Account/Preferences/HotkeySettings.tsx+++ b/apps/studio/components/interfaces/Account/Preferences/HotkeySettings.tsx@@ -1,4 +1,5 @@import { LOCAL_STORAGE_KEYS } from 'common'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import Panel from 'components/ui/Panel'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { KeyboardShortcut, Toggle } from 'ui'@@ -13,7 +14,7 @@ export const HotkeySettings = () => {true)const [aiAssistantEnabled, setAiAssistantEnabled] = useLocalStorageQuery(- LOCAL_STORAGE_KEYS.HOTKEY_AI_ASSISTANT,+ LOCAL_STORAGE_KEYS.HOTKEY_SIDEBAR(SIDEBAR_KEYS.AI_ASSISTANT),true)diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsxindex 8678bc08b49..0732dbec742 100644--- a/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx@@ -6,6 +6,8 @@ import { Logs } from 'icons'import { BASE_PATH } from 'lib/constants'import { useParams } from 'common'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { useTheme } from 'next-themes'import { useEffect, useState } from 'react'@@ -13,6 +15,7 @@ export const OverviewLearnMore = () => {const [isMounted, setIsMounted] = useState(false)const { ref } = useParams()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { theme, resolvedTheme } = useTheme()useEffect(() => {@@ -48,9 +51,9 @@ export const OverviewLearnMore = () => {{label: 'Ask Assistant',onClick: () => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Auth Help',- open: true,initialInput:'Look at my logs related to Supabase Auth and help me debug the recent errors.',suggestions: {diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsxindex 9f97fe8dc93..c938d273cd1 100644--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx@@ -8,6 +8,8 @@ import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {Button,DropdownMenu,@@ -37,6 +39,7 @@ export const PolicyRow = ({onSelectDeletePolicy = noop,}: PolicyRowProps) => {const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { can: canUpdatePolicies } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,'policies'@@ -119,9 +122,9 @@ export const PolicyRow = ({className="space-x-2"onClick={() => {const sql = generatePolicyUpdateSQL(policy)+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: `Update policy ${policy.name}`,- open: true,sqlSnippets: [sql],initialInput: `Update the policy with name \"${policy.name}\" in the ${policy.schema} schema on the ${policy.table} table. It should...`,suggestions: {diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsxindex 40953561bd3..3fd18c5cf46 100644--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx@@ -9,6 +9,8 @@ import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { AiIconAnimation, Badge, CardTitle } from 'ui'import type { PolicyTable } from './PolicyTableRow.types'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'interface PolicyTableRowHeaderProps {table: PolicyTable@@ -25,6 +27,7 @@ export const PolicyTableRowHeader = ({}: PolicyTableRowHeaderProps) => {const { ref } = useParams()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { can: canCreatePolicies } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,@@ -101,9 +104,9 @@ export const PolicyTableRowHeader = ({type="default"className="px-1"onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Create new policy',- open: true,initialInput: `Create and name a new policy for the ${table.schema} schema on the ${table.name} table that ...`,})}}diff --git a/apps/studio/components/interfaces/BranchManagement/ReviewWithAI.tsx b/apps/studio/components/interfaces/BranchManagement/ReviewWithAI.tsxindex fe63f11d8dd..1d2204ad7ad 100644--- a/apps/studio/components/interfaces/BranchManagement/ReviewWithAI.tsx+++ b/apps/studio/components/interfaces/BranchManagement/ReviewWithAI.tsx@@ -6,6 +6,8 @@ import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { tablesToSQL } from 'lib/helpers'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { AiIconAnimation } from 'ui'interface ReviewWithAIProps {@@ -24,6 +26,7 @@ export const ReviewWithAI = ({disabled = false,}: ReviewWithAIProps) => {const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { data: selectedOrg } = useSelectedOrganizationQuery()const { mutate: sendEvent } = useSendEventMutation()@@ -75,9 +78,9 @@ export const ReviewWithAI = ({})}+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: `Review merge: ${currentBranch.name} → ${mainBranch.name}`,- open: true,sqlSnippets: sqlSnippets.length > 0 ? sqlSnippets : undefined,initialInput: `I want to run the attached database changes on my production database branch as part of a branch merge from "${currentBranch.name}" into "${mainBranch.name || 'main'}". I've included the current production database schema as extra context. Please analyze the proposed schema changes and provide concise feedback on their impact on the production schema including any migration concerns and potential conflicts.`,suggestions: {diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsxindex 8832787fa65..1f0953c369d 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx@@ -5,10 +5,12 @@ import Link from 'next/link'import { useRouter } from 'next/router'import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {Button,DropdownMenu,@@ -44,6 +46,7 @@ const FunctionList = ({const router = useRouter()const { data: selectedProject } = useSelectedProjectQuery()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { data: functions } = useDatabaseFunctionsQuery({projectRef: selectedProject?.ref,@@ -168,9 +171,9 @@ const FunctionList = ({<DropdownMenuItemclassName="space-x-2"onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: `Update function ${x.name}`,- open: true,initialInput: 'Update this function to do...',suggestions: {title:diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsxindex 7dbaaaae4bd..d504ba1bc1a 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx@@ -11,6 +11,7 @@ import AlertError from 'components/ui/AlertError'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import SchemaSelector from 'components/ui/SchemaSelector'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'import { useSchemasQuery } from 'data/database/schemas-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'@@ -18,6 +19,7 @@ import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {AiIconAnimation,Card,@@ -52,6 +54,7 @@ const FunctionsList = ({const { search } = useParams()const { data: project } = useSelectedProjectQuery()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const filterString = search ?? ''@@ -200,13 +203,13 @@ const FunctionsList = ({disabled={!canCreateFunctions}className="px-1 pointer-events-auto"icon={<AiIconAnimation size={16} />}- onClick={() =>+ onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Create new function',- open: true,initialInput: `Create a new function for the schema ${selectedSchema} that does ...`,})- }+ }}tooltip={{content: {side: 'bottom',diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsxindex 2690209c904..0374a3758ee 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx@@ -3,10 +3,12 @@ import { includes, sortBy } from 'lodash'import { Check, Copy, Edit, Edit2, MoreVertical, Trash, X } from 'lucide-react'import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useDatabaseTriggersQuery } from 'data/database-triggers/database-triggers-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {Badge,Button,@@ -43,6 +45,7 @@ const TriggerList = ({}: TriggerListProps) => {const { data: project } = useSelectedProjectQuery()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { data: triggers } = useDatabaseTriggersQuery({projectRef: project?.ref,@@ -171,9 +174,9 @@ const TriggerList = ({className="space-x-2"onClick={() => {const sql = generateTriggerCreateSQL(x)+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: `Update trigger ${X.name}`,- open: true,initialInput: `Update this trigger which exists on the ${x.schema}.${x.table} table to...`,suggestions: {title:diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsxindex 1f5d10fe750..5f662b3e54c 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx@@ -10,6 +10,7 @@ import AlertError from 'components/ui/AlertError'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import SchemaSelector from 'components/ui/SchemaSelector'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useDatabaseTriggersQuery } from 'data/database-triggers/database-triggers-query'import { useTablesQuery } from 'data/tables/tables-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'@@ -17,6 +18,7 @@ import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useIsProtectedSchema, useProtectedSchemas } from 'hooks/useProtectedSchemas'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {AiIconAnimation,Button,@@ -49,6 +51,7 @@ const TriggersList = ({}: TriggersListProps) => {const { data: project } = useSelectedProjectQuery()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [filterString, setFilterString] = useQueryState(@@ -138,10 +141,10 @@ const TriggersList = ({disabled={!hasTables || !canCreateTriggers}className="px-1 pointer-events-auto"icon={<AiIconAnimation size={16} />}- onClick={() =>+ onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Create new trigger',- open: true,initialInput: `Create a new trigger for the schema ${selectedSchema} that does ...`,suggestions: {title:@@ -162,7 +165,7 @@ const TriggersList = ({],},})- }+ }}tooltip={{content: {side: 'bottom',diff --git a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsxindex 9412f8ae035..d591e1cb74d 100644--- a/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx+++ b/apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionButton.tsx@@ -19,13 +19,15 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from 'ui'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'export const DeployEdgeFunctionButton = () => {const router = useRouter()const { ref } = useParams()const { data: org } = useSelectedOrganizationQuery()const snap = useAiAssistantStateSnapshot()-+ const { openSidebar } = useSidebarManagerSnapshot()const { mutate: sendEvent } = useSendEventMutation()return (@@ -85,9 +87,9 @@ export const DeployEdgeFunctionButton = () => {<DropdownMenuItemclassName="gap-4"onSelect={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Create new edge function',- open: true,initialInput: `Create a new edge function that ...`,suggestions: {title:diff --git a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsxindex a89cd1c85a0..fd842256727 100644--- a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx+++ b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx@@ -8,11 +8,13 @@ import { ScaffoldSectionTitle } from 'components/layouts/Scaffold'import { DocsButton } from 'components/ui/DocsButton'import { ResourceItem } from 'components/ui/Resource/ResourceItem'import { ResourceList } from 'components/ui/Resource/ResourceList'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { DOCS_URL } from 'lib/constants'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {AiIconAnimation,Button,@@ -38,6 +40,7 @@ export const FunctionsEmptyState = () => {const { ref } = useParams()const router = useRouter()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { mutate: sendEvent } = useSendEventMutation()const { data: org } = useSelectedOrganizationQuery()@@ -95,9 +98,9 @@ export const FunctionsEmptyState = () => {<Buttontype="default"onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Create new edge function',- open: true,initialInput: 'Create a new edge function that ...',suggestions: {title:diff --git a/apps/studio/components/interfaces/Home/AdvisorWidget.tsx b/apps/studio/components/interfaces/Home/AdvisorWidget.tsxindex 102ebdd4229..9a7555a3249 100644--- a/apps/studio/components/interfaces/Home/AdvisorWidget.tsx+++ b/apps/studio/components/interfaces/Home/AdvisorWidget.tsx@@ -27,6 +27,8 @@ import {TabsTrigger_Shadcn_ as TabsTrigger,} from 'ui'import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'interface SlowQuery {rolname: string@@ -45,6 +47,7 @@ export const AdvisorWidget = () => {})const snap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const securityLints = useMemo(() => (lints ?? []).filter((lint: Lint) => lint.categories.includes('SECURITY')),@@ -147,9 +150,9 @@ export const AdvisorWidget = () => {onClick={(e) => {e.stopPropagation()e.preventDefault()+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Summarize lint',- open: true,initialInput: `Summarize the issue and suggest fixes for the following lint item:Title: ${lintInfoMap.find((item) => item.name === lint.name)?.title ?? lint.title}Entity: ${(lint.metadata && (lint.metadata.entity || (lint.metadata.schema && lint.metadata.name && `${lint.metadata.schema}.${lint.metadata.name}`))) ?? 'N/A'}diff --git a/apps/studio/components/interfaces/HomeNew/AdvisorSection.tsx b/apps/studio/components/interfaces/HomeNew/AdvisorSection.tsxindex d5d302a7cdc..492e484a661 100644--- a/apps/studio/components/interfaces/HomeNew/AdvisorSection.tsx+++ b/apps/studio/components/interfaces/HomeNew/AdvisorSection.tsx@@ -9,11 +9,13 @@ import {LintCategoryBadge,lintInfoMap,} from 'components/interfaces/Linter/Linter.utils'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { Lint, useProjectLintsQuery } from 'data/lint/lint-query'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {AiIconAnimation,Button,@@ -43,6 +45,7 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: boconst snap = useAiAssistantStateSnapshot()const { mutate: sendEvent } = useSendEventMutation()const { data: organization } = useSelectedOrganizationQuery()+ const { openSidebar } = useSidebarManagerSnapshot()const [selectedLint, setSelectedLint] = useState<Lint | null>(null)@@ -64,7 +67,7 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo}, [totalErrors])const handleAskAssistant = useCallback(() => {- snap.toggleAssistant()+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)if (projectRef && organization?.slug) {sendEvent({action: 'home_advisor_ask_assistant_clicked',@@ -77,7 +80,7 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo},})}- }, [snap, sendEvent, projectRef, organization, totalErrors])+ }, [sendEvent, openSidebar, projectRef, organization, totalErrors])const handleCardClick = useCallback((lint: Lint) => {@@ -150,9 +153,9 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: boonClick={(e) => {e.stopPropagation()e.preventDefault()+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Summarize lint',- open: true,initialInput: createLintSummaryPrompt(lint),})if (projectRef && organization?.slug) {diff --git a/apps/studio/components/interfaces/HomeNew/GettingStarted/GettingStartedSection.tsx b/apps/studio/components/interfaces/HomeNew/GettingStarted/GettingStartedSection.tsxindex 165faed1418..cd220809d3f 100644--- a/apps/studio/components/interfaces/HomeNew/GettingStarted/GettingStartedSection.tsx+++ b/apps/studio/components/interfaces/HomeNew/GettingStarted/GettingStartedSection.tsx@@ -4,11 +4,13 @@ import { useCallback, useMemo, useState } from 'react'import { useParams } from 'common'import { FRAMEWORKS } from 'components/interfaces/Connect/Connect.constants'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { BASE_PATH } from 'lib/constants'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { Button, Card, CardContent, ToggleGroup, ToggleGroupItem } from 'ui'import { FrameworkSelector } from './FrameworkSelector'import { GettingStarted } from './GettingStarted'@@ -36,6 +38,7 @@ export function GettingStartedSection({ value, onChange }: GettingStartedSectionconst { data: organization } = useSelectedOrganizationQuery()const { mutate: sendEvent } = useSendEventMutation()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const [selectedFramework, setSelectedFramework] = useState<string>(DEFAULT_FRAMEWORK_KEY)const workflow: 'no-code' | 'code' | null = value === 'code' || value === 'no-code' ? value : null@@ -44,8 +47,11 @@ export function GettingStartedSection({ value, onChange }: GettingStartedSectionconst statuses = useGettingStartedProgress()const openAiChat = useCallback(- (name: string, initialInput: string) => aiSnap.newChat({ name, open: true, initialInput }),- [aiSnap]+ (name: string, initialInput: string) => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)+ aiSnap.newChat({ name, initialInput })+ },+ [aiSnap, openSidebar])const connectPresetLinks = useMemo(() => {diff --git a/apps/studio/components/interfaces/Linter/LintDetail.tsx b/apps/studio/components/interfaces/Linter/LintDetail.tsxindex d27463cf257..f5c04d4d806 100644--- a/apps/studio/components/interfaces/Linter/LintDetail.tsx+++ b/apps/studio/components/interfaces/Linter/LintDetail.tsx@@ -8,6 +8,8 @@ import { ExternalLink } from 'lucide-react'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { AiIconAnimation, Button } from 'ui'import { EntityTypeIcon, LintCTA, LintEntity } from './Linter.utils'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'interface LintDetailProps {lint: Lint@@ -17,6 +19,7 @@ interface LintDetailProps {const LintDetail = ({ lint, projectRef, onAskAssistant }: LintDetailProps) => {const snap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()return (<div>@@ -41,9 +44,9 @@ const LintDetail = ({ lint, projectRef, onAskAssistant }: LintDetailProps) => {icon={<AiIconAnimation className="scale-75 w-3 h-3" />}onClick={() => {onAskAssistant?.()+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Summarize lint',- open: true,initialInput: createLintSummaryPrompt(lint),})}}diff --git a/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsx b/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsxindex 8bed6a1596c..9a8019083d3 100644--- a/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsx+++ b/apps/studio/components/interfaces/Realtime/Inspector/EmptyRealtime.tsx@@ -2,17 +2,20 @@ import { AiIconAnimation, Button, Card, cn } from 'ui'import Link from 'next/link'import { AnimatedCursors } from './AnimatedCursors'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'/*** Acts as a container component for the entire log display*/export const EmptyRealtime = ({ projectRef }: { projectRef: string }) => {const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const handleCreateTriggerWithAssistant = () => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: `Realtime`,- open: true,initialInput: `Help me set up a realtime experience for my project`,})}diff --git a/apps/studio/components/interfaces/Reports/ReportPadding.tsx b/apps/studio/components/interfaces/Reports/ReportPadding.tsxindex 1f0261bd60a..a002a9846af 100644--- a/apps/studio/components/interfaces/Reports/ReportPadding.tsx+++ b/apps/studio/components/interfaces/Reports/ReportPadding.tsx@@ -1,19 +1,15 @@import { PropsWithChildren } from 'react'-import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { cn } from 'ui'/*** Standardized padding and width layout for non-custom reports*/const ReportPadding = ({ children }: PropsWithChildren<{}>) => {- const snap = useAiAssistantStateSnapshot()-return (<divclassName={cn(- 'flex flex-col flex-grow gap-4 px-5 py-6 mx-auto 1xl:px-28 lg:px-16 2xl:px-32 w-full',- snap.open ? 'xl:px-6' : 'xl:px-22'+ 'flex flex-col flex-grow gap-4 px-5 py-6 mx-auto 1xl:px-28 lg:px-16 2xl:px-32 w-full @lg:px-6 @xl:px-22')}>{children}diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsxindex 9d7c268d827..bedc4df9f4a 100644--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx@@ -4,10 +4,12 @@ import { MutableRefObject, useEffect, useRef, useState } from 'react'import { useDebounce } from '@uidotdev/usehooks'import { LOCAL_STORAGE_KEYS, useParams } from 'common'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useProfile } from 'lib/profile'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { useTabsStateSnapshot } from 'state/tabs'import { cn } from 'ui'@@ -55,6 +57,7 @@ const MonacoEditor = ({const snapV2 = useSqlEditorV2StateSnapshot()const tabsSnap = useTabsStateSnapshot()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const [intellisenseEnabled] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,@@ -112,9 +115,9 @@ const MonacoEditor = ({const selectedValue = (editorRef?.current as any).getModel().getValueInRange((editorRef?.current as any)?.getSelection())+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Explain code section',- open: true,sqlSnippets: [selectedValue],initialInput: 'Can you explain this section to me in more detail?',})diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex 58b82051866..8614d72f2fa 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -8,6 +8,7 @@ import { toast } from 'sonner'import { LOCAL_STORAGE_KEYS, useParams } from 'common'import ResizableAIWidget from 'components/ui/AIEditor/ResizableAIWidget'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { GridFooter } from 'components/ui/GridFooter'import { useSqlTitleGenerateMutation } from 'data/ai/sql-title-mutation'import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'@@ -28,6 +29,7 @@ import { useProfile } from 'lib/profile'import { wrapWithRoleImpersonation } from 'lib/role-impersonation'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import {isRoleImpersonationEnabled,useGetImpersonatedRoleState,@@ -86,6 +88,7 @@ export const SQLEditor = () => {const queryClient = useQueryClient()const tabs = useTabsStateSnapshot()const aiSnap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const snapV2 = useSqlEditorV2StateSnapshot()const getImpersonatedRoleState = useGetImpersonatedRoleState()const databaseSelectorState = useDatabaseSelectorStateSnapshot()@@ -380,9 +383,9 @@ export const SQLEditor = () => {try {const snippet = snapV2.snippets[id]const result = snapV2.results[id]?.[0]+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)aiSnap.newChat({name: 'Debug SQL snippet',- open: true,sqlSnippets: [(snippet.snippet.content?.sql ?? '').replace(sqlAiDisclaimerComment, '').trim(),],diff --git a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx b/apps/studio/components/layouts/AppLayout/AssistantButton.tsxindex afe8bcba9fd..d9e8b835dd9 100644--- a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx+++ b/apps/studio/components/layouts/AppLayout/AssistantButton.tsx@@ -3,11 +3,13 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { AiIconAnimation, KeyboardShortcut } from 'ui'+import { SIDEBAR_KEYS } from '../ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'export const AssistantButton = () => {- const snap = useAiAssistantStateSnapshot()+ const { toggleSidebar } = useSidebarManagerSnapshot()const [isAIAssistantHotkeyEnabled] = useLocalStorageQuery<boolean>(- LOCAL_STORAGE_KEYS.HOTKEY_AI_ASSISTANT,+ LOCAL_STORAGE_KEYS.HOTKEY_SIDEBAR(SIDEBAR_KEYS.AI_ASSISTANT),true)@@ -18,7 +20,7 @@ export const AssistantButton = () => {id="assistant-trigger"className="rounded-none w-[32px] h-[30px] flex items-center justify-center p-0 hover:bg-brand-400"onClick={() => {- snap.toggleAssistant()+ toggleSidebar(SIDEBAR_KEYS.AI_ASSISTANT)}}tooltip={{content: {diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsxindex cf226207bb2..87a65ed455e 100644--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/HelpPopover.tsx@@ -20,12 +20,15 @@ import {PopoverTrigger_Shadcn_,Popover_Shadcn_,} from 'ui'+import { SIDEBAR_KEYS } from '../LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'export const HelpPopover = () => {const router = useRouter()const { data: project } = useSelectedProjectQuery()const { data: org } = useSelectedOrganizationQuery()const snap = useAiAssistantStateSnapshot()+ const { openSidebar } = useSidebarManagerSnapshot()const { mutate: sendEvent } = useSendEventMutation()@@ -69,9 +72,9 @@ export const HelpPopover = () => {size="tiny"icon={<AiIconAnimation allowHoverEffect size={14} />}onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Support',- open: true,initialInput: `I need help with my project`,suggestions: {title:diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsxnew file mode 100644index 00000000000..6ae847d36c1--- /dev/null+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider.tsx@@ -0,0 +1,27 @@+import { useRouter } from 'next/router'+import { PropsWithChildren, useEffect } from 'react'+import { useRegisterSidebar, useSidebarManagerSnapshot } from 'state/sidebar-manager-state'+import { AIAssistant } from 'components/ui/AIAssistantPanel/AIAssistant'++export const SIDEBAR_KEYS = {+ AI_ASSISTANT: 'ai-assistant',+} as const++export const LayoutSidebarProvider = ({ children }: PropsWithChildren) => {+ useRegisterSidebar(SIDEBAR_KEYS.AI_ASSISTANT, () => <AIAssistant />, {}, 'i')++ const router = useRouter()+ const { openSidebar } = useSidebarManagerSnapshot()++ // Handle sidebar URL parameter+ useEffect(() => {+ if (!router.isReady) return++ const sidebarParam = router.query.sidebar+ if (typeof sidebarParam === 'string') {+ openSidebar(sidebarParam)+ }+ }, [router.isReady, router.query.sidebar, openSidebar])++ return <>{children}</>+}diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsxnew file mode 100644index 00000000000..1c5cef6bb60--- /dev/null+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsx@@ -0,0 +1,72 @@+import { act, screen, waitFor } from '@testing-library/react'+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'++import { LayoutSidebar } from './index'+import { LayoutSidebarProvider, SIDEBAR_KEYS } from './LayoutSidebarProvider'+import { sidebarManagerState } from 'state/sidebar-manager-state'+import { render } from 'tests/helpers'+import { routerMock } from 'tests/lib/route-mock'+import { ResizablePanel, ResizablePanelGroup } from 'ui'++vi.mock('components/ui/AIAssistantPanel/AIAssistant', () => ({+ AIAssistant: () => <div data-testid="ai-assistant-sidebar">AI Assistant</div>,+}))++const resetSidebarManagerState = () => {+ Object.keys(sidebarManagerState.sidebars).forEach((id) => {+ sidebarManagerState.unregisterSidebar(id)+ })+ sidebarManagerState.closeActive()+}++describe('LayoutSidebar', () => {+ beforeEach(() => {+ routerMock.setCurrentUrl('/projects/default')+ })++ afterEach(() => {+ resetSidebarManagerState()+ localStorage.clear()+ vi.clearAllMocks()+ })++ const renderSidebar = () =>+ render(+ <ResizablePanelGroup direction="horizontal">+ <ResizablePanel>+ <div />+ </ResizablePanel>+ <LayoutSidebarProvider>+ <LayoutSidebar />+ </LayoutSidebarProvider>+ </ResizablePanelGroup>+ )++ it('does not render when there is no active sidebar', () => {+ renderSidebar()++ expect(screen.queryByTestId('ai-assistant-sidebar')).toBeNull()+ })++ it('renders the active sidebar content when toggled on', async () => {+ renderSidebar()++ await waitFor(() => {+ expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.AI_ASSISTANT]).toBeDefined()+ })++ act(() => {+ sidebarManagerState.toggleSidebar(SIDEBAR_KEYS.AI_ASSISTANT)+ })++ expect(await screen.findByTestId('ai-assistant-sidebar')).toBeInTheDocument()+ })++ it('auto-opens when sidebar query param matches a registered sidebar', async () => {+ routerMock.setCurrentUrl(`/?sidebar=${SIDEBAR_KEYS.AI_ASSISTANT}`)++ renderSidebar()++ await screen.findByTestId('ai-assistant-sidebar')+ })+})diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.tsxnew file mode 100644index 00000000000..7d613b538be--- /dev/null+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.tsx@@ -0,0 +1,32 @@+import { Fragment } from 'react'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'+import { ResizableHandle, ResizablePanel, cn } from 'ui'++export const LayoutSidebar = () => {+ const { activeSidebar } = useSidebarManagerSnapshot()++ if (!activeSidebar?.component) {+ return null+ }++ return (+ <Fragment>+ <ResizableHandle withHandle />+ <ResizablePanel+ id="panel-side"+ key={activeSidebar.id}+ defaultSize={30}+ minSize={30}+ maxSize={50}+ className={cn(+ 'border-l bg fixed z-40 right-0 top-0 bottom-0',+ 'w-screen h-[100dvh]',+ 'md:absolute md:h-auto md:w-3/4',+ 'xl:relative xl:border-l-0'+ )}+ >+ {activeSidebar.component()}+ </ResizablePanel>+ </Fragment>+ )+}diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsxindex 98b53f5f2f2..68d6e88b359 100644--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx@@ -2,21 +2,16 @@ import { AnimatePresence, motion } from 'framer-motion'import Head from 'next/head'import { useRouter } from 'next/router'import { forwardRef, Fragment, PropsWithChildren, ReactNode, useEffect, useState } from 'react'--import { LOCAL_STORAGE_KEYS, useParams, useFlag } from 'common'+import { useParams, useFlag } from 'common'import { CreateBranchModal } from 'components/interfaces/BranchManagement/CreateBranchModal'import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'-import { AIAssistant } from 'components/ui/AIAssistantPanel/AIAssistant'import { Loading } from 'components/ui/Loading'import { ResourceExhaustionWarningBanner } from 'components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner'import { useCustomContent } from 'hooks/custom-content/useCustomContent'-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { withAuth } from 'hooks/misc/withAuth'-import { useHotKey } from 'hooks/ui/useHotKey'import { PROJECT_STATUS } from 'lib/constants'-import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { useAppStateSnapshot } from 'state/app-state'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { cn, ResizableHandle, ResizablePanel, ResizablePanelGroup } from 'ui'@@ -34,6 +29,8 @@ import RestartingState from './RestartingState'import { RestoreFailedState } from './RestoreFailedState'import RestoringState from './RestoringState'import { UpgradingState } from './UpgradingState'+import { LayoutSidebar } from './LayoutSidebar'+import { LayoutSidebarProvider } from './LayoutSidebar/LayoutSidebarProvider'// [Joshen] This is temporary while we unblock users from managing their project// if their project is not responding well for any reason. Eventually needs a bit of an overhaul@@ -93,19 +90,10 @@ export const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<Projecconst { data: selectedOrganization } = useSelectedOrganizationQuery()const { data: selectedProject } = useSelectedProjectQuery()const { mobileMenuOpen, showSidebar, setMobileMenuOpen } = useAppStateSnapshot()- const aiSnap = useAiAssistantStateSnapshot()- const [isAiAssistantHotkeyEnabled] = useLocalStorageQuery<boolean>(- LOCAL_STORAGE_KEYS.HOTKEY_AI_ASSISTANT,- true- )const { appTitle } = useCustomContent(['app:title'])const titleSuffix = appTitle || 'Supabase'- useHotKey(() => aiSnap.toggleAssistant(), 'i', [aiSnap], {- enabled: isAiAssistantHotkeyEnabled,- })-const editor = useEditorType()const forceShowProductMenu = editor === undefinedconst sideBarIsOpen = forceShowProductMenu || showSidebar@@ -227,25 +215,9 @@ export const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<Projec)}</main></ResizablePanel>- {isClient && aiSnap.open && (- <>- <ResizableHandle withHandle />- <ResizablePanel- id="panel-assistant"- defaultSize={30}- minSize={30}- maxSize={50}- className={cn(- 'border-l bg fixed z-40 right-0 top-0 bottom-0',- 'w-screen h-[100dvh]',- 'md:absolute md:h-auto md:w-3/4',- 'xl:relative xl:border-l-0'- )}- >- <AIAssistant className="w-full h-[100dvh] md:h-full max-h-[100dvh]" />- </ResizablePanel>- </>- )}+ <LayoutSidebarProvider>+ <LayoutSidebar />+ </LayoutSidebarProvider></ResizablePanelGroup></ResizablePanel></ResizablePanelGroup>diff --git a/apps/studio/components/layouts/Tabs/NewTab.tsx b/apps/studio/components/layouts/Tabs/NewTab.tsxindex 99dbe052b96..5ccaa92bf10 100644--- a/apps/studio/components/layouts/Tabs/NewTab.tsx+++ b/apps/studio/components/layouts/Tabs/NewTab.tsx@@ -23,6 +23,7 @@ import { useProfile } from 'lib/profile'import { AssistantMessageType, useAiAssistantStateSnapshot } from 'state/ai-assistant-state'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { useTableEditorStateSnapshot } from 'state/table-editor'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { createTabId, useTabsStateSnapshot } from 'state/tabs'import {AiIconAnimation,@@ -37,6 +38,7 @@ import {import { useEditorType } from '../editors/EditorsLayout.hooks'import { ActionCard } from './ActionCard'import { RecentItems } from './RecentItems'+import { SIDEBAR_KEYS } from '../ProjectLayout/LayoutSidebar/LayoutSidebarProvider'const NEW_PROJECT_THRESHOLD_DAYS = 7const TABLE_QUICKSTART_FLAG = 'tableQuickstart'@@ -59,7 +61,7 @@ export function NewTab() {const snapV2 = useSqlEditorV2StateSnapshot()const tabs = useTabsStateSnapshot()const aiSnap = useAiAssistantStateSnapshot()-+ const { openSidebar } = useSidebarManagerSnapshot()const [isCreatingChat, setIsCreatingChat] = useState(false)const [templates] = partition(SQL_TEMPLATES, { type: 'template' })const [quickstarts] = partition(SQL_TEMPLATES, { type: 'quickstart' })@@ -103,9 +105,9 @@ export function NewTab() {setIsCreatingChat(true)try {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)const chatId = aiSnap.newChat({name: 'Create a database table',- open: true,})if (!chatId) {diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxindex 4678cf0a7af..e0eb19df63c 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -24,6 +24,8 @@ import { BASE_PATH, IS_PLATFORM } from 'lib/constants'import uuidv4 from 'lib/uuid'import type { AssistantModel } from 'state/ai-assistant-state'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { Button, cn, KeyboardShortcut } from 'ui'import { Admonition } from 'ui-patterns'@@ -59,6 +61,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {const disablePrompts = useFlag('disableAssistantPrompts')const { snippets } = useSqlEditorV2StateSnapshot()const snap = useAiAssistantStateSnapshot()+ const { closeSidebar, isSidebarOpen } = useSidebarManagerSnapshot()const isPaidPlan = selectedOrganization?.plan?.id !== 'free'@@ -432,11 +435,11 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {}, [snap.initialInput])useEffect(() => {- if (snap.open && isInSQLEditor && !!snippetContent) {+ if (isSidebarOpen(SIDEBAR_KEYS.AI_ASSISTANT) && isInSQLEditor && !!snippetContent) {snap.setSqlSnippets([{ label: 'Current Query', content: snippetContent }])}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [snap.open, isInSQLEditor, snippetContent])+ }, [isSidebarOpen, isInSQLEditor, snippetContent])return (<ErrorBoundary@@ -457,11 +460,11 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {},]}>- <div className={cn('flex flex-col h-full', className)}>+ <div className={cn('flex flex-col h-full w-full md:h-full max-h-[100dvh]', className)}><AIAssistantHeaderisChatLoading={isChatLoading}onNewChat={snap.newChat}- onCloseAssistant={snap.closeAssistant}+ onCloseAssistant={() => closeSidebar(SIDEBAR_KEYS.AI_ASSISTANT)}showMetadataWarning={showMetadataWarning}updatedOptInSinceMCP={updatedOptInSinceMCP}isHipaaProjectDisallowed={isHipaaProjectDisallowed as boolean}diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsxindex 60585ed6662..3637ef1edf7 100644--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx@@ -20,6 +20,8 @@ import {TooltipContent,} from 'ui'import { ButtonTooltip } from '../ButtonTooltip'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'interface EditQueryButtonProps {id?: string@@ -41,7 +43,7 @@ export const EditQueryButton = ({const { newQuery } = useNewQuery()const sqlEditorSnap = useSqlEditorV2StateSnapshot()- const snap = useAiAssistantStateSnapshot()+ const { closeSidebar } = useSidebarManagerSnapshot()const isInSQLEditor = router.pathname.includes('/sql')const isInNewSnippet = router.pathname.endsWith('/sql')@@ -79,7 +81,7 @@ export const EditQueryButton = ({// This component needs to be updated to work with local EditorPanel state// For now, fall back to creating a new queryif (sql) newQuery(sql, title)- snap.closeAssistant()+ closeSidebar(SIDEBAR_KEYS.AI_ASSISTANT)} else {if (sql) newQuery(sql, title)}diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsxindex c8fa03fb8d0..b813c3babb6 100644--- a/apps/studio/pages/project/[ref]/functions/new.tsx+++ b/apps/studio/pages/project/[ref]/functions/new.tsx@@ -42,6 +42,8 @@ import {TooltipContent,TooltipTrigger,} from 'ui'+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'// Array of adjectives and nouns for random function name generationconst ADJECTIVES = [@@ -104,6 +106,7 @@ const NewFunctionPage = () => {const snap = useAiAssistantStateSnapshot()const { mutate: sendEvent } = useSendEventMutation()const showStripeExample = useIsFeatureEnabled('edge_functions:show_stripe_example')+ const { openSidebar } = useSidebarManagerSnapshot()const [files, setFiles] = useState<{ id: number; name: string; content: string; selected?: boolean }[]@@ -167,9 +170,9 @@ const NewFunctionPage = () => {const handleChat = () => {const selectedFile = files.find((f) => f.selected) ?? files[0]+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)snap.newChat({name: 'Explain edge function',- open: true,sqlSnippets: [selectedFile.content],initialInput: 'Help me understand and improve this edge function...',suggestions: {diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsxindex 70b855b3a1d..4dd0ff88108 100644--- a/apps/studio/state/ai-assistant-state.tsx+++ b/apps/studio/state/ai-assistant-state.tsx@@ -28,7 +28,6 @@ type ChatSession = {}type AiAssistantData = {- open: booleaninitialInput: stringsqlSnippets?: SqlSnippet[]suggestions?: SuggestionsType@@ -41,14 +40,12 @@ type AiAssistantData = {// Data structure stored in IndexedDBtype StoredAiAssistantState = {projectRef: string- open: booleanactiveChatId?: stringchats: Record<string, ChatSession>model?: AssistantModel}const INITIAL_AI_ASSISTANT: AiAssistantData = {- open: false,initialInput: '',sqlSnippets: undefined,suggestions: undefined,@@ -167,7 +164,6 @@ async function tryMigrateFromLocalStorage(if (parsedFromLocalStorage && typeof parsedFromLocalStorage.chats === 'object') {migratedState = {projectRef: projectRef,- open: parsedFromLocalStorage.open ?? false,activeChatId: parsedFromLocalStorage.activeChatId,chats: parsedFromLocalStorage.chats,model: parsedFromLocalStorage.model ?? INITIAL_AI_ASSISTANT.model,@@ -199,15 +195,6 @@ async function tryMigrateFromLocalStorage(// Helper function to ensure an active chat exists or initialize a new onefunction ensureActiveChatOrInitialize(state: AiAssistantState) {- // Check URL param again to override loaded 'open' state if present- if (typeof window !== 'undefined') {- const urlParams = new URLSearchParams(window.location.search)- const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')- if (aiAssistantPanelOpenParam !== null) {- state.open = aiAssistantPanelOpenParam === 'true'- }- }-// Ensure an active chat exists after loading/migrationif (!state.activeChatId || !state.chats[state.activeChatId]) {const chatIds = Object.keys(state.chats)@@ -228,15 +215,6 @@ export const createAiAssistantState = (): AiAssistantState => {// Initialize with defaults, loading happens asynchronously in the providerconst initialState = { ...INITIAL_AI_ASSISTANT }- // Check URL params for initial 'open' state, overriding any loaded state later if present- if (typeof window !== 'undefined') {- const urlParams = new URLSearchParams(window.location.search)- const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')- if (aiAssistantPanelOpenParam !== null) {- initialState.open = aiAssistantPanelOpenParam === 'true'- }- }-const state: AiAssistantState = proxy({...initialState, // Spread initial values directly@@ -244,19 +222,6 @@ export const createAiAssistantState = (): AiAssistantState => {Object.assign(state, INITIAL_AI_ASSISTANT)},- // Panel visibility- openAssistant: () => {- state.open = true- },-- closeAssistant: () => {- state.open = false- },-- toggleAssistant: () => {- state.open = !state.open- },-setModel: (model: AssistantModel) => {state.model = model},@@ -268,7 +233,7 @@ export const createAiAssistantState = (): AiAssistantState => {newChat: (options?: { name?: string } & Partial<- Pick<AiAssistantData, 'open' | 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>+ Pick<AiAssistantData, 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>>) => {const chatId = uuidv4()@@ -287,7 +252,6 @@ export const createAiAssistantState = (): AiAssistantState => {state.activeChatId = chatId// Update non-chat related state based on options, falling back to current state, then initial- state.open = options?.open ?? state.openstate.initialInput = options?.initialInput ?? INITIAL_AI_ASSISTANT.initialInputstate.sqlSnippets = options?.sqlSnippets ?? INITIAL_AI_ASSISTANT.sqlSnippetsstate.suggestions = options?.suggestions ?? INITIAL_AI_ASSISTANT.suggestions@@ -399,25 +363,15 @@ export const createAiAssistantState = (): AiAssistantState => {// --- New function to load persisted state ---loadPersistedState: (persistedState: StoredAiAssistantState) => {- state.open = persistedState.openstate.chats = persistedState.chatsstate.activeChatId = persistedState.activeChatIdstate.model = persistedState.model ?? INITIAL_AI_ASSISTANT.model- // Check URL param again to override loaded 'open' state if present- if (typeof window !== 'undefined') {- const urlParams = new URLSearchParams(window.location.search)- const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')- if (aiAssistantPanelOpenParam !== null) {- state.open = aiAssistantPanelOpenParam === 'true'- }- }-// Ensure an active chat exists after loadingif (!state.activeChat) {const chatIds = Object.keys(state.chats)if (chatIds.length > 0) {- // Maybe select the most recently updated? For now, first.+ // Select the most recently updated chatstate.activeChatId = chatIds.sort((a, b) =>(state.chats[b].updatedAt?.getTime() || 0) -@@ -440,14 +394,11 @@ export const createAiAssistantState = (): AiAssistantState => {export type AiAssistantState = AiAssistantData & {resetAiAssistantPanel: () => void- openAssistant: () => void- closeAssistant: () => void- toggleAssistant: () => voidactiveChat: ChatSession | undefinedsetModel: (model: AssistantModel) => voidnewChat: (options?: { name?: string } & Partial<- Pick<AiAssistantData, 'open' | 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>+ Pick<AiAssistantData, 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>>) => stringselectChat: (id: string) => void@@ -522,7 +473,6 @@ export const AiAssistantStateContextProvider = ({ children }: PropsWithChildren)// Prepare state for IndexedDBconst stateToSave: StoredAiAssistantState = {projectRef: project?.ref,- open: snap.open,activeChatId: snap.activeChatId,model: snap.model,chats: snap.chatsdiff --git a/apps/studio/state/sidebar-manager-state.tsx b/apps/studio/state/sidebar-manager-state.tsxnew file mode 100644index 00000000000..bb455845ec4--- /dev/null+++ b/apps/studio/state/sidebar-manager-state.tsx@@ -0,0 +1,179 @@+import { LOCAL_STORAGE_KEYS } from 'common/constants'+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'+import { ReactNode, useEffect } from 'react'+import { proxy, snapshot, useSnapshot } from 'valtio'++type SidebarHandlers = {+ onOpen?: () => void+ onClose?: () => void+}++type ManagedSidebar = SidebarHandlers & {+ id: string+ component: () => ReactNode | undefined+}++type SidebarManagerData = {+ sidebars: Partial<Record<string, ManagedSidebar>>+ activeSidebar: ManagedSidebar | undefined+}++type SidebarManagerState = SidebarManagerData & {+ registerSidebar: (+ id: string,+ component: () => ReactNode | undefined,+ handlers?: SidebarHandlers+ ) => void+ unregisterSidebar: (id: string) => void+ openSidebar: (id: string) => void+ toggleSidebar: (id: string) => void+ closeSidebar: (id: string) => void+ isSidebarOpen: (id: string) => boolean+ closeActive: () => void+}++const INITIAL_SIDEBAR_MANAGER_DATA: SidebarManagerData = {+ sidebars: {},+ activeSidebar: undefined,+}++const createSidebarManagerState = () => {+ const state: SidebarManagerState = proxy({+ ...INITIAL_SIDEBAR_MANAGER_DATA,++ registerSidebar(+ id: string,+ component: () => ReactNode | undefined,+ handlers: SidebarHandlers = {}+ ) {+ state.sidebars[id] = {+ id,+ component,+ ...handlers,+ }+ },++ unregisterSidebar(id: string) {+ const panel = state.sidebars[id]+ if (!panel) return++ delete state.sidebars[id]++ if (state.activeSidebar?.id === id) {+ state.activeSidebar = undefined+ panel.onClose?.()+ }+ },++ openSidebar(id: string) {+ const panel = state.sidebars[id]+ if (!panel) {+ console.warn(`Sidebar "${id}" is not registered. Register it before opening.`)+ return+ }++ if (state.activeSidebar?.id === id) {+ return+ }++ if (state.activeSidebar && state.activeSidebar.id !== id) {+ const previousPanel = state.activeSidebar+ previousPanel?.onClose?.()+ }++ state.activeSidebar = panel+ panel.onOpen?.()+ },++ toggleSidebar(id: string) {+ const panel = state.sidebars[id]+ if (!panel) {+ console.warn(`Sidebar "${id}" is not registered. Register it before toggling.`)+ return+ }++ if (state.activeSidebar?.id === id) {+ panel.onClose?.()+ state.activeSidebar = undefined+ return+ }++ if (state.activeSidebar && state.activeSidebar.id !== id) {+ const previousPanel = state.activeSidebar+ previousPanel?.onClose?.()+ }++ state.activeSidebar = panel+ panel.onOpen?.()+ },++ closeSidebar(id: string) {+ if (state.activeSidebar?.id !== id) return++ const panel = state.sidebars[id]+ if (!panel) return++ panel.onClose?.()+ state.activeSidebar = undefined+ return+ },++ isSidebarOpen(id: string) {+ return state.activeSidebar?.id === id+ },++ closeActive() {+ if (!state.activeSidebar) return+ state.activeSidebar?.onClose?.()+ state.activeSidebar = undefined+ },+ })++ return state+}++export const sidebarManagerState = createSidebarManagerState()++export const getSidebarManagerSnapshot = () => snapshot(sidebarManagerState)++export const useSidebarManagerSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>+ useSnapshot(sidebarManagerState, options)++export const useRegisterSidebar = (+ id: string,+ component: () => ReactNode,+ handlers: SidebarHandlers = {},+ hotKey?: string+) => {+ const [isSidebarHotkeyEnabled] = useLocalStorageQuery<boolean>(+ LOCAL_STORAGE_KEYS.HOTKEY_SIDEBAR(id),+ true+ )++ useEffect(() => {+ const { registerSidebar, unregisterSidebar } = sidebarManagerState++ registerSidebar(id, component, handlers)++ return () => {+ unregisterSidebar(id)+ }+ }, [id])++ useEffect(() => {+ if (!hotKey) return++ function hotKeyHandler(e: KeyboardEvent) {+ if ((e.metaKey || e.ctrlKey) && e.key === hotKey && !e.altKey && !e.shiftKey) {+ sidebarManagerState.toggleSidebar(id)+ }+ }++ if (isSidebarHotkeyEnabled) {+ window.addEventListener('keydown', hotKeyHandler)+ return () => {+ window.removeEventListener('keydown', hotKeyHandler)+ }+ }+ }, [id, hotKey, isSidebarHotkeyEnabled])+}diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.tsindex 26ad2f83d50..1cfda8d9b95 100644--- a/packages/common/constants/local-storage.ts+++ b/packages/common/constants/local-storage.ts@@ -78,7 +78,9 @@ export const LOCAL_STORAGE_KEYS = {HOTKEY_INLINE_EDITOR: 'supabase-dashboard-hotkey-inline-editor',HOTKEY_COMMAND_MENU: 'supabase-dashboard-hotkey-command-menu',- HOTKEY_AI_ASSISTANT: 'supabase-dashboard-hotkey-ai-assistant',++ // Project sidebar hotkeys+ HOTKEY_SIDEBAR: (sidebarId: string) => `supabase-dashboard-hotkey-sidebar-${sidebarId}`,/*** COMMON