Files
supabase/apps/studio/components/ui/AIAssistantPanel/SupportAssistantSuccessCardContent.tsx
Carel de Waal 0acc0eb8b3 feat: Support Form - Sync AI assistant conversation to Front (#46778)
# 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>
2026-07-08 12:41:53 +02:00

244 lines
8.0 KiB
TypeScript

import type { UIMessage as MessageType } from '@ai-sdk/react'
import { ArrowUpRight } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import type { JSX } from 'react'
import type { StreamdownProps } from 'streamdown'
import {
AiIconAnimation,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
cn,
Skeleton,
} from 'ui'
import { buildSupportAssistantPrompt } from '@/components/interfaces/Support/SupportAssistant.utils'
import type { SubmittedSupportRequest } from '@/components/interfaces/Support/SupportForm.state'
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 {
useAiAssistantState,
useAiAssistantStateSnapshot,
type AiAssistantState,
} from '@/state/ai-assistant-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
type SupportAssistantPreviewChat = AiAssistantState['chatInstances'][string]
const EMPTY_MESSAGES: MessageType[] = []
const Streamdown = dynamic<StreamdownProps>(
() => import('streamdown').then((mod) => mod.Streamdown),
{ ssr: false }
)
interface SupportAssistantSuccessCardContentProps {
request: SubmittedSupportRequest
className?: string
}
function hasProjectScopedAssistantContext(projectRef: string | undefined) {
return projectRef !== undefined && projectRef !== NO_PROJECT_MARKER
}
export function SupportAssistantSuccessCardContent({
request,
className,
}: SupportAssistantSuccessCardContentProps) {
const hasAssistantContext = hasProjectScopedAssistantContext(request.projectRef)
const aiAssistant = useAiAssistantStateSnapshot()
const aiAssistantState = useAiAssistantState()
const { openSidebar } = useSidebarManagerSnapshot()
const track = useTrack()
const createdChatIdRef = useRef<string | null>(null)
const [chatId, setChatId] = useState<string>()
const chat = chatId ? aiAssistant.chatInstances[chatId] : undefined
const assistantPrompt = useMemo(() => buildSupportAssistantPrompt(request), [request])
useEffect(() => {
if (!hasAssistantContext) return
if (createdChatIdRef.current) return
const newChatId = aiAssistant.newChat({
name: 'Support request',
initialMessage: assistantPrompt,
})
createdChatIdRef.current = newChatId
setChatId(newChatId)
}, [aiAssistant, assistantPrompt, hasAssistantContext])
const handleOpenAssistant = () => {
track(
'support_assistant_follow_up_card_clicked',
{ ticketCategory: request.category },
{
project: request.projectRef,
organization: request.organizationSlug,
}
)
if (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)
}
if (!hasAssistantContext) return null
return (
<Card
role="button"
tabIndex={0}
aria-label="Open assistant response"
onClick={handleOpenAssistant}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
handleOpenAssistant()
}
}}
className={cn(
'group cursor-pointer bg-muted/50 transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand',
className
)}
>
<CardHeader className="flex-row items-center justify-between gap-4 space-y-0">
<div className="flex min-w-0 items-center gap-3">
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background">
<AiIconAnimation size={14} />
</div>
<div className="min-w-0 space-y-1">
<CardTitle>While you wait</CardTitle>
<CardDescription>Assistant may be able to help</CardDescription>
</div>
</div>
<ArrowUpRight
size={14}
strokeWidth={1.5}
className="shrink-0 text-foreground-lighter transition-colors group-hover:text-foreground"
aria-hidden
/>
</CardHeader>
{chat ? (
<SupportAssistantResponsePreview chat={chat as SupportAssistantPreviewChat} />
) : (
<CardContent>
<SupportAssistantResponseLoadingSkeleton />
</CardContent>
)}
</Card>
)
}
function useChatMessages(chat: SupportAssistantPreviewChat | undefined) {
const subscribe = useCallback(
(onStoreChange: () => void) => {
return chat?.['~registerMessagesCallback']?.(onStoreChange) ?? (() => {})
},
[chat]
)
const getSnapshot = useCallback(() => chat?.messages ?? EMPTY_MESSAGES, [chat])
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
}
function getAssistantMessageText(message: MessageType) {
return (
message.parts
?.filter((part) => part.type === 'text')
.map((part) => part.text)
.join('') ?? ''
)
}
function SupportAssistantResponsePreview({ chat }: { chat: SupportAssistantPreviewChat }) {
const messages = useChatMessages(chat)
const latestAssistantMessage = [...messages]
.reverse()
.find((message) => message.role === 'assistant')
if (!latestAssistantMessage) {
return (
<CardContent>
<SupportAssistantResponseLoadingSkeleton />
</CardContent>
)
}
const previewText = getAssistantMessageText(latestAssistantMessage)
return (
<CardContent className="relative max-h-48 overflow-hidden">
<SupportAssistantPreviewMarkdown>{previewText}</SupportAssistantPreviewMarkdown>
</CardContent>
)
}
function SupportAssistantPreviewMarkdown({ children }: { children: string }) {
return (
<Streamdown
className="prose prose-sm dark:prose-dark max-w-none space-y-3 text-sm text-foreground-light prose-p:my-0 prose-strong:font-medium prose-strong:text-foreground prose-code:text-xs prose-li:my-0 prose-ul:my-0 prose-ol:my-0"
components={supportAssistantPreviewMarkdownComponents}
>
{children}
</Streamdown>
)
}
function SupportAssistantPreviewImage({ src }: JSX.IntrinsicElements['img']) {
return <span className="font-mono text-foreground-lighter">[Image: {src?.toString()}]</span>
}
const supportAssistantPreviewMarkdownComponents: StreamdownProps['components'] = {
img: SupportAssistantPreviewImage,
}
function SupportAssistantResponseLoadingSkeleton() {
return (
<div className="space-y-2">
<Skeleton className="h-4 w-[82%]" />
<Skeleton className="h-4 w-[92%]" />
<Skeleton className="h-4 w-[68%]" />
</div>
)
}