Skip to content

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

feat: Support Form - Sync AI assistant conversation to Front (#46778)

Carel de Waal0acc0eb8b39c
diff --git a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
index 7bde18ffcfc..544d407176a 100644
--- a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
+++ b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx
@@ -7,15 +7,23 @@ import type { SubmittedSupportRequest } from './SupportForm.state'
import { NO_PROJECT_MARKER } from './SupportForm.utils'
import { SupportAssistantSuccessCardContent as SupportAssistantSuccessCard } from '@/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent'
-const { chatInstances, mockNewChat, mockOpenSidebar, mockSelectChat, mockTrack } = vi.hoisted(
- () => ({
- chatInstances: {} as Record<string, MockChat>,
- mockNewChat: vi.fn(),
- mockOpenSidebar: vi.fn(),
- mockSelectChat: vi.fn(),
- mockTrack: vi.fn(),
- })
-)
+const {
+ chatInstances,
+ chats,
+ mockNewChat,
+ mockOpenSidebar,
+ mockSelectChat,
+ mockSyncSupportChatToFront,
+ mockTrack,
+} = vi.hoisted(() => ({
+ chatInstances: {} as Record<string, MockChat>,
+ chats: {} as Record<string, { messages: unknown[]; supportMetadata?: unknown }>,
+ mockNewChat: vi.fn(),
+ mockOpenSidebar: vi.fn(),
+ mockSelectChat: vi.fn(),
+ mockSyncSupportChatToFront: vi.fn(),
+ mockTrack: vi.fn(),
+}))
type MockChat = {
messages: Array<{ id: string; role: string; parts: Array<{ type: string; text: string }> }>
@@ -40,6 +48,14 @@ vi.mock('@/state/ai-assistant-state', () => ({
newChat: mockNewChat,
selectChat: mockSelectChat,
}),
+ useAiAssistantState: () => ({
+ chats,
+ selectChat: mockSelectChat,
+ }),
+}))
+
+vi.mock('@/state/ai-chat-front-sync', () => ({
+ syncSupportChatToFront: mockSyncSupportChatToFront,
}))
vi.mock('@/state/sidebar-manager-state', () => ({
@@ -63,6 +79,8 @@ const supportRequest: SubmittedSupportRequest = {
library: 'javascript',
allowSupportAccess: true,
dashboardLogs: undefined,
+ threadRef: 'thread-ref-1',
+ frontConversationId: 'front-conversation-1',
}
describe('SupportAssistantSuccessCard', () => {
@@ -81,15 +99,18 @@ describe('SupportAssistantSuccessCard', () => {
beforeEach(() => {
Object.keys(chatInstances).forEach((key) => delete chatInstances[key])
+ Object.keys(chats).forEach((key) => delete chats[key])
mockNewChat.mockReset()
mockOpenSidebar.mockReset()
mockSelectChat.mockReset()
+ mockSyncSupportChatToFront.mockReset()
mockTrack.mockReset()
nextChatMessages = []
emitChatMessagesChange = undefined
mockNewChat.mockImplementation(() => {
chatInstances['chat-1'] = createMockChat(nextChatMessages)
+ chats['chat-1'] = { messages: nextChatMessages }
return 'chat-1'
})
})
@@ -179,6 +200,48 @@ describe('SupportAssistantSuccessCard', () => {
expect(mockOpenSidebar).toHaveBeenCalledWith('ai-assistant')
})
+ it('tags the chat as a support chat and syncs it to Front on first open', async () => {
+ const user = userEvent.setup()
+ render(<SupportAssistantSuccessCard request={supportRequest} />)
+
+ const button = await screen.findByRole('button', { name: /open assistant response/i })
+ await user.click(button)
+
+ expect(chats['chat-1'].supportMetadata).toMatchObject({
+ isSupportChat: true,
+ lifecycleStatus: 'bot_active',
+ subject: 'API requests fail',
+ category: SupportCategories.PROBLEM,
+ severity: 'Normal',
+ organizationSlug: 'org-1',
+ projectRef: 'project-1',
+ allowSupportAccess: true,
+ threadRef: 'thread-ref-1',
+ frontConversationId: 'front-conversation-1',
+ lastSyncedMessageCount: 0,
+ isSyncing: false,
+ isLifecycleSyncing: false,
+ })
+
+ // The initial flush is behind a dynamic import, so it lands asynchronously
+ await waitFor(() => {
+ expect(mockSyncSupportChatToFront).toHaveBeenCalledWith(
+ 'chat-1',
+ expect.objectContaining({ chats })
+ )
+ })
+
+ // A second open must not re-tag the chat or trigger another initial flush
+ const taggedMetadata = chats['chat-1'].supportMetadata
+ await user.click(button)
+
+ await waitFor(() => {
+ expect(mockSelectChat).toHaveBeenCalledTimes(2)
+ })
+ expect(chats['chat-1'].supportMetadata).toBe(taggedMetadata)
+ expect(mockSyncSupportChatToFront).toHaveBeenCalledTimes(1)
+ })
+
it('opens the generated assistant chat with keyboard activation', async () => {
const user = userEvent.setup()
render(<SupportAssistantSuccessCard request={supportRequest} />)
diff --git a/apps/studio/components/interfaces/Support/SupportForm.state.ts b/apps/studio/components/interfaces/Support/SupportForm.state.ts
index 3caac18083d..678c7bc0c9f 100644
--- a/apps/studio/components/interfaces/Support/SupportForm.state.ts
+++ b/apps/studio/components/interfaces/Support/SupportForm.state.ts
@@ -10,6 +10,10 @@ export type SubmittedSupportRequest = Pick<
projectRef: string | undefined
library?: string
dashboardLogs?: string
+ // Front conversation created at submit + the thread_ref used to create it, so the
+ // AI support chat can append to the same conversation if the user engages it.
+ threadRef?: string
+ frontConversationId?: string
}
export type SupportFormState =
diff --git a/apps/studio/components/interfaces/Support/SupportFormV3.tsx b/apps/studio/components/interfaces/Support/SupportFormV3.tsx
index 553dd433d88..5235151c4ce 100644
--- a/apps/studio/components/interfaces/Support/SupportFormV3.tsx
+++ b/apps/studio/components/interfaces/Support/SupportFormV3.tsx
@@ -5,6 +5,7 @@ import { CLIENT_LIBRARIES } from 'common/constants'
import { type Dispatch, type MouseEventHandler } from 'react'
import type { SubmitHandler, UseFormReturn } from 'react-hook-form'
import { Form, Separator } from 'ui'
+import { v4 as uuidv4 } from 'uuid'
import {
AffectedServicesSelector,
@@ -98,7 +99,7 @@ export const SupportFormV3 = ({
})
const { mutate: submitSupportTicket } = useSendSupportTicketMutation({
- onSuccess: (_, variables) => {
+ onSuccess: (data, variables) => {
dispatch({
type: 'SUCCESS',
sentProjectRef: variables.projectRef,
@@ -115,6 +116,10 @@ export const SupportFormV3 = ({
library: variables.library,
allowSupportAccess: variables.allowSupportAccess,
dashboardLogs: variables.dashboardLogs,
+ // Front conversation created by this submission + the thread_ref used to
+ // create it, so the AI support chat can append to the same conversation.
+ threadRef: variables.threadRef,
+ frontConversationId: data?.conversationId,
},
})
},
@@ -192,6 +197,11 @@ export const SupportFormV3 = ({
browserInformation: detectBrowser(),
dashboardLogs: dashboardLogUrl?.[0],
dashboardStudioVersion: commit ? formatStudioVersion(commit) : undefined,
+ // Stable Front thread_ref so the AI support chat (if the user engages it) can
+ // be appended to the same Front conversation this submission creates. Use the
+ // uuid package rather than crypto.randomUUID(), which is undefined in insecure
+ // contexts (non-localhost HTTP) and would throw, silently aborting the submit.
+ threadRef: uuidv4(),
}
if (values.projectRef !== NO_PROJECT_MARKER) {
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index 62ec0219eea..435e8157739 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -177,7 +177,13 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const isChatLoading = chatStatus === 'submitted' || chatStatus === 'streaming'
const hasPendingApproval = hasPendingToolApproval(chatMessages)
- const isChatInputDisabled = !isApiKeySet || disablePrompts || isLoadingOrganization
+ const supportMetadata = snap.activeChat?.supportMetadata
+ const isSupportChat = !!supportMetadata?.isSupportChat
+ const isSupportChatClosed = isSupportChat && supportMetadata.lifecycleStatus !== 'bot_active'
+ const activeChatId = snap.activeChatId
+ const supportConversationId = supportMetadata?.frontConversationId
+ const isChatInputDisabled =
+ !isApiKeySet || disablePrompts || isLoadingOrganization || isSupportChatClosed
const deleteMessageFromHere = useCallback(
(messageId: string) => {
@@ -548,6 +554,33 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
</AnimatePresence>
<div className="px-3 pb-3 z-20 relative">
+ {isSupportChat && !isSupportChatClosed && (
+ <div className="mb-3">
+ <div className="mb-3 border-t" />
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="tiny"
+ disabled={!activeChatId || !supportConversationId}
+ onClick={() =>
+ activeChatId && state.setSupportLifecycleStatus(activeChatId, 'escalated')
+ }
+ >
+ Escalate to human
+ </Button>
+ <Button
+ variant="outline"
+ size="tiny"
+ disabled={!activeChatId || !supportConversationId}
+ onClick={() =>
+ activeChatId && state.setSupportLifecycleStatus(activeChatId, 'user_resolved')
+ }
+ >
+ Resolve
+ </Button>
+ </div>
+ </div>
+ )}
{disablePrompts && (
<Admonition
showIcon={false}
@@ -581,10 +614,14 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
disabled={isChatInputDisabled}
placeholder={
hasMessages
- ? 'Ask a follow up question...'
+ ? isSupportChat
+ ? 'Share details so the assistant can help with your support request...'
+ : 'Ask a follow up question...'
: (snap.sqlSnippets ?? [])?.length > 0
? 'Ask a question or make a change...'
- : 'Chat to Postgres...'
+ : isSupportChat
+ ? 'Describe your support issue...'
+ : 'Chat to Postgres...'
}
value={value}
onValueChange={(e) => setValue(e.target.value)}
diff --git a/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx b/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
index 454b995427b..462b958782a 100644
--- a/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
@@ -20,7 +20,11 @@ import type { SubmittedSupportRequest } from '@/components/interfaces/Support/Su
import { NO_PROJECT_MARKER } from '@/components/interfaces/Support/SupportForm.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { useTrack } from '@/lib/telemetry/track'
-import { useAiAssistantStateSnapshot, type AiAssistantState } from '@/state/ai-assistant-state'
+import {
+ useAiAssistantState,
+ useAiAssistantStateSnapshot,
+ type AiAssistantState,
+} from '@/state/ai-assistant-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
type SupportAssistantPreviewChat = AiAssistantState['chatInstances'][string]
@@ -47,6 +51,7 @@ export function SupportAssistantSuccessCardContent({
}: SupportAssistantSuccessCardContentProps) {
const hasAssistantContext = hasProjectScopedAssistantContext(request.projectRef)
const aiAssistant = useAiAssistantStateSnapshot()
+ const aiAssistantState = useAiAssistantState()
const { openSidebar } = useSidebarManagerSnapshot()
const track = useTrack()
const createdChatIdRef = useRef<string | null>(null)
@@ -79,7 +84,38 @@ export function SupportAssistantSuccessCardContent({
)
if (chatId) {
- aiAssistant.selectChat(chatId)
+ // Tag the chat as a support chat on first engagement so its messages and
+ // lifecycle sync to Front. Gated on the click (rather than on chat creation)
+ // so chats the user never opens don't create Front conversations.
+ const chat = aiAssistantState.chats[chatId]
+ if (chat && !chat.supportMetadata) {
+ chat.supportMetadata = {
+ subject: request.subject,
+ category: request.category,
+ severity: request.severity,
+ organizationSlug: request.organizationSlug,
+ projectRef: request.projectRef,
+ library: request.library,
+ affectedServices: request.affectedServices,
+ allowSupportAccess: request.allowSupportAccess,
+ // Reuse the Front conversation created at submit so AI messages thread into it.
+ frontConversationId: request.frontConversationId,
+ threadRef: request.threadRef,
+ isSupportChat: true,
+ lifecycleStatus: 'bot_active',
+ lastSyncedMessageCount: 0,
+ isSyncing: false,
+ isLifecycleSyncing: false,
+ }
+
+ // Flush any messages produced before the user engaged (the initial prompt
+ // and any assistant reply). Subsequent turns sync via the onFinish hook.
+ void import('@/state/ai-chat-front-sync')
+ .then(({ syncSupportChatToFront }) => syncSupportChatToFront(chatId, aiAssistantState))
+ .catch(() => {})
+ }
+
+ aiAssistantState.selectChat(chatId)
}
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
}
diff --git a/apps/studio/data/feedback/ai-chat-front-sync.ts b/apps/studio/data/feedback/ai-chat-front-sync.ts
new file mode 100644
index 00000000000..c3275301419
--- /dev/null
+++ b/apps/studio/data/feedback/ai-chat-front-sync.ts
@@ -0,0 +1,71 @@
+import * as Sentry from '@sentry/nextjs'
+import type { components } from 'api-types'
+
+import { post } from '@/data/fetchers'
+
+export type AiSupportStatus = 'bot_active' | 'escalated' | 'user_resolved' | 'bot_resolved'
+
+export type SyncConversationMessagesVariables =
+ components['schemas']['SyncConversationMessagesBody']
+
+type SyncConversationMessagesResponse = components['schemas']['SyncConversationMessagesResponse']
+
+type EscalateConversationVariables = components['schemas']['EscalateConversationBody']
+
+type ResolveConversationVariables = components['schemas']['ResolveConversationBody']
+
+type UpdateConversationLifecycleResponse =
+ components['schemas']['UpdateConversationLifecycleResponse']
+
+/**
+ * Sync AI support chat messages to Front via the Platform API.
+ *
+ * These are fire-and-forget helpers: failures are reported to Sentry and return
+ * `null` so a Front outage never breaks the user's chat. The caller leaves its
+ * sync bookkeeping untouched on `null` and retries the same delta on the next
+ * turn (the server de-dupes by external_id).
+ */
+export async function syncConversationMessagesToFront(
+ variables: SyncConversationMessagesVariables
+): Promise<SyncConversationMessagesResponse | null> {
+ const { data, error } = await post('/platform/feedback/conversations/messages', {
+ body: variables,
+ })
+
+ if (error) {
+ Sentry.captureException(error)
+ return null
+ }
+
+ return data
+}
+
+export async function escalateConversationInFront(
+ variables: EscalateConversationVariables
+): Promise<UpdateConversationLifecycleResponse | null> {
+ const { data, error } = await post('/platform/feedback/conversations/escalation', {
+ body: variables,
+ })
+
+ if (error) {
+ Sentry.captureException(error)
+ return null
+ }
+
+ return data
+}
+
+export async function resolveConversationInFront(
+ variables: ResolveConversationVariables
+): Promise<UpdateConversationLifecycleResponse | null> {
+ const { data, error } = await post('/platform/feedback/conversations/resolve', {
+ body: variables,
+ })
+
+ if (error) {
+ Sentry.captureException(error)
+ return null
+ }
+
+ return data
+}
diff --git a/apps/studio/data/feedback/support-ticket-send.ts b/apps/studio/data/feedback/support-ticket-send.ts
index 37957dce243..941e0bebf0d 100644
--- a/apps/studio/data/feedback/support-ticket-send.ts
+++ b/apps/studio/data/feedback/support-ticket-send.ts
@@ -24,6 +24,9 @@ export type sendSupportTicketVariables = {
dashboardSentryIssueId?: string
dashboardLogs?: string
dashboardStudioVersion?: string
+ // Stable Front thread_ref so the AI support chat can later be appended to the
+ // same Front conversation that this submission creates.
+ threadRef?: string
}
const RATE_LIMIT_FALLBACK_SECONDS = 60
@@ -44,6 +47,7 @@ export async function sendSupportTicket({
dashboardSentryIssueId,
dashboardLogs,
dashboardStudioVersion,
+ threadRef,
}: sendSupportTicketVariables) {
const { data, error, response } = await post('/platform/feedback/send', {
body: {
@@ -64,6 +68,7 @@ export async function sendSupportTicket({
dashboardSentryIssueId,
dashboardLogs,
dashboardStudioVersion,
+ threadRef,
},
})
diff --git a/apps/studio/lib/ai/generate-assistant-response.ts b/apps/studio/lib/ai/generate-assistant-response.ts
index 93f32fb6bf8..9679be6fb9b 100644
--- a/apps/studio/lib/ai/generate-assistant-response.ts
+++ b/apps/studio/lib/ai/generate-assistant-response.ts
@@ -30,6 +30,7 @@ export async function generateAssistantResponse({
chatId,
chatName,
allowTracing,
+ supportMode,
userId,
orgId,
planId,
@@ -48,6 +49,7 @@ export async function generateAssistantResponse({
chatId?: string
chatName?: string
allowTracing?: boolean
+ supportMode?: boolean
userId?: string
orgId?: number
planId?: string
@@ -121,6 +123,9 @@ export async function generateAssistantResponse({
const assistantContent = hasProjectContext
? `The user's current project is ${projectRef || 'unknown'}. Their available schemas are: ${schemasString}. The current chat name is: ${chatName || 'unnamed'}.`
: undefined
+ const supportAssistantContent = supportMode
+ ? `This is an active support chat. Help the user while they wait for a human agent. Keep guidance practical and concise. If the user asks for a human, or if the issue cannot be safely resolved, call escalate_to_human with a short reason. Only call resolve_support_conversation after the user explicitly confirms the issue is resolved; otherwise keep helping.`
+ : undefined
const systemMessage: SystemModelMessage = {
role: 'system',
@@ -137,6 +142,14 @@ export async function generateAssistantResponse({
},
]
: []),
+ ...(supportAssistantContent
+ ? [
+ {
+ role: 'assistant' as const,
+ content: supportAssistantContent,
+ },
+ ]
+ : []),
...(await convertToModelMessages(messages)),
]
diff --git a/apps/studio/lib/ai/tool-filter.ts b/apps/studio/lib/ai/tool-filter.ts
index d5f0d1b58a5..66cf66c5b3e 100644
--- a/apps/studio/lib/ai/tool-filter.ts
+++ b/apps/studio/lib/ai/tool-filter.ts
@@ -32,6 +32,8 @@ export const toolSetValidationSchema = z.record(
'execute_sql',
'deploy_edge_function',
'rename_chat',
+ 'escalate_to_human',
+ 'resolve_support_conversation',
'list_policies',
// Fallback tools for self-hosted
@@ -70,6 +72,8 @@ export const TOOL_CATEGORY_MAP: Record<string, ToolCategory> = {
execute_sql: TOOL_CATEGORIES.UI,
deploy_edge_function: TOOL_CATEGORIES.UI,
rename_chat: TOOL_CATEGORIES.UI,
+ escalate_to_human: TOOL_CATEGORIES.UI,
+ resolve_support_conversation: TOOL_CATEGORIES.UI,
search_docs: TOOL_CATEGORIES.UI,
get_active_incidents: TOOL_CATEGORIES.UI,
load_knowledge: TOOL_CATEGORIES.UI,
diff --git a/apps/studio/lib/ai/tools/index.ts b/apps/studio/lib/ai/tools/index.ts
index 295921d1c70..5907292062f 100644
--- a/apps/studio/lib/ai/tools/index.ts
+++ b/apps/studio/lib/ai/tools/index.ts
@@ -7,6 +7,7 @@ import { getIncidentTools } from './incident-tools'
import { getMcpTools } from './mcp-tools'
import { getSchemaTools } from './schema-tools'
import { getStudioTools } from './studio-tools'
+import { getSupportLifecycleTools } from './support-tools'
import { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
export const getTools = async ({
@@ -16,6 +17,7 @@ export const getTools = async ({
aiOptInLevel,
accessToken,
baseUrl,
+ supportMode,
signal,
}: {
projectRef: string
@@ -24,6 +26,7 @@ export const getTools = async ({
aiOptInLevel: AiOptInLevel
accessToken?: string
baseUrl?: string
+ supportMode?: boolean
// Required: tools fetched from the remote MCP server hold an HTTP connection
// that is closed when this signal aborts (i.e. when the request ends).
signal: AbortSignal
@@ -73,7 +76,8 @@ export const getTools = async ({
}
// Filter all tools based on the (potentially modified) AI opt-in level
- const filteredTools: ToolSet = filterToolsByOptInLevel(tools, aiOptInLevel)
+ const toolsWithSupport = supportMode ? { ...tools, ...getSupportLifecycleTools() } : tools
+ const filteredTools: ToolSet = filterToolsByOptInLevel(toolsWithSupport, aiOptInLevel)
return filteredTools
}
diff --git a/apps/studio/lib/ai/tools/support-tools.ts b/apps/studio/lib/ai/tools/support-tools.ts
new file mode 100644
index 00000000000..352875c369a
--- /dev/null
+++ b/apps/studio/lib/ai/tools/support-tools.ts
@@ -0,0 +1,33 @@
+import { tool } from 'ai'
+import { z } from 'zod'
+
+export const getSupportLifecycleTools = () => ({
+ escalate_to_human: tool({
+ description:
+ 'Escalate this support conversation to a human support agent when the assistant cannot resolve the issue.',
+ inputSchema: z.object({
+ reason: z
+ .string()
+ .trim()
+ .min(1, 'Escalation reason is required')
+ .describe('A short reason that explains why this support chat should be escalated.'),
+ }),
+ execute: async () => {
+ return { status: 'Escalation request sent to client.' }
+ },
+ }),
+ resolve_support_conversation: tool({
+ description:
+ 'Mark this support conversation as resolved when the issue appears solved from the user perspective.',
+ inputSchema: z.object({
+ summary: z
+ .string()
+ .trim()
+ .min(1, 'Resolution summary is required')
+ .describe('A concise summary of the fix or guidance that resolved the support request.'),
+ }),
+ execute: async () => {
+ return { status: 'Resolve request sent to client.' }
+ },
+ }),
+})
diff --git a/apps/studio/lib/api/generate-v4.test.ts b/apps/studio/lib/api/generate-v4.test.ts
index 5110d04fe8a..e7326ca57d0 100644
--- a/apps/studio/lib/api/generate-v4.test.ts
+++ b/apps/studio/lib/api/generate-v4.test.ts
@@ -3,6 +3,7 @@ import { UIMessage } from 'ai'
import { expect, test, vi } from 'vitest'
import generateV4 from '../../pages/api/ai/sql/generate-v4'
+import { getTools } from '@/lib/ai/tools'
import { sanitizeMessagePart } from '@/lib/ai/tools/tool-sanitizer'
vi.mock('@/lib/ai/tools/tool-sanitizer', () => ({
@@ -34,6 +35,7 @@ test('generateV4 calls the tool sanitizer', async () => {
projectRef: 'test-project',
connectionString: 'test-connection',
orgSlug: 'test-org',
+ supportMode: true,
},
on: vi.fn(),
}
@@ -84,6 +86,11 @@ test('generateV4 calls the tool sanitizer', async () => {
await generateV4(mockReq as any, mockRes as any)
expect(sanitizeMessagePart).toHaveBeenCalled()
+ expect(getTools).toHaveBeenCalledWith(
+ expect.objectContaining({
+ supportMode: true,
+ })
+ )
// The response 'close' event must be wired up so the remote MCP connection
// opened in getTools is torn down when the stream finishes or the client drops
expect(mockRes.on).toHaveBeenCalledWith('close', expect.any(Function))
diff --git a/apps/studio/pages/api/ai/sql/generate-v4.ts b/apps/studio/pages/api/ai/sql/generate-v4.ts
index 1bbc78aa29b..aa48b2cea79 100644
--- a/apps/studio/pages/api/ai/sql/generate-v4.ts
+++ b/apps/studio/pages/api/ai/sql/generate-v4.ts
@@ -62,6 +62,7 @@ const requestBodySchema = z.object({
table: z.string().optional(),
chatId: z.string().optional(),
chatName: z.string().optional(),
+ supportMode: z.boolean().optional(),
orgSlug: z.string().optional(),
model: z.string().optional(),
})
@@ -91,6 +92,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
chatId,
chatName,
model: rawRequestedModel,
+ supportMode,
} = data
const requestedModel: AssistantModelId | undefined =
@@ -176,6 +178,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
aiOptInLevel,
accessToken,
baseUrl: getURL(),
+ supportMode,
signal: abortController.signal,
})
@@ -217,6 +220,7 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: Jw
projectIsSensitive,
projectRegion,
}),
+ supportMode,
userId,
orgId,
planId,
diff --git a/apps/studio/state/ai-assistant-state.tsx b/apps/studio/state/ai-assistant-state.tsx
index 7c31bfef138..f7e59494d94 100644
--- a/apps/studio/state/ai-assistant-state.tsx
+++ b/apps/studio/state/ai-assistant-state.tsx
@@ -7,6 +7,7 @@ import { createContext, PropsWithChildren, useContext, useEffect, useState } fro
import { v4 as uuidv4 } from 'uuid'
import { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio'
+import type { AiSupportStatus } from '@/data/feedback/ai-chat-front-sync'
import { constructHeaders } from '@/data/fetchers'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { prepareMessagesForAPI } from '@/lib/ai/message-utils'
@@ -25,12 +26,41 @@ export type SqlSnippet = string | { label: string; content: string }
export type AssistantModel = AssistantModelId
+export type SupportChatMetadata = {
+ subject: string
+ category: string
+ severity: string
+ organizationSlug?: string
+ projectRef?: string
+ library?: string
+ affectedServices?: string
+ allowSupportAccess: boolean
+ browserInformation?: string
+ frontConversationId?: string
+ // Front thread_ref shared with the submit-time conversation. Sent as the sync
+ // API `chatId` so AI messages thread into that same Front conversation.
+ threadRef?: string
+ isSupportChat: true
+ lifecycleStatus: AiSupportStatus
+ // A lifecycle transition requested before the Front conversation id existed
+ // (e.g. the assistant resolved the chat before the first message sync
+ // returned an id). Flushed by syncSupportChatToFront once the id is assigned.
+ pendingLifecycleStatus?: AiSupportStatus
+ lifecycleClosedAt?: string
+ lastSyncedMessageCount: number
+ // Guards message syncs; lifecycle syncs use `isLifecycleSyncing` so the two
+ // never block each other.
+ isSyncing: boolean
+ isLifecycleSyncing: boolean
+}
+
type ChatSession = {
id: string
name: string
messages: AssistantMessageType[]
createdAt: Date
updatedAt: Date
+ supportMetadata?: SupportChatMetadata
}
export type AiAssistantContext = {
@@ -259,6 +289,7 @@ function createChatInstance(
connectionString: state.context.connectionString,
chatId: options.id,
chatName: chat?.name,
+ supportMode: chat?.supportMetadata?.isSupportChat ?? false,
orgSlug: state.context.orgSlug,
context: state.context,
model: state.model,
@@ -273,6 +304,16 @@ function createChatInstance(
return
}
+ if (toolCall.toolName === 'escalate_to_human') {
+ state.setSupportLifecycleStatus(options.id, 'escalated')
+ return
+ }
+
+ if (toolCall.toolName === 'resolve_support_conversation') {
+ state.setSupportLifecycleStatus(options.id, 'bot_resolved')
+ return
+ }
+
if (toolCall.toolName === 'rename_chat') {
const { newName } = toolCall.input as { newName: string }
@@ -301,6 +342,13 @@ function createChatInstance(
}
delete state.pendingSpanIds[options.id]
}
+
+ // Sync support chat messages to Front (fire-and-forget, dynamic import to avoid SSR issues)
+ if (chat?.supportMetadata) {
+ import('@/state/ai-chat-front-sync')
+ .then(({ syncSupportChatToFront }) => syncSupportChatToFront(options.id, state))
+ .catch(() => {})
+ }
}
},
})
@@ -374,6 +422,28 @@ export const createAiAssistantState = (): AiAssistantState => {
return chatId
},
+ setSupportLifecycleStatus: (chatId: string, status: AiSupportStatus) => {
+ const chat = state.chats[chatId]
+ if (!chat?.supportMetadata) return
+
+ chat.supportMetadata.lifecycleStatus = status
+ if (status !== 'bot_active') {
+ chat.supportMetadata.lifecycleClosedAt = new Date().toISOString()
+ }
+
+ // No Front conversation yet (the initial message sync hasn't returned an
+ // id). Queue the transition so syncSupportChatToFront can flush it once the
+ // id is assigned, rather than silently dropping it.
+ if (!chat.supportMetadata.frontConversationId) {
+ chat.supportMetadata.pendingLifecycleStatus = status
+ return
+ }
+
+ import('@/state/ai-chat-front-sync').then(({ syncSupportLifecycleToFront }) => {
+ syncSupportLifecycleToFront(chatId, state, status).catch(() => {})
+ })
+ },
+
selectChat: (id: string) => {
if (id !== state.activeChatId) {
state.activeChatId = id
@@ -493,6 +563,20 @@ export const createAiAssistantState = (): AiAssistantState => {
? storedModel
: INITIAL_AI_ASSISTANT.model
+ // Reset sync guards on any support chats (can't be mid-sync after reload)
+ Object.values(state.chats).forEach((chat) => {
+ if (chat.supportMetadata) {
+ if (!chat.supportMetadata.isSupportChat) {
+ chat.supportMetadata.isSupportChat = true
+ }
+ if (!chat.supportMetadata.lifecycleStatus) {
+ chat.supportMetadata.lifecycleStatus = 'bot_active'
+ }
+ chat.supportMetadata.isSyncing = false
+ chat.supportMetadata.isLifecycleSyncing = false
+ }
+ })
+
// Ensure an active chat exists after loading
if (!state.activeChat) {
const chatIds = Object.keys(state.chats)
@@ -545,6 +629,7 @@ export type AiAssistantState = AiAssistantData & {
Pick<AiAssistantData, 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>
>
) => string
+ setSupportLifecycleStatus: (chatId: string, status: AiSupportStatus) => void
selectChat: (id: string) => void
deleteChat: (id: string) => void
renameChat: (id: string, name: string) => void
diff --git a/apps/studio/state/ai-chat-front-sync.ts b/apps/studio/state/ai-chat-front-sync.ts
new file mode 100644
index 00000000000..b2c8575caee
--- /dev/null
+++ b/apps/studio/state/ai-chat-front-sync.ts
@@ -0,0 +1,176 @@
+import { parseSupportAssistantPrompt } from '@/components/interfaces/Support/SupportAssistant.utils'
+import {
+ escalateConversationInFront,
+ resolveConversationInFront,
+ syncConversationMessagesToFront,
+} from '@/data/feedback/ai-chat-front-sync'
+import type { AiSupportStatus } from '@/data/feedback/ai-chat-front-sync'
+import type { AiAssistantState } from '@/state/ai-assistant-state'
+
+/**
+ * Extracts plain text content from AI SDK message parts.
+ * Messages use a parts array where text content is in `part.type === 'text'`.
+ */
+function extractTextFromMessage(message: {
+ parts?: Array<{ type: string; text?: string }>
+}): string {
+ if (!message.parts) return ''
+ return message.parts
+ .filter((part) => part.type === 'text' && part.text)
+ .map((part) => part.text ?? '')
+ .join('\n')
+}
+
+type SyncableChatMessage = {
+ id: string
+ role: string
+ content?: string
+ parts?: Array<{ type: string; text?: string }>
+}
+
+/**
+ * Syncs unsynced support chat messages to Front.
+ *
+ * Called from the AI assistant state `onFinish` callback (fire-and-forget).
+ * Uses `isSyncing` flag to prevent concurrent syncs for the same chat.
+ * Uses `lastSyncedMessageCount` to only send new (delta) messages.
+ */
+export async function syncSupportChatToFront(
+ chatId: string,
+ state: AiAssistantState
+): Promise<void> {
+ const chat = state.chats[chatId]
+ if (!chat?.supportMetadata) return
+
+ const { supportMetadata } = chat
+
+ // Prevent concurrent syncs
+ if (supportMetadata.isSyncing) return
+ supportMetadata.isSyncing = true
+
+ try {
+ const allMessages = chat.messages
+ // Snapshot the boundary now: `chat.messages` may grow while the sync is in
+ // flight (streaming finishing, a fast follow-up). Advancing the counter to the
+ // post-await length would skip those messages and drop them from Front. On
+ // failure we leave the counter untouched and retry the same delta — the server
+ // de-dupes by external_id (chatId:msg.id), so retries don't duplicate.
+ const syncedUpTo = allMessages.length
+ const unsyncedMessages = allMessages.slice(supportMetadata.lastSyncedMessageCount)
+
+ if (unsyncedMessages.length === 0) return
+
+ const isInitial = supportMetadata.lastSyncedMessageCount === 0
+
+ // Convert AI SDK messages to plain text format for the sync API
+ const messagesToSync = (unsyncedMessages as SyncableChatMessage[])
+ .filter((msg) => msg.role === 'user' || msg.role === 'assistant')
+ .map((msg) => ({
+ id: msg.id,
+ role: msg.role as 'user' | 'assistant',
+ content: extractTextFromMessage(msg) || msg.content || '',
+ }))
+ // The seeded first message is a full `<support>...</support>` block. On the
+ // initial sync we only want the user's actual message (the `<message>` value)
+ // in Front, not the metadata block. Once the conversation already exists the
+ // metadata was already sent, so drop the block entirely (empty content is
+ // filtered out below).
+ .map((msg) => {
+ const parsed = parseSupportAssistantPrompt(msg.content)
+ if (!parsed) return msg
+ // When frontConversationId exists the user message was already sent via /feedback/send
+ return {
+ ...msg,
+ content: isInitial && !supportMetadata.frontConversationId ? (parsed.message ?? '') : '',
+ }
+ })
+ .filter((msg) => msg.content.length > 0)
+
+ if (messagesToSync.length === 0) return
+
+ const result = await syncConversationMessagesToFront({
+ // Thread on the shared Front thread_ref (from submit) so messages append to the
+ // pre-created conversation. Falls back to the studio chat id for chats that
+ // weren't created via the support form.
+ chatId: supportMetadata.threadRef ?? chatId,
+ subject: supportMetadata.subject,
+ messages: messagesToSync,
+ isInitial,
+ conversationId: supportMetadata.frontConversationId,
+ ...(isInitial && {
+ organizationSlug: supportMetadata.organizationSlug,
+ projectRef: supportMetadata.projectRef,
+ category: supportMetadata.category,
+ severity: supportMetadata.severity,
+ affectedServices: supportMetadata.affectedServices,
+ library: supportMetadata.library,
+ allowSupportAccess: supportMetadata.allowSupportAccess,
+ browserInformation: supportMetadata.browserInformation,
+ }),
+ })
+
+ if (result) {
+ // Update sync tracking
+ supportMetadata.lastSyncedMessageCount = syncedUpTo
+
+ if (result.conversationId && !supportMetadata.frontConversationId) {
+ supportMetadata.frontConversationId = result.conversationId
+ }
+
+ // Flush a lifecycle transition that was requested before the Front
+ // conversation id existed (e.g. the assistant resolved/escalated the chat
+ // before this first message sync returned an id). syncSupportLifecycleToFront
+ // uses its own guard, so this won't contend with the message-sync flag.
+ if (supportMetadata.frontConversationId && supportMetadata.pendingLifecycleStatus) {
+ const pending = supportMetadata.pendingLifecycleStatus
+ supportMetadata.pendingLifecycleStatus = undefined
+ void syncSupportLifecycleToFront(chatId, state, pending).catch(() => {})
+ }
+ }
+ } finally {
+ supportMetadata.isSyncing = false
+ }
+}
+
+export async function syncSupportLifecycleToFront(
+ chatId: string,
+ state: AiAssistantState,
+ aiSupportStatus: AiSupportStatus
+): Promise<void> {
+ const chat = state.chats[chatId]
+ if (!chat?.supportMetadata) return
+
+ const { supportMetadata } = chat
+ if (!supportMetadata.frontConversationId) return
+ // Use a dedicated guard so an in-flight message sync (`isSyncing`) can never
+ // short-circuit a lifecycle transition. A dropped lifecycle call is never
+ // retried, unlike message syncs, so the two must not share a flag.
+ if (supportMetadata.isLifecycleSyncing) return
+
+ supportMetadata.isLifecycleSyncing = true
+
+ try {
+ let result = null
+
+ const threadRef = supportMetadata.threadRef ?? chatId
+
+ if (aiSupportStatus === 'escalated') {
+ result = await escalateConversationInFront({
+ chatId: threadRef,
+ conversationId: supportMetadata.frontConversationId,
+ })
+ } else if (aiSupportStatus === 'user_resolved' || aiSupportStatus === 'bot_resolved') {
+ result = await resolveConversationInFront({
+ chatId: threadRef,
+ conversationId: supportMetadata.frontConversationId,
+ aiSupportStatus,
+ })
+ }
+
+ if (result?.aiSupportStatus) {
+ supportMetadata.lifecycleStatus = result.aiSupportStatus
+ }
+ } finally {
+ supportMetadata.isLifecycleSyncing = false
+ }
+}