mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 17:35:10 +03:00
# Sync AI assistant conversation to Front ## What & why When a user submits a support ticket, an AI assistant chat opens so they get help immediately while waiting for a human agent. This PR mirrors every turn of that chat into the Front conversation the support form already created, so the support team sees the full context and Front automations (routing, emails, CSAT) can act on it. Studio holds no Front credentials — it calls the platform endpoints (see the platform PR) to do the syncing. The assistant card is gated behind the `supportAssistantFollowUp` ConfigCat flag. ## How it works 1. **Submit** — `SupportFormV3` generates a stable `threadRef` (via the `uuid` package — `crypto.randomUUID()` is `undefined` in insecure contexts like non-localhost HTTP and would throw, silently aborting the submit) and sends it on `/platform/feedback/send`. The response returns the Front `conversationId`. Both are stored on `SubmittedSupportRequest`. 2. **Open chat** — `SupportAssistantSuccessCardContent` opens a chat seeded with `supportMetadata` (`threadRef`, `frontConversationId`, subject, category, severity, …). The first message is a `<support>…</support>` XML block. 3. **First user message** — the chat is tagged `isSupportChat = true`; the `onFinish` hook fires `syncSupportChatToFront`. 4. **Subsequent turns** — each `onFinish` slices the unsynced delta, strips the XML metadata block from the seed message, and posts to the platform messages endpoint. 5. **Escalation / resolve** — the `escalate_to_human` / `resolve_support_conversation` tools (and manual **Escalate**/**Resolve** buttons in the assistant input) flip lifecycle status via `setSupportLifecycleStatus` → `syncSupportLifecycleToFront`, which calls the escalation/resolve endpoints. Front rules act on `ai_support_status`. The assistant only resolves after the user explicitly confirms the issue is fixed. ## Key design decisions - **`threadRef` as the shared key** — one UUID travels as `threadRef` on submit and as `chatId` on every sync, so all messages thread into a single Front conversation. - **`conversationId` from the form response** — passed to all sync/lifecycle calls so the platform skips lazy derivation and PATCHes custom fields directly. - **Delta-only sync** — `lastSyncedMessageCount` tracks what's been sent; the boundary is snapshotted before the async call to avoid skipping messages that arrive mid-flight. - **Server-side de-dup** — stable `external_id` (`chatId:msg.id`) means retries don't duplicate in Front. - **Fire-and-forget** — sync failures log to Sentry, never break the chat; `isSyncing` resets on rehydration so the next `onFinish` retries the same delta. Message and lifecycle syncs use separate guards (`isSyncing` / `isLifecycleSyncing`) so an in-flight message sync can't drop an escalate/resolve. - **Lifecycle queued until the conversation exists** — if a lifecycle transition is requested before the initial message sync has returned a `frontConversationId`, it's stored as `pendingLifecycleStatus` and flushed once the id is assigned, rather than dropped. - **Tools return immediately** — the lifecycle tools return a stub to the AI SDK; the real Front call happens in `onFinish`, keeping async I/O out of the tool execute path. - **XML seed stripped before sync** — only the user's actual `<message>` is sent to Front (or dropped entirely if the form already created the conversation). ## Changes | Area | File(s) | | --- | --- | | Support form state | `SupportForm.state.ts` — `threadRef` / `frontConversationId` on `SubmittedSupportRequest` | | Support form submit | `support-ticket-send.ts` — sends `threadRef`, reads `conversationId` | | Support form UI | `SupportFormV3.tsx` — generates `threadRef`, stores `conversationId` | | AI assistant state | `ai-assistant-state.tsx` — `SupportChatMetadata`, `setSupportLifecycleStatus`, `onFinish` wiring, tool handling | | Message sync | `state/ai-chat-front-sync.ts` — delta tracking, message filtering, initial vs. incremental | | API data layer | `data/feedback/ai-chat-front-sync.ts` — typed platform-client wrappers for the three conversation endpoints | | Support tools | `lib/ai/tools/support-tools.ts` — `escalate_to_human`, `resolve_support_conversation` | | Tool integration | `lib/ai/tool-filter.ts`, `tools/index.ts`, `generate-assistant-response.ts` | | Success card | `SupportAssistantSuccessCardContent.tsx` — tags chat on first engagement | | Assistant panel UI | `AIAssistant.tsx` — Escalate/Resolve buttons, disabled input on closed chats, support placeholders | <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit - **New Features** - Support chats now include “Escalate to human” and “Resolve” actions. - Support submissions can be associated with a stable Front thread via a generated `threadRef`, preserving linkage across follow-ups. - AI assistant responses and input hints adapt when support mode is active. - **Bug Fixes** - Improved support chat state management and lifecycle handling to keep conversation metadata and message history synchronized more reliably with Front. - **Chores** - Added/updated coverage to reflect the new support-chat state and syncing behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
177 lines
6.5 KiB
TypeScript
177 lines
6.5 KiB
TypeScript
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
|
|
}
|
|
}
|