Skip to content

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

Multiple assistant chats (#34011)

Saxon Fletcher58272034b197
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
index 51bb4985cc8..7ef7d9ffc84 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
@@ -8,7 +8,7 @@ import { DropdownMenuItemTooltip } from 'components/ui/DropdownMenuItemTooltip'
import Panel from 'components/ui/Panel'
import { useAuthConfigQuery } from 'data/auth/auth-config-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
Badge,
Button,
@@ -37,7 +37,7 @@ const PolicyRow = ({
onSelectEditPolicy = noop,
onSelectDeletePolicy = noop,
}: PolicyRowProps) => {
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const canUpdatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'policies')
const { project } = useProjectContext()
@@ -119,7 +119,8 @@ const PolicyRow = ({
className="space-x-2"
onClick={() => {
const sql = generatePolicyCreateSQL(policy)
- setAiAssistantPanel({
+ 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...`,
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
index 8db35873f1f..c668c505a3d 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
@@ -6,7 +6,7 @@ import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { EditorTablePageLink } from 'data/prefetchers/project.$ref.editor.$id'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { AiIconAnimation, Badge } from 'ui'
interface PolicyTableRowHeaderProps {
@@ -33,7 +33,7 @@ const PolicyTableRowHeader = ({
onSelectCreatePolicy,
}: PolicyTableRowHeaderProps) => {
const { ref } = useParams()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const canCreatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'policies')
const canToggleRLS = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
@@ -113,7 +113,8 @@ const PolicyTableRowHeader = ({
type="default"
className="px-1"
onClick={() => {
- setAiAssistantPanel({
+ 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/Database/Functions/FunctionsList/FunctionList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
index 243cd504909..7fe3674f943 100644
--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
@@ -8,7 +8,7 @@ import Table from 'components/to-be-cleaned/Table'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
Button,
DropdownMenu,
@@ -35,7 +35,7 @@ const FunctionList = ({
}: FunctionListProps) => {
const router = useRouter()
const { project: selectedProject } = useProjectContext()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const { data: functions } = useDatabaseFunctionsQuery({
projectRef: selectedProject?.ref,
@@ -131,7 +131,8 @@ const FunctionList = ({
<DropdownMenuItem
className="space-x-2"
onClick={() => {
- setAiAssistantPanel({
+ aiSnap.newChat({
+ name: `Update function ${x.name}`,
open: true,
initialInput: 'Update this function to do...',
suggestions: {
diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
index f06a0d3bade..079776aec57 100644
--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
@@ -17,7 +17,7 @@ import { useSchemasQuery } from 'data/database/schemas-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { PROTECTED_SCHEMAS } from 'lib/constants/schemas'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { AiIconAnimation, Input } from 'ui'
import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'
import FunctionList from './FunctionList'
@@ -36,7 +36,7 @@ const FunctionsList = ({
const router = useRouter()
const { search } = useParams()
const { project } = useProjectContext()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
const filterString = search ?? ''
@@ -149,7 +149,8 @@ const FunctionsList = ({
className="px-1 pointer-events-auto"
icon={<AiIconAnimation size={16} />}
onClick={() =>
- setAiAssistantPanel({
+ aiSnap.newChat({
+ name: 'Create new function',
open: true,
initialInput: `Create a new function for the schema ${selectedSchema} that does ...`,
})
diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
index f70944bf7a3..35517b03e3d 100644
--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.tsx
@@ -7,7 +7,7 @@ import Table from 'components/to-be-cleaned/Table'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useDatabaseTriggersQuery } from 'data/database-triggers/database-triggers-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
Badge,
Button,
@@ -37,7 +37,7 @@ const TriggerList = ({
deleteTrigger,
}: TriggerListProps) => {
const { project } = useProjectContext()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const { data: triggers } = useDatabaseTriggersQuery({
projectRef: project?.ref,
@@ -156,7 +156,8 @@ const TriggerList = ({
className="space-x-2"
onClick={() => {
const sql = generateTriggerCreateSQL(x)
- setAiAssistantPanel({
+ aiSnap.newChat({
+ name: `Update trigger ${X.name}`,
open: true,
initialInput: `Update this trigger which exists on the ${x.schema}.${x.table} table to...`,
suggestions: {
diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
index ee6c1608fed..b7cc7a9c27f 100644
--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx
@@ -16,7 +16,7 @@ import { useSchemasQuery } from 'data/database/schemas-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { PROTECTED_SCHEMAS } from 'lib/constants/schemas'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { AiIconAnimation, Input } from 'ui'
import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'
import TriggerList from './TriggerList'
@@ -33,7 +33,7 @@ const TriggersList = ({
deleteTrigger = noop,
}: TriggersListProps) => {
const { project } = useProjectContext()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
const [filterString, setFilterString] = useState<string>('')
@@ -130,7 +130,8 @@ const TriggersList = ({
className="px-1 pointer-events-auto"
icon={<AiIconAnimation size={16} />}
onClick={() =>
- setAiAssistantPanel({
+ aiSnap.newChat({
+ name: 'Create new trigger',
open: true,
initialInput: `Create a new trigger for the schema ${selectedSchema} that does ...`,
suggestions: {
diff --git a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
index 4e1327a15a8..5ebce1db22b 100644
--- a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
+++ b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.tsx
@@ -8,7 +8,7 @@ import { useFlag } from 'hooks/ui/useFlag'
import { Code, Terminal } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
AiIconAnimation,
Button,
@@ -27,7 +27,7 @@ import { TerminalInstructions } from './TerminalInstructions'
export const FunctionsEmptyState = () => {
const { ref } = useParams()
const router = useRouter()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const edgeFunctionCreate = useFlag('edgeFunctionCreate')
const { mutate: sendEvent } = useSendEventMutation()
@@ -78,7 +78,8 @@ export const FunctionsEmptyState = () => {
<Button
type="default"
onClick={() => {
- setAiAssistantPanel({
+ aiSnap.newChat({
+ name: 'Create new edge function',
open: true,
initialInput: 'Create a new edge function that ...',
suggestions: {
diff --git a/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx b/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx
index a4471f159cb..a8c8873ecb3 100644
--- a/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx
+++ b/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx
@@ -9,7 +9,7 @@ import { LINTER_LEVELS } from 'components/interfaces/Linter/Linter.constants'
import { LintEntity, NoIssuesFound, lintInfoMap } from 'components/interfaces/Linter/Linter.utils'
import { Lint } from 'data/lint/lint-query'
import { useRouter } from 'next/router'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
AiIconAnimation,
Button,
@@ -43,7 +43,7 @@ const LinterDataGrid = ({
const gridRef = useRef<DataGridHandle>(null)
const { ref } = useParams()
const router = useRouter()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const snap = useAiAssistantStateSnapshot()
const [view, setView] = useState<'details' | 'suggestion'>('details')
@@ -243,7 +243,8 @@ const LinterDataGrid = ({
<Button
icon={<AiIconAnimation className="scale-75 w-3 h-3" />}
onClick={() => {
- setAiAssistantPanel({
+ snap.newChat({
+ name: 'Summarize lint',
open: true,
initialInput: `Summarize the issue and suggest fixes: ${lintInfoMap.find((item) => item.name === selectedLint.name)?.title}
\nEntity: ${(selectedLint.metadata && (selectedLint.metadata.entity || (selectedLint.metadata.schema && selectedLint.metadata.name && `${selectedLint.metadata.schema}.${selectedLint.metadata.name}`))) ?? ''}
diff --git a/apps/studio/components/interfaces/Reports/ReportPadding.tsx b/apps/studio/components/interfaces/Reports/ReportPadding.tsx
index 85285bcfff9..61aa6d17116 100644
--- a/apps/studio/components/interfaces/Reports/ReportPadding.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportPadding.tsx
@@ -1,19 +1,19 @@
import { PropsWithChildren } from 'react'
-import { useAppStateSnapshot } from 'state/app-state'
+
+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 { aiAssistantPanel } = useAppStateSnapshot()
- const { open } = aiAssistantPanel
+ const snap = useAiAssistantStateSnapshot()
return (
<div
className={cn(
'flex flex-col gap-4 px-5 py-6 mx-auto 1xl:px-28 lg:px-16 2xl:px-32 w-full',
- open ? 'xl:px-6' : 'xl:px-24'
+ snap.open ? 'xl:px-6' : 'xl:px-24'
)}
>
{children}
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index 19d012a27e4..c9a5a04cf66 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -8,7 +8,7 @@ import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
import { useProfile } from 'lib/profile'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import { cn } from 'ui'
import { Admonition } from 'ui-patterns'
@@ -50,7 +50,7 @@ const MonacoEditor = ({
const project = useSelectedProject()
const snapV2 = useSqlEditorV2StateSnapshot()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const [intellisenseEnabled] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
@@ -93,7 +93,8 @@ const MonacoEditor = ({
const selectedValue = (editorRef?.current as any)
.getModel()
.getValueInRange((editorRef?.current as any)?.getSelection())
- setAiAssistantPanel({
+ 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.tsx
index 723e59cc656..8bfb9e20531 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -29,7 +29,7 @@ import { formatSql } from 'lib/formatSql'
import { detectOS, uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import { wrapWithRoleImpersonation } from 'lib/role-impersonation'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
import { isRoleImpersonationEnabled, useGetImpersonatedRole } from 'state/role-impersonation-state'
import { getSqlEditorV2StateSnapshot, useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
@@ -83,7 +83,7 @@ export const SQLEditor = () => {
const queryClient = useQueryClient()
const project = useSelectedProject()
const organization = useSelectedOrganization()
- const appSnap = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
const getImpersonatedRole = useGetImpersonatedRole()
const databaseSelectorState = useDatabaseSelectorStateSnapshot()
@@ -366,7 +366,8 @@ export const SQLEditor = () => {
try {
const snippet = snapV2.snippets[id]
const result = snapV2.results[id]?.[0]
- appSnap.setAiAssistantPanel({
+ 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.tsx
index 2854c85248c..8540c6087ff 100644
--- a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx
+++ b/apps/studio/components/layouts/AppLayout/AssistantButton.tsx
@@ -1,8 +1,8 @@
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { AiIconAnimation, Button } from 'ui'
const AssistantButton = () => {
- const { setAiAssistantPanel, aiAssistantPanel } = useAppStateSnapshot()
+ const snap = useAiAssistantStateSnapshot()
return (
<Button
@@ -11,7 +11,7 @@ const AssistantButton = () => {
id="assistant-trigger"
className="h-full w-full rounded-none"
onClick={() => {
- setAiAssistantPanel({ open: !aiAssistantPanel.open })
+ snap.toggleAssistant()
}}
>
<AiIconAnimation allowHoverEffect size={20} />
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
index dd7b88091f4..63449f99cf8 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
@@ -5,6 +5,7 @@ import { PROJECT_STATUS } from 'lib/constants'
import { DatabaseSelectorStateContextProvider } from 'state/database-selector'
import { RoleImpersonationStateContextProvider } from 'state/role-impersonation-state'
import { TableEditorStateContextProvider } from 'state/table-editor'
+import { AiAssistantStateContextProvider } from 'state/ai-assistant-state'
export interface ProjectContextType {
project?: Project
@@ -40,11 +41,16 @@ export const ProjectContextProvider = ({
return (
<ProjectContext.Provider value={value}>
<TableEditorStateContextProvider key={`table-editor-state-${projectRef}`}>
- <DatabaseSelectorStateContextProvider key={`database-selector-state-${projectRef}`}>
- <RoleImpersonationStateContextProvider key={`role-impersonation-state-${projectRef}`}>
- {children}
- </RoleImpersonationStateContextProvider>
- </DatabaseSelectorStateContextProvider>
+ <AiAssistantStateContextProvider
+ key={`ai-assistant-state-${projectRef}`}
+ projectRef={projectRef}
+ >
+ <DatabaseSelectorStateContextProvider key={`database-selector-state-${projectRef}`}>
+ <RoleImpersonationStateContextProvider key={`role-impersonation-state-${projectRef}`}>
+ {children}
+ </RoleImpersonationStateContextProvider>
+ </DatabaseSelectorStateContextProvider>
+ </AiAssistantStateContextProvider>
</TableEditorStateContextProvider>
</ProjectContext.Provider>
)
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index 074bf251ac3..56225c6b8da 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -1,22 +1,24 @@
+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 { useParams } from 'common'
import {
useIsSQLEditorTabsEnabled,
useIsTableEditorTabsEnabled,
} from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'
-import { AIAssistantPanel } from 'components/ui/AIAssistantPanel/AIAssistantPanel'
+import { AIAssistant } from 'components/ui/AIAssistantPanel/AIAssistant'
import AISettingsModal from 'components/ui/AISettingsModal'
import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'
import { Loading } from 'components/ui/Loading'
import { ResourceExhaustionWarningBanner } from 'components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner'
-import { AnimatePresence, motion } from 'framer-motion'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { withAuth } from 'hooks/misc/withAuth'
import { PROJECT_STATUS } from 'lib/constants'
-import Head from 'next/head'
-import { useRouter } from 'next/router'
-import { forwardRef, Fragment, PropsWithChildren, ReactNode, useEffect, useState } from 'react'
+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'
@@ -89,15 +91,8 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
const [isClient, setIsClient] = useState(false)
const selectedOrganization = useSelectedOrganization()
const selectedProject = useSelectedProject()
- const {
- editorPanel,
- aiAssistantPanel,
- setAiAssistantPanel,
- mobileMenuOpen,
- setMobileMenuOpen,
- showSidebar,
- } = useAppStateSnapshot()
- const { open } = aiAssistantPanel
+ const { editorPanel, mobileMenuOpen, showSidebar, setMobileMenuOpen } = useAppStateSnapshot()
+ const aiSnap = useAiAssistantStateSnapshot()
const isTableEditorTabsEnabled = useIsTableEditorTabsEnabled()
const isSQLEditorTabsEnabled = useIsSQLEditorTabsEnabled()
@@ -130,7 +125,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === 'i' && !e.altKey && !e.shiftKey) {
- setAiAssistantPanel({ open: !open })
+ aiSnap.openAssistant()
e.preventDefault()
e.stopPropagation()
}
@@ -138,7 +133,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open])
+ }, [aiSnap.open])
return (
<>
@@ -230,7 +225,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
)}
</main>
</ResizablePanel>
- {isClient && (aiAssistantPanel.open || editorPanel.open) && (
+ {isClient && (aiSnap.open || editorPanel.open) && (
<>
<ResizableHandle withHandle />
<ResizablePanel
@@ -242,7 +237,9 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
'w-screen h-[100dvh] md:h-auto md:w-auto'
)}
>
- {aiAssistantPanel.open && <AIAssistantPanel />}
+ {aiSnap.open && (
+ <AIAssistant className="w-full h-[100dvh] md:h-full max-h-[100dvh]" />
+ )}
{editorPanel.open && <EditorPanel />}
</ResizablePanel>
</>
diff --git a/apps/studio/components/layouts/Scaffold.tsx b/apps/studio/components/layouts/Scaffold.tsx
index be0e3f45bda..9fde6e0173e 100644
--- a/apps/studio/components/layouts/Scaffold.tsx
+++ b/apps/studio/components/layouts/Scaffold.tsx
@@ -1,6 +1,6 @@
import { forwardRef, HTMLAttributes } from 'react'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { cn } from 'ui'
export const MAX_WIDTH_CLASSES = 'mx-auto w-full max-w-[1200px]'
@@ -24,8 +24,7 @@ export const ScaffoldContainer = forwardRef<
size?: 'small' | 'default' | 'large' | 'full'
}
>(({ className, bottomPadding, size = 'default', ...props }, ref) => {
- const { aiAssistantPanel } = useAppStateSnapshot()
- const { open } = aiAssistantPanel
+ const snap = useAiAssistantStateSnapshot()
const maxWidthClass = {
small: 'max-w-[768px]',
@@ -43,7 +42,7 @@ export const ScaffoldContainer = forwardRef<
maxWidthClass,
PADDING_CLASSES,
bottomPadding && 'pb-16',
- open ? 'xl:px-6' : '',
+ snap.open ? 'xl:px-6' : '',
className
)}
/>
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index 7af8600b5b2..0caa98bb3d2 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -3,9 +3,9 @@ import type { Message as MessageType } from 'ai/react'
import { useChat } from 'ai/react'
import { AnimatePresence, motion } from 'framer-motion'
import { last } from 'lodash'
-import { ArrowDown, FileText, Info, X } from 'lucide-react'
+import { ArrowDown, FileText, Info, RefreshCw, X } from 'lucide-react'
import { useRouter } from 'next/router'
-import { memo, useEffect, useMemo, useRef, useState } from 'react'
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { useParams, useSearchParamsShallow } from 'common/hooks'
@@ -26,7 +26,7 @@ import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useFlag } from 'hooks/ui/useFlag'
import { BASE_PATH, IS_PLATFORM, OPT_IN_TAGS } from 'lib/constants'
import uuidv4 from 'lib/uuid'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
AiIconAnimation,
@@ -39,7 +39,9 @@ import {
} from 'ui'
import { Admonition, AssistantChatForm, GenericSkeletonLoader } from 'ui-patterns'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { ButtonTooltip } from '../ButtonTooltip'
import DotGrid from '../DotGrid'
+import { AIAssistantChatSelector } from './AIAssistantChatSelector'
import AIOnboarding from './AIOnboarding'
import CollapsibleCodeBlock from './CollapsibleCodeBlock'
import { Message } from './Message'
@@ -62,18 +64,11 @@ const MemoizedMessage = memo(
MemoizedMessage.displayName = 'MemoizedMessage'
interface AIAssistantProps {
- id: string
initialMessages?: MessageType[] | undefined
className?: string
- onResetConversation: () => void
}
-export const AIAssistant = ({
- id,
- initialMessages,
- className,
- onResetConversation,
-}: AIAssistantProps) => {
+export const AIAssistant = ({ className }: AIAssistantProps) => {
const router = useRouter()
const project = useSelectedProject()
const isOptedInToAI = useOrgOptedIntoAi()
@@ -84,15 +79,15 @@ export const AIAssistant = ({
const disablePrompts = useFlag('disableAssistantPrompts')
const { snippets } = useSqlEditorV2StateSnapshot()
- const { aiAssistantPanel, setAiAssistantPanel, saveLatestMessage } = useAppStateSnapshot()
- const { open, initialInput, sqlSnippets, suggestions } = aiAssistantPanel
+ const snap = useAiAssistantStateSnapshot()
const inputRef = useRef<HTMLTextAreaElement>(null)
const { ref: scrollContainerRef, isSticky, scrollToEnd } = useAutoScroll()
- const [value, setValue] = useState<string>(initialInput)
- const [assistantError, setAssistantError] = useState<string>()
- const [lastSentMessage, setLastSentMessage] = useState<MessageType>()
+ // Add a ref to store the last user message
+ const lastUserMessageRef = useRef<MessageType | null>(null)
+
+ const [value, setValue] = useState<string>(snap.initialInput || '')
const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)
const { data: check, isSuccess } = useCheckOpenAIKeyQuery()
@@ -116,21 +111,41 @@ export const AIAssistant = ({
const currentTable = tables?.find((t) => t.id.toString() === entityId)
const currentSchema = searchParams?.get('schema') ?? 'public'
+ const currentChat = snap.chats[snap.activeChatId ?? ''].name
const { ref } = useParams()
const org = useSelectedOrganization()
const { mutate: sendEvent } = useSendEventMutation()
+ const handleError = useCallback((error: Error) => {
+ const errorMessage = JSON.parse(error.message).message
+ toast.error(errorMessage)
+ }, [])
+
+ // Handle completion of the assistant's response
+ const handleChatFinish = useCallback((message: MessageType) => {
+ // If we have a user message stored in the ref, save both messages
+ if (lastUserMessageRef.current) {
+ snap.saveMessage([lastUserMessageRef.current, message])
+ lastUserMessageRef.current = null
+ } else {
+ // Otherwise just save the assistant message
+ snap.saveMessage(message)
+ }
+ }, [])
+
const {
messages: chatMessages,
isLoading: isChatLoading,
append,
setMessages,
} = useChat({
- id,
+ id: snap.activeChatId,
api: `${BASE_PATH}/api/ai/sql/generate-v3`,
maxSteps: 5,
- initialMessages,
+ // [Alaister] typecast is needed here because valtio returns readonly arrays
+ // and useChat expects a mutable array
+ initialMessages: snap.activeChat?.messages as unknown as MessageType[] | undefined,
body: {
includeSchemaMetadata,
projectRef: project?.ref,
@@ -138,50 +153,42 @@ export const AIAssistant = ({
schema: currentSchema,
table: currentTable?.name,
},
- onFinish: (message) => saveLatestMessage(message),
- onError: (error) => {
- const errorMessage = JSON.parse(error.message).message
- toast.error(errorMessage)
- },
+ onError: handleError,
+ onFinish: handleChatFinish,
})
const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
const { mutate: updateOrganization, isLoading: isUpdating } = useOrganizationUpdateMutation()
- const messages = useMemo(() => {
- return [
- ...chatMessages,
- ...(assistantError !== undefined && lastSentMessage !== undefined ? [lastSentMessage] : []),
- ]
- }, [chatMessages, assistantError, lastSentMessage])
-
const renderedMessages = useMemo(
() =>
- messages.map((message) => {
+ chatMessages.map((message) => {
return (
<MemoizedMessage
key={message.id}
message={message}
- isLoading={isChatLoading && message.id === messages[messages.length - 1].id}
+ isLoading={isChatLoading && message.id === chatMessages[chatMessages.length - 1].id}
/>
)
}),
- [messages, isChatLoading]
+ [chatMessages, isChatLoading]
)
- const hasMessages = messages.length > 0
+ const hasMessages = chatMessages.length > 0
const sendMessageToAssistant = async (content: string) => {
const payload = { role: 'user', createdAt: new Date(), content } as MessageType
const headerData = await constructHeaders()
+ snap.clearSqlSnippets()
+
+ // Store the user message in the ref before appending
+ lastUserMessageRef.current = payload
+
append(payload, {
headers: { Authorization: headerData.get('Authorization') ?? '' },
})
- setAiAssistantPanel({ sqlSnippets: undefined, messages: [...messages, payload] })
setValue('')
- setAssistantError(undefined)
- setLastSentMessage(payload)
if (content.includes('Help me to debug')) {
sendEvent({
@@ -196,10 +203,6 @@ export const AIAssistant = ({
}
}
- const closeAssistant = () => {
- setAiAssistantPanel({ open: false })
- }
-
const confirmOptInToShareSchemaData = async () => {
if (!canUpdateOrganization) {
return toast.error('You do not have the required permissions to update this organization')
@@ -224,6 +227,12 @@ export const AIAssistant = ({
)
}
+ const handleClearMessages = () => {
+ snap.clearMessages()
+ setMessages([])
+ lastUserMessageRef.current = null
+ }
+
// Update scroll behavior for new messages
useEffect(() => {
if (!isChatLoading) {
@@ -233,29 +242,22 @@ export const AIAssistant = ({
if (isSticky) {
setTimeout(scrollToEnd, 0)
}
- }, [isChatLoading, isSticky, scrollToEnd, messages])
+ }, [isChatLoading, isSticky, scrollToEnd])
useEffect(() => {
- setValue(initialInput)
- if (inputRef.current) {
+ setValue(snap.initialInput || '')
+ if (inputRef.current && snap.initialInput) {
inputRef.current.focus()
- inputRef.current.setSelectionRange(initialInput.length, initialInput.length)
+ inputRef.current.setSelectionRange(snap.initialInput.length, snap.initialInput.length)
}
- }, [initialInput])
+ }, [snap.initialInput])
- // Remove suggestions if sqlSnippets were removed
useEffect(() => {
- if (!sqlSnippets || sqlSnippets.length === 0) {
- setAiAssistantPanel({ suggestions: undefined })
- }
- }, [sqlSnippets, suggestions, setAiAssistantPanel])
-
- useEffect(() => {
- if (open && isInSQLEditor && !!snippetContent) {
- setAiAssistantPanel({ sqlSnippets: [snippetContent] })
+ if (snap.open && isInSQLEditor && !!snippetContent) {
+ snap.setSqlSnippets([snippetContent])
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open, isInSQLEditor, snippetContent])
+ }, [snap.open, isInSQLEditor, snippetContent])
return (
<>
@@ -265,8 +267,8 @@ export const AIAssistant = ({
<div className="border-b flex items-center bg gap-x-3 px-5 h-[46px]">
<AiIconAnimation allowHoverEffect />
- <div className="text-sm flex-1">Assistant</div>
- <div className="flex gap-4 items-center">
+ <div className="text-sm flex-1 flex items-center gap-x-2">
+ Assistant
<Tooltip>
<TooltipTrigger asChild>
<Info size={14} className="text-foreground-light" />
@@ -278,13 +280,37 @@ export const AIAssistant = ({
: 'Project metadata is not being shared. Opt in to improve Assistant responses.'}
</TooltipContent>
</Tooltip>
- <div className="flex gap-2">
- {(hasMessages || suggestions || sqlSnippets) && (
- <Button type="default" disabled={isChatLoading} onClick={onResetConversation}>
- Reset
- </Button>
- )}
- <Button type="default" className="w-7" onClick={closeAssistant} icon={<X />} />
+ </div>
+ <div className="flex items-center gap-x-4">
+ <Tooltip>
+ <TooltipTrigger>
+ <p
+ title={currentChat}
+ className="text-xs text-foreground-light truncate max-w-[145px] 2xl:max-w-full"
+ >
+ {currentChat}
+ </p>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">Current chat: {currentChat}</TooltipContent>
+ </Tooltip>
+ <div className="flex items-center gap-x-2">
+ <AIAssistantChatSelector />
+ <ButtonTooltip
+ type="default"
+ size="tiny"
+ icon={<RefreshCw size={14} />}
+ onClick={handleClearMessages}
+ className="h-7 w-7 p-0"
+ disabled={isChatLoading}
+ tooltip={{ content: { side: 'bottom', text: 'Clear messages' } }}
+ />
+ <ButtonTooltip
+ type="default"
+ className="w-7 h-7"
+ onClick={snap.closeAssistant}
+ icon={<X />}
+ tooltip={{ content: { side: 'bottom', text: 'Close assistant' } }}
+ />
</div>
</div>
</div>
@@ -319,7 +345,8 @@ export const AIAssistant = ({
{hasMessages ? (
<div className="w-full p-5">
{renderedMessages}
- {(last(messages)?.role === 'user' || last(messages)?.content?.length === 0) && (
+ {(last(chatMessages)?.role === 'user' ||
+ last(chatMessages)?.content?.length === 0) && (
<div className="flex gap-4 w-auto overflow-hidden">
<AiIconAnimation size={20} className="text-foreground-muted shrink-0" />
<div className="text-foreground-lighter text-sm flex gap-1.5 items-center">
@@ -349,14 +376,14 @@ export const AIAssistant = ({
)}
<div className="h-1" />
</div>
- ) : suggestions ? (
+ ) : snap.suggestions ? (
<div className="w-full h-full px-8 py-0 flex flex-col flex-1 justify-end">
<h3 className="text-foreground-light font-mono text-sm uppercase mb-3">
Suggestions
</h3>
- {suggestions.title && <p>{suggestions.title}</p>}
+ {snap.suggestions.title && <p>{snap.suggestions.title}</p>}
<div className="-mx-3 mt-4 mb-12">
- {suggestions?.prompts?.map((prompt: string, idx: number) => (
+ {snap.suggestions?.prompts?.map((prompt: string, idx: number) => (
<Button
key={`suggestion-${idx}`}
size="small"
@@ -365,9 +392,12 @@ export const AIAssistant = ({
className="w-full justify-start py-1 h-auto"
onClick={() => {
setValue(prompt)
- if (inputRef.current) {
+ if (inputRef.current && snap.initialInput) {
inputRef.current.focus()
- inputRef.current.setSelectionRange(initialInput.length, initialInput.length)
+ inputRef.current.setSelectionRange(
+ snap.initialInput.length,
+ snap.initialInput.length
+ )
}
}}
>
@@ -475,17 +505,17 @@ export const AIAssistant = ({
</AnimatePresence>
<div className="p-5 pt-0 z-20 relative">
- {sqlSnippets && sqlSnippets.length > 0 && (
+ {snap.sqlSnippets && snap.sqlSnippets.length > 0 && (
<div className="mb-2">
- {sqlSnippets.map((snippet: string, index: number) => (
+ {snap.sqlSnippets.map((snippet: string, index: number) => (
<CollapsibleCodeBlock
key={index}
hideLineNumbers
value={snippet}
onRemove={() => {
- const newSnippets = [...sqlSnippets]
+ const newSnippets = [...(snap.sqlSnippets ?? [])]
newSnippets.splice(index, 1)
- setAiAssistantPanel({ sqlSnippets: newSnippets })
+ snap.setSqlSnippets(newSnippets)
}}
className="text-xs"
/>
@@ -525,7 +555,7 @@ export const AIAssistant = ({
placeholder={
hasMessages
? 'Reply to the assistant...'
- : (sqlSnippets ?? [])?.length > 0
+ : (snap.sqlSnippets ?? [])?.length > 0
? 'Ask a question or make a change...'
: 'Chat to Postgres...'
}
@@ -535,7 +565,7 @@ export const AIAssistant = ({
event.preventDefault()
if (includeSchemaMetadata) {
const sqlSnippetsString =
- sqlSnippets
+ snap.sqlSnippets
?.map((snippet: string) => '```sql\n' + snippet + '\n```')
.join('\n') || ''
const valueWithSnippets = [value, sqlSnippetsString].filter(Boolean).join('\n\n')
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
index d69c482fa7a..6139b45105b 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
@@ -5,98 +5,8 @@ import { databaseTriggerKeys } from 'data/database-triggers/keys'
import { databaseKeys } from 'data/database/keys'
import { enumeratedTypesKeys } from 'data/enumerated-types/keys'
import { tableKeys } from 'data/tables/keys'
-import { CommonDatabaseEntity } from 'state/app-state'
-import { SupportedAssistantEntities } from './AIAssistant.types'
import { SAFE_FUNCTIONS } from './AiAssistant.constants'
-const PLACEHOLDER_PREFIX = `-- Press tab to use this code
-\n&nbsp;\n`
-
-// [Joshen] Not used but keeping this for now in case we do an inline editor
-export const generatePlaceholder = (
- editor?: SupportedAssistantEntities | null,
- entity?: CommonDatabaseEntity,
- existingDefinition?: string
-) => {
- switch (editor) {
- case 'functions':
- if (entity === undefined) {
- return `${PLACEHOLDER_PREFIX}
-CREATE FUNCTION *schema*.*function_name*(*param1 type*, *param2 type*)\n
-&nbsp;&nbsp;RETURNS *return_type*\n
-&nbsp;&nbsp;LANGUAGE *plpgsql*\n
-&nbsp;&nbsp;SECURITY DEFINER\n
-&nbsp;&nbsp;SET *search_path = ''*\n
-AS $$\n
-DECLARE\n
-&nbsp;&nbsp;*-- Variable declarations*\n
-BEGIN\n
-&nbsp;&nbsp;*-- Function logic*\n
-END;\n
-$$;
-`
- } else {
- return `${PLACEHOLDER_PREFIX}
--- To rename the function\n
-ALTER FUNCTION *${entity.name}* RENAME TO *new_name*;\n
-&nbsp;\n
--- To change the schema of the function\n
-ALTER FUNCTION *${entity.name}* SET SCHEMA *new_schema*;\n
-&nbsp;\n
--- To update the function body or the arguments, use\n
--- the create or replace statement instead\n
-${existingDefinition
- ?.replaceAll(
- '\n ',
- `\n\
- &nbsp;&nbsp;`
- )
- .replaceAll('\n', '\n\n')
- .trim()}
-`
- }
- case 'rls-policies':
- if (entity === undefined) {
- return `${PLACEHOLDER_PREFIX}
-CREATE POLICY *name* ON *table_name*\n
-AS PERMISSIVE -- PERMISSIVE | RESTRICTIVE\n
-FOR ALL -- ALL | SELECT | INSERT | UPDATE | DELETE\n
-TO *role_name* -- Default: public\n
-USING ( *using_expression* )\n
-WITH CHECK ( *check_expression* );
-`
- } else {
- let expression = ''
- if (entity.definition !== null && entity.definition !== undefined) {
- expression += `USING ( *${entity.definition}* )${
- entity.check === null || entity.check === undefined ? ';' : ''
- }\n`
- }
- if (entity.check !== null && entity.check !== undefined) {
- expression += `WITH CHECK ( *${entity.check}* );\n`
- }
- return `${PLACEHOLDER_PREFIX}
-BEGIN;\n
-&nbsp;\n
--- To update your policy definition\n
-ALTER POLICY "${entity.name}"\n
-ON "${entity.schema}"."${entity.table}"\n
-TO *${(entity.roles ?? []).join(', ')}*\n
-${expression}
-&nbsp;\n
--- To rename the policy\n
-ALTER POLICY "${entity.name}"\n
-ON "${entity.schema}"."${entity.table}"\n
-RENAME TO "*New Policy Name*";\n
-&nbsp;\n
-COMMIT;
-`
- }
- default:
- return undefined
- }
-}
-
// [Joshen] This is just very basic identification, but possible can extend perhaps
export const identifyQueryType = (query: string) => {
const formattedQuery = query.toLowerCase().replaceAll('\n', ' ')
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
new file mode 100644
index 00000000000..ac2752e21ee
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
@@ -0,0 +1,213 @@
+import { Check, Edit, MessageSquare, Plus, Trash, X } from 'lucide-react'
+import { useState } from 'react'
+
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
+import {
+ Button,
+ cn,
+ Command_Shadcn_,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ CommandSeparator_Shadcn_,
+ Input_Shadcn_,
+ Popover_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ ScrollArea,
+} from 'ui'
+import { ButtonTooltip } from '../ButtonTooltip'
+
+interface AIAssistantChatSelectorProps {
+ className?: string
+}
+
+export const AIAssistantChatSelector = ({ className }: AIAssistantChatSelectorProps) => {
+ const snap = useAiAssistantStateSnapshot()
+
+ const [chatSelectorOpen, setChatSelectorOpen] = useState(false)
+ const [editingChatId, setEditingChatId] = useState<string | null>(null)
+ const [editingChatName, setEditingChatName] = useState('')
+
+ const chats = Object.entries(snap.chats)
+
+ const handleSelectChat = (id: string) => {
+ snap.selectChat(id)
+ setChatSelectorOpen(false)
+ }
+
+ const handleDeleteChat = (id: string, e?: React.MouseEvent) => {
+ if (e) {
+ e.stopPropagation()
+ }
+ snap.deleteChat(id)
+ }
+
+ const handleStartEditChat = (id: string, name: string, e?: React.MouseEvent) => {
+ if (e) {
+ e.stopPropagation()
+ }
+ setEditingChatId(id)
+ setEditingChatName(name)
+ }
+
+ const handleSaveEditChat = (e?: React.MouseEvent) => {
+ if (e) {
+ e.stopPropagation()
+ }
+ if (editingChatId && editingChatName.trim()) {
+ snap.renameChat(editingChatId, editingChatName.trim())
+ setEditingChatId(null)
+ setEditingChatName('')
+ }
+ }
+
+ const handleCancelEditChat = (e?: React.MouseEvent | React.FocusEvent) => {
+ if (e) {
+ e.stopPropagation()
+ }
+ setEditingChatId(null)
+ setEditingChatName('')
+ }
+
+ const handleInputBlur = (e: React.FocusEvent) => {
+ e.stopPropagation()
+ const relatedTarget = e.relatedTarget as HTMLElement | null
+ const isSaveOrCancelButton = relatedTarget?.closest('button')
+
+ if (!isSaveOrCancelButton && editingChatId && editingChatName.trim()) {
+ handleSaveEditChat()
+ } else if (!isSaveOrCancelButton) {
+ handleCancelEditChat(e)
+ }
+ }
+
+ return (
+ <Popover_Shadcn_ open={chatSelectorOpen} onOpenChange={setChatSelectorOpen}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <ButtonTooltip
+ type="default"
+ size="tiny"
+ icon={<MessageSquare size={14} />}
+ className={cn('h-7 w-7', className)}
+ tooltip={{ content: { side: 'bottom', text: 'View chats' } }}
+ />
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="w-[250px] p-0" align="end">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Search chats..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No chats found.</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ <ScrollArea className={chats.length > 4 ? 'h-40' : ''}>
+ {chats.map(([id, chat]) => (
+ <CommandItem_Shadcn_
+ key={id}
+ value={id}
+ onSelect={() => handleSelectChat(id)}
+ className="flex items-center justify-between gap-2 py-1 w-full overflow-hidden group"
+ keywords={[chat.name]}
+ >
+ <div className="flex items-center w-full flex-1 min-w-0">
+ {editingChatId === id ? (
+ <div className="flex items-center gap-2 w-full">
+ <Input_Shadcn_
+ value={editingChatName}
+ onChange={(e) => setEditingChatName(e.target.value)}
+ autoFocus
+ size="tiny"
+ className="flex-1 w-full"
+ onClick={(e) => e.stopPropagation()}
+ onBlur={handleInputBlur}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ e.stopPropagation()
+ handleSaveEditChat()
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ e.stopPropagation()
+ handleCancelEditChat()
+ }
+ }}
+ />
+ <div className="flex items-center gap-0">
+ <Button
+ type="text"
+ size="tiny"
+ icon={<Check size={14} />}
+ onClick={(e) => handleSaveEditChat(e)}
+ className="h-7 w-7"
+ />
+ <Button
+ type="text"
+ size="tiny"
+ icon={<X size={14} />}
+ onClick={(e) => handleCancelEditChat(e)}
+ className="h-7 w-7"
+ />
+ </div>
+ </div>
+ ) : (
+ <>
+ <Check
+ className={cn(
+ 'mr-2 h-4 w-4 flex-shrink-0',
+ snap.activeChatId === id ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ <span className="truncate flex-1 min-w-0 overflow-hidden">
+ {chat.name}
+ </span>
+ </>
+ )}
+ </div>
+ {editingChatId !== id && (
+ <div className="flex items-center gap-x-0 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
+ <Button
+ type="text"
+ size="tiny"
+ icon={<Edit size={14} />}
+ onClick={(e) => handleStartEditChat(id, chat.name, e)}
+ className="h-6 w-6"
+ />
+ {chats.length > 1 && (
+ <Button
+ type="text"
+ size="tiny"
+ icon={<Trash size={14} />}
+ onClick={(e) => handleDeleteChat(id, e)}
+ className="h-6 w-6"
+ />
+ )}
+ </div>
+ )}
+ </CommandItem_Shadcn_>
+ ))}
+ </ScrollArea>
+ </CommandGroup_Shadcn_>
+ <CommandSeparator_Shadcn_ />
+ <CommandGroup_Shadcn_>
+ <CommandItem_Shadcn_
+ className="cursor-pointer w-full gap-x-2"
+ onSelect={() => {
+ snap.newChat()
+ setChatSelectorOpen(false)
+ }}
+ onClick={() => {
+ snap.newChat()
+ setChatSelectorOpen(false)
+ }}
+ >
+ <Plus size={14} strokeWidth={1.5} />
+ <span>New chat</span>
+ </CommandItem_Shadcn_>
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )
+}
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
deleted file mode 100644
index 28989c18b4b..00000000000
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { Message as MessageType } from 'ai/react'
-import { uuidv4 } from 'lib/helpers'
-import { useState } from 'react'
-import { useAppStateSnapshot } from 'state/app-state'
-import { cn } from 'ui'
-import { AIAssistant } from './AIAssistant'
-
-export const AIAssistantPanel = () => {
- const { aiAssistantPanel, resetAiAssistantPanel } = useAppStateSnapshot()
- const [initialMessages, setInitialMessages] = useState<MessageType[] | undefined>(
- aiAssistantPanel.messages?.length > 0 ? (aiAssistantPanel.messages as any) : undefined
- )
-
- const { open } = aiAssistantPanel
- const [chatId, setChatId] = useState(() => uuidv4())
-
- const handleReset = () => {
- // reset local and global state
- setChatId(uuidv4())
- setInitialMessages(undefined)
- resetAiAssistantPanel()
- }
-
- return !open ? null : (
- <AIAssistant
- initialMessages={initialMessages}
- id={chatId}
- className={cn('w-full h-[100dvh] md:h-full max-h-[100dvh]')}
- onResetConversation={handleReset}
- />
- )
-}
diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
index 1f133156f62..19485ce8428 100644
--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
@@ -1,5 +1,5 @@
import { debounce } from 'lodash'
-import { Book, Check, Save, X } from 'lucide-react'
+import { Book, Save, X } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
@@ -20,24 +20,22 @@ import { useProfile } from 'lib/profile'
import { useAppStateSnapshot } from 'state/app-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
- AiIconAnimation,
Button,
cn,
- Input_Shadcn_,
- SQL_ICON,
- Popover_Shadcn_,
- PopoverTrigger_Shadcn_,
- PopoverContent_Shadcn_,
+ CodeBlock,
Command_Shadcn_,
- CommandInput_Shadcn_,
- CommandList_Shadcn_,
CommandEmpty_Shadcn_,
CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
CommandItem_Shadcn_,
+ CommandList_Shadcn_,
HoverCard_Shadcn_,
HoverCardContent_Shadcn_,
HoverCardTrigger_Shadcn_,
- CodeBlock,
+ Popover_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ SQL_ICON,
} from 'ui'
import { Admonition } from 'ui-patterns'
import { containsUnknownFunction, isReadOnlySelect } from '../AIAssistantPanel/AIAssistant.utils'
@@ -53,7 +51,7 @@ interface EditorPanelProps {
export const EditorPanel = ({ onChange }: EditorPanelProps) => {
const { ref } = useParams()
const project = useSelectedProject()
- const { editorPanel, setEditorPanel, setAiAssistantPanel } = useAppStateSnapshot()
+ const { editorPanel, setEditorPanel } = useAppStateSnapshot()
const { profile } = useProfile()
const snapV2 = useSqlEditorV2StateSnapshot()
const { mutateAsync: generateSqlTitle } = useSqlTitleGenerateMutation()
diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.ts
index d84cc68ed39..343f93a2825 100644
--- a/apps/studio/lib/constants/index.ts
+++ b/apps/studio/lib/constants/index.ts
@@ -40,7 +40,8 @@ export const STRIPE_PUBLIC_KEY =
export const USAGE_APPROACHING_THRESHOLD = 0.75
export const LOCAL_STORAGE_KEYS = {
- AI_ASSISTANT_STATE: 'supabase-ai-assistant-state',
+ AI_ASSISTANT_STATE: (projectRef: string | undefined) =>
+ `supabase-ai-assistant-state-${projectRef}`,
SIDEBAR_BEHAVIOR: 'supabase-sidebar-behavior',
EDITOR_PANEL_STATE: 'supabase-editor-panel-state',
diff --git a/apps/studio/pages/project/[ref]/functions/index.tsx b/apps/studio/pages/project/[ref]/functions/index.tsx
index ad369e7e507..416b96c373b 100644
--- a/apps/studio/pages/project/[ref]/functions/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/index.tsx
@@ -18,7 +18,7 @@ import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useFlag } from 'hooks/ui/useFlag'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import type { NextPageWithLayout } from 'types'
import {
AiIconAnimation,
@@ -35,7 +35,7 @@ import {
const EdgeFunctionsPage: NextPageWithLayout = () => {
const { ref } = useParams()
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const snap = useAiAssistantStateSnapshot()
const router = useRouter()
const {
data: functions,
@@ -118,7 +118,8 @@ const EdgeFunctionsPage: NextPageWithLayout = () => {
className="px-1 pointer-events-auto"
icon={<AiIconAnimation size={16} />}
onClick={() => {
- setAiAssistantPanel({
+ snap.newChat({
+ name: 'Create new edge function',
open: true,
initialInput: `Create a new edge function that ...`,
suggestions: {
diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsx
index e88afd0444a..26931123ec3 100644
--- a/apps/studio/pages/project/[ref]/functions/new.tsx
+++ b/apps/studio/pages/project/[ref]/functions/new.tsx
@@ -19,7 +19,7 @@ import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useFlag } from 'hooks/ui/useFlag'
import { BASE_PATH, IS_PLATFORM } from 'lib/constants'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import {
AiIconAnimation,
Button,
@@ -103,7 +103,7 @@ const NewFunctionPage = () => {
const project = useSelectedProject()
const isOptedInToAI = useOrgOptedIntoAi()
const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
- const { setAiAssistantPanel } = useAppStateSnapshot()
+ const snap = useAiAssistantStateSnapshot()
const edgeFunctionCreate = useFlag('edgeFunctionCreate')
const { mutate: sendEvent } = useSendEventMutation()
const org = useSelectedOrganization()
@@ -162,7 +162,8 @@ const NewFunctionPage = () => {
const handleChat = () => {
const selectedFile = files.find((f) => f.selected) ?? files[0]
- setAiAssistantPanel({
+ snap.newChat({
+ name: 'Explain edge function',
open: true,
sqlSnippets: [selectedFile.content],
initialInput: 'Help me understand and improve this edge function...',
diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsx
new file mode 100644
index 00000000000..1b9cddcfad7
--- /dev/null
+++ b/apps/studio/state/ai-assistant-state.tsx
@@ -0,0 +1,280 @@
+import type { Message as MessageType } from 'ai/react'
+import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
+import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
+
+import { LOCAL_STORAGE_KEYS } from 'lib/constants'
+
+type SuggestionsType = {
+ title: string
+ prompts?: string[]
+}
+
+type ChatSession = {
+ id: string
+ name: string
+ messages: readonly MessageType[]
+ createdAt: Date
+ updatedAt: Date
+}
+
+type AiAssistantData = {
+ open: boolean
+ initialInput: string
+ sqlSnippets?: string[]
+ suggestions?: SuggestionsType
+ tables: { schema: string; name: string }[]
+ chats: Record<string, ChatSession>
+ activeChatId?: string
+}
+
+const INITIAL_AI_ASSISTANT: AiAssistantData = {
+ open: false,
+ initialInput: '',
+ sqlSnippets: undefined,
+ suggestions: undefined,
+ tables: [],
+ chats: {},
+ activeChatId: undefined,
+}
+
+export const createAiAssistantState = (projectRef: string | undefined) => {
+ const getInitialState = (): AiAssistantData => {
+ if (typeof window === 'undefined') {
+ return INITIAL_AI_ASSISTANT
+ }
+
+ const stored = localStorage.getItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef))
+ const urlParams = new URLSearchParams(window.location.search)
+ const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')
+
+ let parsedAiAssistant = INITIAL_AI_ASSISTANT
+
+ try {
+ if (stored) {
+ parsedAiAssistant = JSON.parse(stored, (key, value) => {
+ if ((key === 'createdAt' || key === 'updatedAt') && value) {
+ return new Date(value)
+ }
+ return value
+ })
+ }
+ } catch {
+ // Ignore parsing errors
+ }
+
+ return {
+ ...parsedAiAssistant,
+ open:
+ aiAssistantPanelOpenParam !== null
+ ? aiAssistantPanelOpenParam === 'true'
+ : parsedAiAssistant.open,
+ }
+ }
+
+ const initialState = getInitialState()
+
+ const state = proxy({
+ open: initialState.open,
+ initialInput: initialState.initialInput,
+ sqlSnippets: initialState.sqlSnippets,
+ suggestions: initialState.suggestions,
+ tables: initialState.tables,
+ chats: initialState.chats,
+ activeChatId: initialState.activeChatId,
+
+ resetAiAssistantPanel: () => {
+ state.open = state.open
+ state.chats = state.chats
+ state.activeChatId = state.activeChatId
+ Object.assign(state, INITIAL_AI_ASSISTANT)
+ },
+
+ // Panel visibility
+ openAssistant: () => {
+ state.open = true
+ },
+
+ closeAssistant: () => {
+ state.open = false
+ },
+
+ toggleAssistant: () => {
+ state.open = !state.open
+ },
+
+ // Chat management
+ get activeChat() {
+ return state.activeChatId ? state.chats[state.activeChatId] : undefined
+ },
+
+ newChat: (
+ options?: { name?: string } & Partial<
+ Pick<AiAssistantData, 'open' | 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>
+ >
+ ) => {
+ const chatId = crypto.randomUUID()
+ const newChat: ChatSession = {
+ id: chatId,
+ name: options?.name ?? 'New Chat',
+ messages: [],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ }
+
+ state.chats = {
+ ...state.chats,
+ [chatId]: newChat,
+ }
+ state.activeChatId = chatId
+
+ state.open = options?.open ?? state.open
+ state.initialInput = options?.initialInput ?? initialState.initialInput
+ state.sqlSnippets = options?.sqlSnippets ?? initialState.sqlSnippets
+ state.suggestions = options?.suggestions ?? initialState.suggestions
+ state.tables = options?.tables ?? initialState.tables
+
+ return chatId
+ },
+
+ selectChat: (id: string) => {
+ if (id !== state.activeChatId) {
+ state.activeChatId = id
+ }
+ },
+
+ deleteChat: (id: string) => {
+ const { [id]: _, ...remainingChats } = state.chats
+ state.chats = remainingChats
+
+ // If the deleted chat was the active one, select a new active chat
+ if (id === state.activeChatId) {
+ const remainingChatIds = Object.keys(remainingChats)
+ state.activeChatId = remainingChatIds.length > 0 ? remainingChatIds[0] : undefined
+ }
+ },
+
+ renameChat: (id: string, name: string) => {
+ const chat = state.chats[id]
+ if (chat && chat.name !== name) {
+ state.chats = {
+ ...state.chats,
+ [id]: {
+ ...chat,
+ name,
+ updatedAt: new Date(),
+ },
+ }
+ }
+ },
+
+ clearMessages: () => {
+ const chat = state.activeChat
+ if (chat) {
+ chat.messages = []
+ chat.updatedAt = new Date()
+
+ state.sqlSnippets = []
+ state.initialInput = ''
+ }
+ },
+
+ saveMessage: (message: MessageType | MessageType[]) => {
+ let chat = state.activeChat
+ if (!chat) return
+
+ const existingMessages = chat.messages
+ const messagesToAdd = Array.isArray(message)
+ ? message.filter((msg) => !existingMessages.some((existing) => existing.id === msg.id))
+ : !existingMessages.some((existing) => existing.id === message.id)
+ ? [message]
+ : []
+
+ if (messagesToAdd.length > 0) {
+ chat.messages = [...existingMessages, ...messagesToAdd]
+ chat.updatedAt = new Date()
+ }
+ },
+
+ setSqlSnippets: (snippets: string[]) => {
+ state.sqlSnippets = snippets
+ },
+
+ // SQL snippets and suggestions
+ clearSqlSnippets: () => {
+ state.sqlSnippets = undefined
+ // Remove suggestions if sqlSnippets were removed
+ state.suggestions = undefined
+ },
+ })
+
+ // If there's no active chat when the state is created
+ // select the first chat, or create a new one if there are none
+ if (!state.activeChat) {
+ const chatIds = Object.keys(state.chats)
+ if (chatIds.length > 0) {
+ state.activeChatId = chatIds[0]
+ } else {
+ state.newChat()
+ }
+ }
+
+ return state
+}
+
+export type AiAssistantState = ReturnType<typeof createAiAssistantState>
+
+export const AiAssistantStateContext = createContext<AiAssistantState>(
+ createAiAssistantState(undefined)
+)
+
+export const AiAssistantStateContextProvider = ({
+ projectRef,
+ children,
+}: PropsWithChildren<{
+ projectRef: string | undefined
+}>) => {
+ const [state, setState] = useState(() => createAiAssistantState(projectRef))
+
+ useEffect(() => {
+ setState(createAiAssistantState(projectRef))
+ }, [projectRef])
+
+ useEffect(() => {
+ if (typeof window !== 'undefined') {
+ return subscribe(state, () => {
+ const snap = snapshot(state)
+ // Save AI assistant state with limited message history
+ const aiAssistantState = {
+ open: snap.open,
+ activeChatId: snap.activeChatId,
+ chats: snap.chats
+ ? Object.entries(snap.chats).reduce((acc, [chatId, chat]) => {
+ return {
+ ...acc,
+ [chatId]: {
+ ...chat,
+ messages: chat.messages?.slice(-20) || [], // Only keep last 20 messages
+ },
+ }
+ }, {})
+ : {},
+ }
+
+ localStorage.setItem(
+ LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef),
+ JSON.stringify(aiAssistantState)
+ )
+ })
+ }
+ }, [state, projectRef])
+
+ return (
+ <AiAssistantStateContext.Provider value={state}>{children}</AiAssistantStateContext.Provider>
+ )
+}
+
+export const useAiAssistantStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) => {
+ const state = useContext(AiAssistantStateContext)
+
+ return useSnapshot(state, options)
+}
diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.ts
index 21ff3556be6..75d73a7b57c 100644
--- a/apps/studio/state/app-state.ts
+++ b/apps/studio/state/app-state.ts
@@ -1,21 +1,8 @@
-import type { Message as MessageType } from 'ai/react'
+import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
+
import { LOCAL_STORAGE_KEYS as COMMON_LOCAL_STORAGE_KEYS } from 'common'
import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
-import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
-import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
-
-export type CommonDatabaseEntity = {
- id: number
- name: string
- schema: string
- [key: string]: any
-}
-
-export type SuggestionsType = {
- title: string
- prompts?: string[]
-}
export type Template = {
name: string
@@ -23,20 +10,6 @@ export type Template = {
content: string
}
-type AiAssistantPanelType = {
- open: boolean
- messages: MessageType[]
- initialInput: string
- sqlSnippets?: string[]
- suggestions?: SuggestionsType
- editor?: SupportedAssistantEntities | null
- // Raw string content for the monaco editor, currently used to retain where the user left off when toggling off the panel
- content?: string
- // Mainly used for editing a database entity (e.g editing a function, RLS policy etc)
- entity?: CommonDatabaseEntity
- tables: { schema: string; name: string }[]
-}
-
type EditorPanelType = {
open: boolean
initialValue?: string
@@ -53,18 +26,6 @@ type DashboardHistoryType = {
editor?: string
}
-const INITIAL_AI_ASSISTANT: AiAssistantPanelType = {
- open: false,
- messages: [],
- sqlSnippets: undefined,
- initialInput: '',
- suggestions: undefined,
- editor: null,
- content: '',
- entity: undefined,
- tables: [],
-}
-
const INITIAL_EDITOR_PANEL: EditorPanelType = {
open: false,
initialValue: '',
@@ -86,7 +47,6 @@ const EMPTY_DASHBOARD_HISTORY: DashboardHistoryType = {
const getInitialState = () => {
if (typeof window === 'undefined') {
return {
- aiAssistantPanel: INITIAL_AI_ASSISTANT,
editorPanel: INITIAL_EDITOR_PANEL,
dashboardHistory: EMPTY_DASHBOARD_HISTORY,
activeDocsSection: ['introduction'],
@@ -104,24 +64,11 @@ const getInitialState = () => {
}
}
- const stored = localStorage.getItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE)
const storedEditor = localStorage.getItem(LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE)
- const urlParams = new URLSearchParams(window.location.search)
- const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')
-
- let parsedAiAssistant = INITIAL_AI_ASSISTANT
let parsedEditorPanel = INITIAL_EDITOR_PANEL
try {
- if (stored) {
- parsedAiAssistant = JSON.parse(stored, (key, value) => {
- if (key === 'createdAt' && value) {
- return new Date(value)
- }
- return value
- })
- }
if (storedEditor) {
parsedEditorPanel = JSON.parse(storedEditor)
}
@@ -130,13 +77,6 @@ const getInitialState = () => {
}
return {
- aiAssistantPanel: {
- ...parsedAiAssistant,
- open:
- aiAssistantPanelOpenParam !== null
- ? aiAssistantPanelOpenParam === 'true'
- : parsedAiAssistant.open,
- },
editorPanel: parsedEditorPanel,
dashboardHistory: EMPTY_DASHBOARD_HISTORY,
activeDocsSection: ['introduction'],
@@ -218,45 +158,12 @@ export const appState = proxy({
appState.showSidebar = value
},
- resetAiAssistantPanel: () => {
- appState.aiAssistantPanel = {
- ...INITIAL_AI_ASSISTANT,
- open: appState.aiAssistantPanel.open,
- }
- },
-
- setAiAssistantPanel: (value: Partial<AiAssistantPanelType>) => {
- // Close Editor panel if AI Assistant panel is being opened
- if (value.open && appState.editorPanel.open) {
- appState.editorPanel.open = false
- }
-
- const hasEntityChanged = value.entity?.id !== appState.aiAssistantPanel.entity?.id
- appState.aiAssistantPanel = {
- ...appState.aiAssistantPanel,
- content: hasEntityChanged ? '' : appState.aiAssistantPanel.content,
- ...value,
- }
- },
-
showOngoingQueriesPanelOpen: false,
setOnGoingQueriesPanelOpen: (value: boolean) => {
appState.ongoingQueriesPanelOpen = value
},
- saveLatestMessage: (message: any) => {
- appState.aiAssistantPanel = {
- ...appState.aiAssistantPanel,
- messages: [...appState.aiAssistantPanel.messages, message],
- }
- },
-
setEditorPanel: (value: Partial<EditorPanelType>) => {
- // Close AI Assistant panel if editor panel is being opened
- if (value.open && appState.aiAssistantPanel.open) {
- appState.aiAssistantPanel.open = false
- }
-
// Reset templates to initial if initialValue is empty
if (value.initialValue === '') {
value.templates = INITIAL_EDITOR_PANEL.templates
@@ -281,15 +188,6 @@ export const appState = proxy({
// Set up localStorage subscriptions
if (typeof window !== 'undefined') {
subscribe(appState, () => {
- // Save AI assistant state with limited message history
- const aiAssistantState = {
- ...appState.aiAssistantPanel,
- // limit to 20 messages so as to not overflow the context window
- messages: appState.aiAssistantPanel.messages?.slice(-20),
- }
- localStorage.setItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE, JSON.stringify(aiAssistantState))
-
- // Save editor panel state
localStorage.setItem(
LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE,
JSON.stringify(appState.editorPanel)