Skip to content

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

feat: add routed assistant chat tabs to Explorer (#49031)

Saxon Fletcher85db94762c69
diff --git a/apps/studio/TANSTACK_MIGRATION.md b/apps/studio/TANSTACK_MIGRATION.md
index 3253c7a0a49..e9f5d3bb0b6 100644
--- a/apps/studio/TANSTACK_MIGRATION.md
+++ b/apps/studio/TANSTACK_MIGRATION.md
@@ -326,6 +326,7 @@ These are the layout-only TanStack files. Most hold a single product layout comp
- [x] A `routes/project/$ref/explorer/index.tsx` ← `pages/project/[ref]/explorer/index.tsx`
- [x] A `routes/project/$ref/explorer/notebook/$id.tsx` ← `pages/project/[ref]/explorer/notebook/[id].tsx`
+- [x] A `routes/project/$ref/explorer/chat/$id.tsx` ← `pages/project/[ref]/explorer/chat/[id].tsx`
### Auth shell — `/sign-in`, `/sign-up`, etc.
diff --git a/apps/studio/components/interfaces/Explorer/ChatEditor.tsx b/apps/studio/components/interfaces/Explorer/ChatEditor.tsx
new file mode 100644
index 00000000000..e7859c2ee53
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/ChatEditor.tsx
@@ -0,0 +1,99 @@
+import { useParams } from 'common'
+import { Loader2, MessageSquare } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { useEffect, useEffectEvent } from 'react'
+import { Button } from 'ui'
+
+import { useCreateChat } from './hooks'
+import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { AssistantChat } from '@/components/ui/AIAssistantPanel/AssistantChat'
+import { useAiAssistantState, useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
+import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
+import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
+
+export const ChatEditor = () => {
+ const { id, ref } = useParams()
+ const router = useRouter()
+ const tabs = useTabsStateSnapshot()
+ const aiAssistant = useAiAssistantStateSnapshot()
+ const aiAssistantState = useAiAssistantState()
+ const { createChat, openChat } = useCreateChat()
+ const { activeSidebar } = useSidebarManagerSnapshot()
+ const chat = id ? aiAssistant.chats[id] : undefined
+ const chatInstance = id ? aiAssistant.chatInstances[id] : undefined
+ const tabId = id ? createTabId('chat', { id }) : undefined
+ const shortcutsEnabled = activeSidebar?.id !== SIDEBAR_KEYS.AI_ASSISTANT
+
+ const syncChatTab = useEffectEvent(() => {
+ if (!id || !chat) return
+
+ aiAssistantState.ensureChatInstance(id)
+ const nextTabId = createTabId('chat', { id })
+ tabs.addTab({
+ id: nextTabId,
+ type: 'chat',
+ label: chat.name,
+ metadata: { chatId: id },
+ isPreview: false,
+ })
+ tabs.updateTab(nextTabId, { label: chat.name })
+ })
+
+ const removeDeletedChatTab = useEffectEvent(() => {
+ if (!tabId || !tabs.openTabs.includes(tabId)) return
+
+ tabs.handleTabClose({
+ id: tabId,
+ router,
+ editor: 'explorer',
+ onClearDashboardHistory: () => {},
+ })
+ })
+
+ useEffect(() => syncChatTab(), [id, chat?.name])
+
+ useEffect(() => {
+ if (aiAssistant.isInitialized && id && !chat) removeDeletedChatTab()
+ }, [aiAssistant.isInitialized, id, chat])
+
+ if (!aiAssistant.isInitialized || (chat && !chatInstance)) {
+ return (
+ <div className="h-full bg-surface-100 flex items-center justify-center">
+ <Loader2 className="animate-spin text-foreground-muted" />
+ </div>
+ )
+ }
+
+ if (!id || !chat) {
+ return (
+ <div className="h-full bg-surface-100 flex flex-col items-center justify-center gap-3 px-6 text-center">
+ <MessageSquare className="text-foreground-muted" />
+ <div>
+ <h2 className="text-sm text-foreground">Chat not found</h2>
+ <p className="text-sm text-foreground-lighter">
+ This chat may have been deleted or is no longer available.
+ </p>
+ </div>
+ <Button variant="default" onClick={() => router.push(`/project/${ref}/explorer`)}>
+ Back to Explorer
+ </Button>
+ </div>
+ )
+ }
+
+ const handleBranchChat = (messageId: string) => {
+ const branchId = aiAssistantState.createBranch(id, messageId)
+ if (branchId) openChat(branchId)
+ }
+
+ return (
+ <AssistantChat
+ chatId={id}
+ shortcutsEnabled={shortcutsEnabled}
+ className="bg-surface-100"
+ onNewChat={() => createChat()}
+ onSelectChat={openChat}
+ onBranchChat={handleBranchChat}
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ChatEditor.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ChatEditor.test.tsx
new file mode 100644
index 00000000000..1aa2d95956d
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ChatEditor.test.tsx
@@ -0,0 +1,122 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ChatEditor } from '../ChatEditor'
+import { customRender } from '@/tests/lib/custom-render'
+
+const mocks = vi.hoisted(() => ({
+ addTab: vi.fn(),
+ createBranch: vi.fn(),
+ createChat: vi.fn(),
+ ensureChatInstance: vi.fn(),
+ handleTabClose: vi.fn(),
+ openChat: vi.fn(),
+ push: vi.fn(),
+ updateTab: vi.fn(),
+ useParams: vi.fn(),
+ assistantSnapshot: vi.fn(),
+}))
+
+vi.mock('common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('common')>()
+ return { ...actual, useParams: () => mocks.useParams() }
+})
+
+vi.mock('next/router', () => ({
+ useRouter: () => ({ query: { ref: 'default' }, push: mocks.push }),
+}))
+
+vi.mock('@/components/interfaces/Explorer/hooks', () => ({
+ useCreateChat: () => ({ createChat: mocks.createChat, openChat: mocks.openChat }),
+}))
+
+vi.mock('@/state/tabs', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/state/tabs')>()
+ return {
+ ...actual,
+ useTabsStateSnapshot: () => ({
+ addTab: mocks.addTab,
+ handleTabClose: mocks.handleTabClose,
+ openTabs: ['chat-chat-1'],
+ updateTab: mocks.updateTab,
+ }),
+ }
+})
+
+vi.mock('@/state/ai-assistant-state', () => ({
+ useAiAssistantStateSnapshot: () => mocks.assistantSnapshot(),
+ useAiAssistantState: () => ({
+ createBranch: mocks.createBranch,
+ ensureChatInstance: mocks.ensureChatInstance,
+ }),
+}))
+
+vi.mock('@/state/sidebar-manager-state', () => ({
+ useSidebarManagerSnapshot: () => ({ activeSidebar: undefined }),
+}))
+
+vi.mock('@/components/ui/AIAssistantPanel/AssistantChat', () => ({
+ AssistantChat: ({
+ chatId,
+ onSelectChat,
+ }: {
+ chatId: string
+ onSelectChat: (id: string) => void
+ }) => (
+ <button type="button" tabIndex={0} data-chat-id={chatId} onClick={() => onSelectChat('chat-2')}>
+ Assistant
+ </button>
+ ),
+}))
+
+describe('ChatEditor', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.useParams.mockReturnValue({ ref: 'default', id: 'chat-1' })
+ mocks.assistantSnapshot.mockReturnValue({
+ isInitialized: true,
+ chats: { 'chat-1': { id: 'chat-1', name: 'Investigate errors' } },
+ chatInstances: { 'chat-1': {} },
+ })
+ })
+
+ it('renders and registers the routed chat without changing sidebar selection', () => {
+ customRender(<ChatEditor />)
+
+ expect(mocks.ensureChatInstance).toHaveBeenCalledWith('chat-1')
+ expect(screen.getByRole('button', { name: 'Assistant' })).toHaveAttribute(
+ 'data-chat-id',
+ 'chat-1'
+ )
+ expect(mocks.addTab).toHaveBeenCalledWith({
+ id: 'chat-chat-1',
+ type: 'chat',
+ label: 'Investigate errors',
+ metadata: { chatId: 'chat-1' },
+ isPreview: false,
+ })
+ })
+
+ it('routes shared chat navigation through Explorer', () => {
+ customRender(<ChatEditor />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Assistant' }))
+
+ expect(mocks.openChat).toHaveBeenCalledWith('chat-2')
+ })
+
+ it('removes an orphaned tab only after chat hydration completes', () => {
+ mocks.assistantSnapshot.mockReturnValue({
+ isInitialized: true,
+ chats: {},
+ chatInstances: {},
+ })
+
+ customRender(<ChatEditor />)
+
+ expect(screen.getByRole('heading', { name: 'Chat not found' })).toBeVisible()
+ expect(mocks.handleTabClose).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'chat-chat-1', editor: 'explorer' })
+ )
+ })
+})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx
new file mode 100644
index 00000000000..321dbd4c94d
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx
@@ -0,0 +1,111 @@
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useCreateChat } from '../hooks'
+
+const {
+ mockCreateChat,
+ mockPush,
+ mockSelectChat,
+ mockSetContext,
+ mockSetModel,
+ mockWhenInitialized,
+} = vi.hoisted(() => ({
+ mockCreateChat: vi.fn(() => 'chat-2'),
+ mockPush: vi.fn(),
+ mockSelectChat: vi.fn(),
+ mockSetContext: vi.fn(),
+ mockSetModel: vi.fn(),
+ mockWhenInitialized: vi.fn(() => Promise.resolve()),
+}))
+
+vi.mock('next/router', () => ({ useRouter: () => ({ push: mockPush }) }))
+vi.mock('@/hooks/misc/useSelectedProject', () => ({
+ useSelectedProjectQuery: () => ({
+ data: { ref: 'default', connectionString: 'postgres://example' },
+ }),
+}))
+vi.mock('@/hooks/misc/useSelectedOrganization', () => ({
+ useSelectedOrganizationQuery: () => ({ data: { slug: 'acme' } }),
+}))
+vi.mock('@/state/ai-assistant-state', () => ({
+ useAiAssistantState: () => ({
+ createChat: mockCreateChat,
+ selectChat: mockSelectChat,
+ setContext: mockSetContext,
+ setModel: mockSetModel,
+ }),
+ whenAiAssistantInitialized: () => mockWhenInitialized(),
+}))
+
+describe('useCreateChat', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockWhenInitialized.mockImplementation(() => Promise.resolve())
+ })
+
+ it('creates and opens Explorer chats without changing the sidebar selection', async () => {
+ const { result } = renderHook(() => useCreateChat())
+
+ await act(async () => {
+ await result.current.createChat({
+ name: 'Investigate errors',
+ initialMessage: 'What happened?',
+ model: 'gpt-5.4-nano',
+ })
+ })
+
+ expect(mockSetContext).toHaveBeenCalledWith({
+ projectRef: 'default',
+ orgSlug: 'acme',
+ connectionString: 'postgres://example',
+ })
+ expect(mockCreateChat).toHaveBeenCalledWith({
+ name: 'Investigate errors',
+ initialMessage: 'What happened?',
+ })
+ expect(mockSetModel).toHaveBeenCalledWith('gpt-5.4-nano')
+ expect(mockPush).toHaveBeenCalledWith('/project/default/explorer/chat/chat-2')
+ expect(mockSelectChat).not.toHaveBeenCalled()
+
+ act(() => result.current.openChat('chat-1'))
+
+ expect(mockPush).toHaveBeenLastCalledWith('/project/default/explorer/chat/chat-1')
+ expect(mockSelectChat).not.toHaveBeenCalled()
+ })
+
+ // Hydration replaces the chat map and the model wholesale, so a chat created mid-load would be
+ // dropped the moment the persisted state lands
+ it('waits for the assistant state to hydrate before creating the chat', async () => {
+ let resolveHydration = () => {}
+ mockWhenInitialized.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveHydration = resolve
+ })
+ )
+
+ const { result } = renderHook(() => useCreateChat())
+
+ let created: Promise<string | undefined> | undefined
+ await act(async () => {
+ created = result.current.createChat({ name: 'Investigate errors', model: 'gpt-5.4-nano' })
+ })
+
+ expect(mockCreateChat).not.toHaveBeenCalled()
+ expect(mockSetModel).not.toHaveBeenCalled()
+ expect(mockPush).not.toHaveBeenCalled()
+
+ await act(async () => {
+ resolveHydration()
+ await created
+ })
+
+ expect(mockCreateChat).toHaveBeenCalledWith({
+ name: 'Investigate errors',
+ initialMessage: undefined,
+ })
+ expect(mockSetModel).toHaveBeenCalledWith('gpt-5.4-nano')
+ expect(mockPush).toHaveBeenCalledWith('/project/default/explorer/chat/chat-2')
+ })
+})
diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.ts
index 506236d2cf2..61449136ffa 100644
--- a/apps/studio/components/interfaces/Explorer/hooks.ts
+++ b/apps/studio/components/interfaces/Explorer/hooks.ts
@@ -1,9 +1,12 @@
import { useRouter } from 'next/router'
import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'
+import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { generateUuid } from '@/lib/api/snippets.browser'
import { useProfile } from '@/lib/profile'
+import type { AssistantModel } from '@/state/ai-assistant-state'
+import { useAiAssistantState, whenAiAssistantInitialized } from '@/state/ai-assistant-state'
import { useExplorerQueryStateSnapshot } from '@/state/explorer-query'
import { useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
import { type Notebook } from '@/state/notebooks/types'
@@ -73,6 +76,54 @@ This is a sample paragraph to demonstrate the Markdown cells
return { createNotebook }
}
+export const useCreateChat = () => {
+ const router = useRouter()
+ const { data: project } = useSelectedProjectQuery()
+ const { data: organization } = useSelectedOrganizationQuery()
+ const aiAssistantState = useAiAssistantState()
+
+ const openChat = (id: string) => {
+ if (!project) {
+ console.error('Project is required')
+ return undefined
+ }
+
+ router.push(`/project/${project.ref}/explorer/chat/${id}`)
+ }
+
+ const createChat = async ({
+ name,
+ initialMessage,
+ model,
+ }: {
+ name?: string
+ initialMessage?: string
+ model?: AssistantModel
+ } = {}) => {
+ if (!project) {
+ console.error('Project is required')
+ return undefined
+ }
+
+ // Hydration replaces the chat map and the selected model wholesale, so wait it out before
+ // creating anything — otherwise the new chat is dropped as soon as the persisted state lands.
+ await whenAiAssistantInitialized(aiAssistantState)
+
+ aiAssistantState.setContext({
+ projectRef: project.ref,
+ orgSlug: organization?.slug,
+ connectionString: project.connectionString ?? '',
+ })
+ if (model) aiAssistantState.setModel(model)
+
+ const id = aiAssistantState.createChat({ name, initialMessage })
+ router.push(`/project/${project.ref}/explorer/chat/${id}`)
+ return id
+ }
+
+ return { createChat, openChat }
+}
+
export const useCreateQuery = () => {
const router = useRouter()
const { data: project } = useSelectedProjectQuery()
diff --git a/apps/studio/components/layouts/Tabs/Tabs.tsx b/apps/studio/components/layouts/Tabs/Tabs.tsx
index 734071d8879..7191cbe0ac5 100644
--- a/apps/studio/components/layouts/Tabs/Tabs.tsx
+++ b/apps/studio/components/layouts/Tabs/Tabs.tsx
@@ -93,7 +93,8 @@ export const EditorTabs = ({
const onClearDashboardHistory = () => {
if (editor === 'table') {
setLastVisitedTable(undefined)
- } else if (editor === 'sql') {
+ }
+ if (editor === 'sql') {
setLastVisitedSnippet(undefined)
}
}
@@ -138,7 +139,8 @@ export const EditorTabs = ({
closeWithConfirmation(tabsToClose, () => {
tabs.closeTabs(tabsToClose)
onClearDashboardHistory()
- tabs.handleTabNavigation(tabId, router)
+
+ if (tabs.activeTab !== tabId) tabs.handleTabNavigation(tabId, router)
})
}
}
diff --git a/apps/studio/components/ui/EntityTypeIcon.tsx b/apps/studio/components/ui/EntityTypeIcon.tsx
index 755e3d0ba87..6e4b826c17f 100644
--- a/apps/studio/components/ui/EntityTypeIcon.tsx
+++ b/apps/studio/components/ui/EntityTypeIcon.tsx
@@ -1,4 +1,12 @@
-import { Eye, GitBranch, NotebookText, ScrollText, SquareCode, Table2 } from 'lucide-react'
+import {
+ Eye,
+ GitBranch,
+ MessageSquare,
+ NotebookText,
+ ScrollText,
+ SquareCode,
+ Table2,
+} from 'lucide-react'
import { cn, SQL_ICON } from 'ui'
import type { SqlSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
@@ -37,6 +45,7 @@ interface EntityTypeIconProps {
| 'p'
| 'notebook'
| 'query'
+ | 'chat'
| 'explorer-home'
size?: number
strokeWidth?: number
@@ -122,6 +131,10 @@ export const EntityTypeIcon = ({
return <SquareCode size={size} strokeWidth={strokeWidth} />
}
+ if (type === 'chat') {
+ return <MessageSquare size={size} strokeWidth={strokeWidth} />
+ }
+
return (
<div
className={cn(
diff --git a/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx b/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx
new file mode 100644
index 00000000000..4bb149dac09
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx
@@ -0,0 +1,14 @@
+import { ChatEditor } from '@/components/interfaces/Explorer/ChatEditor'
+import { DefaultLayout } from '@/components/layouts/DefaultLayout'
+import { ExplorerLayout } from '@/components/layouts/ExplorerLayout/ExplorerLayout'
+import type { NextPageWithLayout } from '@/types'
+
+const ChatPage: NextPageWithLayout = () => <ChatEditor />
+
+ChatPage.getLayout = (page) => (
+ <DefaultLayout>
+ <ExplorerLayout>{page}</ExplorerLayout>
+ </DefaultLayout>
+)
+
+export default ChatPage
diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts
index 57160fc4e24..182686af6c9 100644
--- a/apps/studio/routeTree.gen.ts
+++ b/apps/studio/routeTree.gen.ts
@@ -231,6 +231,7 @@ import { Route as ProjectRefFunctionsFunctionSlugDetailsRouteImport } from './ro
import { Route as ProjectRefFunctionsFunctionSlugCodeRouteImport } from './routes/project/$ref/functions/$functionSlug/code'
import { Route as ProjectRefExplorerQueryIdRouteImport } from './routes/project/$ref/explorer/query/$id'
import { Route as ProjectRefExplorerNotebookIdRouteImport } from './routes/project/$ref/explorer/notebook/$id'
+import { Route as ProjectRefExplorerChatIdRouteImport } from './routes/project/$ref/explorer/chat/$id'
import { Route as ProjectRefDatabaseTriggersEventRouteImport } from './routes/project/$ref/database/triggers/event'
import { Route as ProjectRefDatabaseTriggersDataRouteImport } from './routes/project/$ref/database/triggers/data'
import { Route as ProjectRefDatabaseTablesIdRouteImport } from './routes/project/$ref/database/tables/$id'
@@ -1529,6 +1530,12 @@ const ProjectRefExplorerNotebookIdRoute =
path: '/notebook/$id',
getParentRoute: () => ProjectRefExplorerRoute,
} as any)
+const ProjectRefExplorerChatIdRoute =
+ ProjectRefExplorerChatIdRouteImport.update({
+ id: '/chat/$id',
+ path: '/chat/$id',
+ getParentRoute: () => ProjectRefExplorerRoute,
+ } as any)
const ProjectRefDatabaseTriggersEventRoute =
ProjectRefDatabaseTriggersEventRouteImport.update({
id: '/event',
@@ -2289,6 +2296,7 @@ export interface FileRoutesByFullPath {
'/project/$ref/database/tables/$id': typeof ProjectRefDatabaseTablesIdRoute
'/project/$ref/database/triggers/data': typeof ProjectRefDatabaseTriggersDataRoute
'/project/$ref/database/triggers/event': typeof ProjectRefDatabaseTriggersEventRoute
+ '/project/$ref/explorer/chat/$id': typeof ProjectRefExplorerChatIdRoute
'/project/$ref/explorer/notebook/$id': typeof ProjectRefExplorerNotebookIdRoute
'/project/$ref/explorer/query/$id': typeof ProjectRefExplorerQueryIdRoute
'/project/$ref/functions/$functionSlug/code': typeof ProjectRefFunctionsFunctionSlugCodeRoute
@@ -2587,6 +2595,7 @@ export interface FileRoutesByTo {
'/project/$ref/database/tables/$id': typeof ProjectRefDatabaseTablesIdRoute
'/project/$ref/database/triggers/data': typeof ProjectRefDatabaseTriggersDataRoute
'/project/$ref/database/triggers/event': typeof ProjectRefDatabaseTriggersEventRoute
+ '/project/$ref/explorer/chat/$id': typeof ProjectRefExplorerChatIdRoute
'/project/$ref/explorer/notebook/$id': typeof ProjectRefExplorerNotebookIdRoute
'/project/$ref/explorer/query/$id': typeof ProjectRefExplorerQueryIdRoute
'/project/$ref/functions/$functionSlug/code': typeof ProjectRefFunctionsFunctionSlugCodeRoute
@@ -2901,6 +2910,7 @@ export interface FileRoutesById {
'/project/$ref/database/tables/$id': typeof ProjectRefDatabaseTablesIdRoute
'/project/$ref/database/triggers/data': typeof ProjectRefDatabaseTriggersDataRoute
'/project/$ref/database/triggers/event': typeof ProjectRefDatabaseTriggersEventRoute
+ '/project/$ref/explorer/chat/$id': typeof ProjectRefExplorerChatIdRoute
'/project/$ref/explorer/notebook/$id': typeof ProjectRefExplorerNotebookIdRoute
'/project/$ref/explorer/query/$id': typeof ProjectRefExplorerQueryIdRoute
'/project/$ref/functions/$functionSlug/code': typeof ProjectRefFunctionsFunctionSlugCodeRoute
@@ -3214,6 +3224,7 @@ export interface FileRouteTypes {
| '/project/$ref/database/tables/$id'
| '/project/$ref/database/triggers/data'
| '/project/$ref/database/triggers/event'
+ | '/project/$ref/explorer/chat/$id'
| '/project/$ref/explorer/notebook/$id'
| '/project/$ref/explorer/query/$id'
| '/project/$ref/functions/$functionSlug/code'
@@ -3512,6 +3523,7 @@ export interface FileRouteTypes {
| '/project/$ref/database/tables/$id'
| '/project/$ref/database/triggers/data'
| '/project/$ref/database/triggers/event'
+ | '/project/$ref/explorer/chat/$id'
| '/project/$ref/explorer/notebook/$id'
| '/project/$ref/explorer/query/$id'
| '/project/$ref/functions/$functionSlug/code'
@@ -3825,6 +3837,7 @@ export interface FileRouteTypes {
| '/project/$ref/database/tables/$id'
| '/project/$ref/database/triggers/data'
| '/project/$ref/database/triggers/event'
+ | '/project/$ref/explorer/chat/$id'
| '/project/$ref/explorer/notebook/$id'
| '/project/$ref/explorer/query/$id'
| '/project/$ref/functions/$functionSlug/code'
@@ -5588,6 +5601,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectRefExplorerNotebookIdRouteImport
parentRoute: typeof ProjectRefExplorerRoute
}
+ '/project/$ref/explorer/chat/$id': {
+ id: '/project/$ref/explorer/chat/$id'
+ path: '/chat/$id'
+ fullPath: '/project/$ref/explorer/chat/$id'
+ preLoaderRoute: typeof ProjectRefExplorerChatIdRouteImport
+ parentRoute: typeof ProjectRefExplorerRoute
+ }
'/project/$ref/database/triggers/event': {
id: '/project/$ref/database/triggers/event'
path: '/event'
@@ -6536,12 +6556,14 @@ const ProjectRefEditorRouteWithChildren =
interface ProjectRefExplorerRouteChildren {
ProjectRefExplorerIndexRoute: typeof ProjectRefExplorerIndexRoute
+ ProjectRefExplorerChatIdRoute: typeof ProjectRefExplorerChatIdRoute
ProjectRefExplorerNotebookIdRoute: typeof ProjectRefExplorerNotebookIdRoute
ProjectRefExplorerQueryIdRoute: typeof ProjectRefExplorerQueryIdRoute
}
const ProjectRefExplorerRouteChildren: ProjectRefExplorerRouteChildren = {
ProjectRefExplorerIndexRoute: ProjectRefExplorerIndexRoute,
+ ProjectRefExplorerChatIdRoute: ProjectRefExplorerChatIdRoute,
ProjectRefExplorerNotebookIdRoute: ProjectRefExplorerNotebookIdRoute,
ProjectRefExplorerQueryIdRoute: ProjectRefExplorerQueryIdRoute,
}
diff --git a/apps/studio/routes/project/$ref/explorer/chat/$id.tsx b/apps/studio/routes/project/$ref/explorer/chat/$id.tsx
new file mode 100644
index 00000000000..5ebd59a8e42
--- /dev/null
+++ b/apps/studio/routes/project/$ref/explorer/chat/$id.tsx
@@ -0,0 +1,11 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+import { ChatEditor } from '@/components/interfaces/Explorer/ChatEditor'
+
+export const Route = createFileRoute('/project/$ref/explorer/chat/$id')({
+ component: ProjectExplorerChatRoute,
+})
+
+function ProjectExplorerChatRoute() {
+ return <ChatEditor />
+}
diff --git a/apps/studio/state/ai-assistant-state.test.ts b/apps/studio/state/ai-assistant-state.test.ts
index d4670010878..10dca9ca78d 100644
--- a/apps/studio/state/ai-assistant-state.test.ts
+++ b/apps/studio/state/ai-assistant-state.test.ts
@@ -1,7 +1,11 @@
import { proxy, ref } from 'valtio/vanilla'
import { describe, expect, it } from 'vitest'
-import { createAiAssistantState, sanitizeForCloning } from './ai-assistant-state'
+import {
+ createAiAssistantState,
+ sanitizeForCloning,
+ whenAiAssistantInitialized,
+} from './ai-assistant-state'
describe('AI assistant chat message sync', () => {
// FE-3954: syncing the live array into valtio corrupted it with Proxies, breaking structuredClone in addToolApprovalResponse
@@ -123,3 +127,44 @@ describe('AI assistant chat surface isolation', () => {
expect(state.chatInstances[chatId].messages).toEqual(state.chats[chatId].messages)
})
})
+
+describe('whenAiAssistantInitialized', () => {
+ it('resolves immediately once the state has hydrated', async () => {
+ const state = createAiAssistantState()
+ state.isInitialized = true
+
+ await expect(whenAiAssistantInitialized(state)).resolves.toBeUndefined()
+ })
+
+ // loadPersistedState replaces state.chats wholesale, so a chat created before hydration is lost
+ it('defers chat creation until hydration lands so the new chat survives', async () => {
+ const state = createAiAssistantState()
+
+ const pending = whenAiAssistantInitialized(state)
+ const droppedChatId = state.createChat({ name: 'Created too early' })
+
+ state.loadPersistedState({
+ projectRef: 'default',
+ activeChatId: 'persisted-chat',
+ model: state.model,
+ chats: {
+ 'persisted-chat': {
+ id: 'persisted-chat',
+ name: 'Persisted chat',
+ messages: [],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ },
+ },
+ })
+ state.isInitialized = true
+
+ expect(state.chats[droppedChatId]).toBeUndefined()
+
+ await pending
+ const chatId = state.createChat({ name: 'Created after hydration' })
+
+ expect(state.chats[chatId]?.name).toBe('Created after hydration')
+ expect(state.chats['persisted-chat']).toBeDefined()
+ })
+})
diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsx
index 8e0413bbc46..4352931d244 100644
--- a/apps/studio/state/ai-assistant-state.tsx
+++ b/apps/studio/state/ai-assistant-state.tsx
@@ -375,6 +375,7 @@ export const createAiAssistantState = (): AiAssistantState => {
chatInstances: {},
pendingSpanIds: {},
messageSpanIds: {},
+ isInitialized: false,
setContext: (context: Partial<AiAssistantContext>) => {
state.context = { ...state.context, ...context }
@@ -382,6 +383,7 @@ export const createAiAssistantState = (): AiAssistantState => {
resetAiAssistantPanel: () => {
Object.assign(state, createInitialAiAssistantData())
+ state.isInitialized = false
},
setModel: (model: AssistantModel) => {
@@ -675,6 +677,7 @@ export type AiAssistantState = AiAssistantData & {
chatInstances: Record<string, Chat<MessageType>>
pendingSpanIds: Record<string, string>
messageSpanIds: Record<string, string>
+ isInitialized: boolean
setContext: (context: Partial<AiAssistantContext>) => void
setModel: (model: AssistantModel) => void
createChat: (options?: CreateChatOptions) => string
@@ -705,6 +708,7 @@ export const AiAssistantStateContextProvider = ({ children }: PropsWithChildren)
// Effect to load state from IndexedDB on mount or projectRef change
useEffect(() => {
let isMounted = true
+ state.isInitialized = false
async function loadAndInitializeState() {
if (!project?.ref || typeof window === 'undefined') {
@@ -733,6 +737,7 @@ export const AiAssistantStateContextProvider = ({ children }: PropsWithChildren)
// 4. Ensure an active chat exists and handle URL overrides
ensureActiveChatOrInitialize(state)
+ state.isInitialized = true
}
loadAndInitializeState()
@@ -792,6 +797,23 @@ export const useAiAssistantStateSnapshot = (options?: Parameters<typeof useSnaps
return useSnapshot(state, options)
}
+/**
+ * Resolves once the assistant state has hydrated from storage. `loadPersistedState` replaces
+ * `state.chats` wholesale, so anything that adds a chat has to wait for hydration or the new
+ * chat is dropped the moment the persisted state lands.
+ */
+export const whenAiAssistantInitialized = (state: AiAssistantState): Promise<void> => {
+ if (state.isInitialized) return Promise.resolve()
+
+ return new Promise((resolve) => {
+ const unsubscribe = subscribe(state, () => {
+ if (!state.isInitialized) return
+ unsubscribe()
+ resolve()
+ })
+ })
+}
+
export const useAiAssistantState = () => {
const state = useContext(AiAssistantStateContext)
return state
diff --git a/apps/studio/state/tabs.test.ts b/apps/studio/state/tabs.test.ts
index b5545269d09..c333833ca60 100644
--- a/apps/studio/state/tabs.test.ts
+++ b/apps/studio/state/tabs.test.ts
@@ -1,7 +1,7 @@
import type { NextRouter } from 'next/router'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { createTabsState, type Tab } from './tabs'
+import { createTabId, createTabsState, type Tab } from './tabs'
import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
const fakeRouter = () => ({ query: { ref: 'default' }, push: vi.fn() }) as unknown as NextRouter
@@ -14,6 +14,52 @@ const sqlTab = (id: string): Tab => ({
metadata: { sqlId: id },
})
+describe('Explorer chat tabs', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ it('creates stable chat tab ids and navigates to the chat route', () => {
+ const store = createTabsState('default')
+ const router = fakeRouter()
+ const id = createTabId('chat', { id: 'assistant-chat-id' })
+
+ store.addTab({
+ id,
+ type: 'chat',
+ label: 'Investigate errors',
+ metadata: { chatId: 'assistant-chat-id' },
+ isPreview: false,
+ })
+ store.handleTabNavigation(id, router)
+
+ expect(id).toBe('chat-assistant-chat-id')
+ expect(router.push).toHaveBeenCalledWith('/project/default/explorer/chat/assistant-chat-id')
+ })
+
+ it('returns to Explorer home when the final chat tab closes', () => {
+ const store = createTabsState('default')
+ const router = fakeRouter()
+ const id = createTabId('chat', { id: 'assistant-chat-id' })
+
+ store.addTab({
+ id,
+ type: 'chat',
+ label: 'Investigate errors',
+ metadata: { chatId: 'assistant-chat-id' },
+ isPreview: false,
+ })
+ store.handleTabClose({
+ id,
+ router,
+ editor: 'explorer',
+ onClearDashboardHistory: () => {},
+ })
+
+ expect(router.push).toHaveBeenCalledWith('/project/default/explorer')
+ })
+})
+
describe('tabs recent items', () => {
beforeEach(() => {
localStorage.clear()
diff --git a/apps/studio/state/tabs.tsx b/apps/studio/state/tabs.tsx
index fbef013a927..bc1a2cbfcb3 100644
--- a/apps/studio/state/tabs.tsx
+++ b/apps/studio/state/tabs.tsx
@@ -19,10 +19,10 @@ import type { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
export const editorEntityTypes = {
table: ['r', 'v', 'm', 'f', 'p'],
sql: ['sql'],
- explorer: ['notebook', 'query'],
+ explorer: ['notebook', 'query', 'chat'],
}
-export type TabType = ENTITY_TYPE | 'sql' | 'notebook' | 'query' | 'explorer-home'
+export type TabType = ENTITY_TYPE | 'sql' | 'notebook' | 'query' | 'chat' | 'explorer-home'
/** Fixed id for Explorer's pinned, non-closable Home tab. */
export const EXPLORER_HOME_TAB_ID = 'explorer-home'
@@ -45,6 +45,7 @@ type CreateTabIdParams = {
sql: { id: string }
notebook: { id: string }
query: { id: string }
+ chat: { id: string }
schema: { schema: string }
view: never
function: never
@@ -63,6 +64,7 @@ export interface Tab {
sqlId?: string
notebookId?: string
queryId?: string
+ chatId?: string
scrollTop?: number
/**
* For SQL tabs, which backend the snippet queries (`'database'` | `'logs'`),
@@ -134,6 +136,7 @@ export interface RecentItem {
sqlId?: string
notebookId?: string
queryId?: string
+ chatId?: string
sqlSource?: SqlSnippetSource
}
}
@@ -438,6 +441,9 @@ export function createTabsState(projectRef: string) {
case 'query':
router.push(`/project/${router.query.ref}/explorer/query/${tab.metadata?.queryId}`)
break
+ case 'chat':
+ router.push(`/project/${router.query.ref}/explorer/chat/${tab.metadata?.chatId}`)
+ break
case 'explorer-home':
router.push(`/project/${router.query.ref}/explorer`)
break
@@ -576,6 +582,7 @@ export function createTabsState(projectRef: string) {
break
case 'notebook':
case 'query':
+ case 'chat':
router.push(`/project/${router.query.ref}/explorer`)
break
case 'r':
@@ -702,6 +709,8 @@ export function createTabId<T extends TabType>(type: T, params: CreateTabIdParam
return `notebook-${(params as CreateTabIdParams['notebook']).id}`
case 'query':
return `query-${(params as CreateTabIdParams['query']).id}`
+ case 'chat':
+ return `chat-${(params as CreateTabIdParams['chat']).id}`
default:
return ''
}