mirror of
https://github.com/supabase/supabase.git
synced 2026-09-07 02:20:52 +08: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>
117 lines
3.3 KiB
TypeScript
117 lines
3.3 KiB
TypeScript
import type { ExtendedSupportCategories } from './Support.constants'
|
|
import type { SupportFormValues } from './SupportForm.schema'
|
|
import { neverGuard } from '@/lib/helpers'
|
|
|
|
export type SubmittedSupportRequest = Pick<
|
|
SupportFormValues,
|
|
'category' | 'severity' | 'subject' | 'message' | 'affectedServices' | 'allowSupportAccess'
|
|
> & {
|
|
organizationSlug: string | undefined
|
|
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 =
|
|
| {
|
|
type: 'initializing'
|
|
}
|
|
| {
|
|
type: 'editing'
|
|
}
|
|
| {
|
|
type: 'submitting'
|
|
}
|
|
| {
|
|
type: 'success'
|
|
sentProjectRef: string | undefined
|
|
sentOrgSlug: string | undefined
|
|
sentCategory: ExtendedSupportCategories
|
|
submittedRequest: SubmittedSupportRequest
|
|
}
|
|
| {
|
|
type: 'error'
|
|
message: string
|
|
code?: number
|
|
}
|
|
|
|
export type SupportFormActions =
|
|
| { type: 'INITIALIZE'; debugSource?: string }
|
|
| { type: 'SUBMIT'; debugSource?: string }
|
|
| {
|
|
type: 'SUCCESS'
|
|
sentProjectRef: string | undefined
|
|
sentOrgSlug: string | undefined
|
|
sentCategory: ExtendedSupportCategories
|
|
submittedRequest: SubmittedSupportRequest
|
|
debugSource?: string
|
|
}
|
|
| { type: 'ERROR'; message: string; code?: number; debugSource?: string }
|
|
| { type: 'RETURN_TO_EDITING'; debugSource?: string }
|
|
|
|
export function createInitialSupportFormState(): SupportFormState {
|
|
return {
|
|
type: 'initializing',
|
|
}
|
|
}
|
|
|
|
export function supportFormReducer(
|
|
state: SupportFormState,
|
|
action: SupportFormActions
|
|
): SupportFormState {
|
|
switch (state.type) {
|
|
case 'initializing':
|
|
if (action.type === 'INITIALIZE') {
|
|
return { type: 'editing' }
|
|
}
|
|
console.warn(
|
|
`[SupportForm > supportFormReducer] ${action.type} action not allowed in 'initializing' state`
|
|
)
|
|
return state
|
|
case 'editing':
|
|
if (action.type === 'SUBMIT') {
|
|
return { type: 'submitting' }
|
|
}
|
|
console.warn(
|
|
`[SupportForm > supportFromReducer] ${action.type} action not allowed in 'filling_out' state`
|
|
)
|
|
return state
|
|
case 'submitting':
|
|
if (action.type === 'SUCCESS') {
|
|
return {
|
|
type: 'success',
|
|
sentProjectRef: action.sentProjectRef,
|
|
sentOrgSlug: action.sentOrgSlug,
|
|
sentCategory: action.sentCategory,
|
|
submittedRequest: action.submittedRequest,
|
|
}
|
|
}
|
|
if (action.type === 'ERROR') {
|
|
return {
|
|
type: 'error',
|
|
message: action.message,
|
|
code: action.code,
|
|
}
|
|
}
|
|
console.warn(
|
|
`[SupportForm > supportFormReducer] ${action.type} action not allowed in 'submitting' state`
|
|
)
|
|
return state
|
|
case 'success':
|
|
console.warn(`[SupportForm > supportFormReducer] ${action.type} allowed in 'success' state`)
|
|
return state
|
|
case 'error':
|
|
if (action.type === 'RETURN_TO_EDITING') {
|
|
return { type: 'editing' }
|
|
}
|
|
console.warn(`[SupportForm > supportFormReducer] ${action.type} allowed in 'success' state`)
|
|
return state
|
|
default:
|
|
return neverGuard(state)
|
|
}
|
|
}
|