🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(support): Send acknowledgement email to user on thread create (#8950)
Michael Fröhlich53b44454f63e
diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsxindex 0cc98f2b6f..829165e252 100644--- a/web/src/features/support-chat/SupportFormSection.tsx+++ b/web/src/features/support-chat/SupportFormSection.tsx@@ -127,7 +127,7 @@ export function SupportFormSection({const parsed: SupportFormValues = SupportFormSchema.parse(values);const msgLen = (parsed.message ?? "").trim().length;- if (msgLen < 20 && !warnedShortOnce) {+ if (msgLen < 50 && !warnedShortOnce) {setWarnedShortOnce(true);return;}@@ -210,7 +210,7 @@ export function SupportFormSection({};const messageIsShortAfterWarning =- warnedShortOnce && (form.getValues("message") ?? "").trim().length < 20;+ warnedShortOnce && (form.getValues("message") ?? "").trim().length < 50;// --- Compact attachment row helpersconst totalMB = (totalUploadBytes / (1024 * 1024)).toFixed(2);@@ -385,37 +385,6 @@ export function SupportFormSection({: "Please explain as fully as possible what you're aiming to do, and what you'd like help with."}/>- <div className="absolute inset-x-2 bottom-2 pr-1">- <Dropzone- className="border-none p-0 text-left"- maxFiles={5}- maxSize={1024 * 1024 * 10}- onDrop={(accepted) => setFiles(accepted)}- onError={console.error}- src={files}- >- {/* Small, single-line trigger */}- <DropzoneEmptyState>- <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">- <Paperclip className="h-4 w-4" />- <span className="truncate">- {hasFiles- ? `${files!.length} file${files!.length > 1 ? "s" : ""} • ${totalMB} MB`- : "Attach files"}- </span>- </div>- </DropzoneEmptyState>- {/* Keep content area minimal; we still allow preview slot if needed */}- <DropzoneContent>- <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">- <Paperclip className="h-4 w-4" />- <span className="truncate">- {hasFiles ? "Add more" : "Attach files"}- </span>- </div>- </DropzoneContent>- </Dropzone>- </div></div></FormControl>@@ -432,38 +401,66 @@ export function SupportFormSection({)}<FormMessage />++ <Dropzone+ className="mt-1 border-none p-0 text-left"+ maxFiles={5}+ maxSize={1024 * 1024 * 10}+ onDrop={(accepted) => setFiles(accepted)}+ onError={console.error}+ src={files}+ >+ {/* Small, single-line trigger */}+ <DropzoneEmptyState>+ <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">+ <Paperclip className="h-4 w-4" />+ <span className="truncate">+ {hasFiles+ ? `${files!.length} file${files!.length > 1 ? "s" : ""} • ${totalMB} MB`+ : "Attach files"}+ </span>+ </div>+ </DropzoneEmptyState>+ {/* Keep content area minimal; we still allow preview slot if needed */}+ <DropzoneContent>+ <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">+ <Paperclip className="h-4 w-4" />+ <span className="truncate">Attach files</span>+ </div>+ </DropzoneContent>+ </Dropzone>++ {files && files.length > 0 && (+ <div className="p-0 text-left text-sm font-medium">+ <div className="mb-2 text-xs font-medium text-muted-foreground">+ Attached files+ </div>+ {files?.map((file) => (+ <div+ key={file.name}+ className="flex flex-row items-center justify-start gap-2 text-xs"+ >+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ onClick={() =>+ setFiles(files.filter((f) => f.name !== file.name))+ }+ className="p-0"+ >+ <span className="sr-only">Remove file</span>+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ {file.name}+ </div>+ ))}+ </div>+ )}</FormItem>)}/>- {files && files.length > 0 && (- <div className="p-0 text-left text-sm font-medium">- <div className="mb-2 text-xs font-medium text-muted-foreground">- Attached files- </div>- {files?.map((file) => (- <div- key={file.name}- className="flex flex-row items-center justify-start gap-2 text-xs"- >- <Button- type="button"- variant="ghost"- size="icon-xs"- onClick={() =>- setFiles(files.filter((f) => f.name !== file.name))- }- className="p-0"- >- <span className="sr-only">Remove file</span>- <Trash2 className="h-3.5 w-3.5" />- </Button>- {file.name}- </div>- ))}- </div>- )}-{/* Actions */}<div className="flex flex-row gap-2"><Button@@ -496,6 +493,13 @@ export function SupportFormSection({)}</Button></div>++ {isSubmittingLocal && (+ <div className="text-xs text-muted-foreground">+ This can take a few seconds — hang tight while we submit your+ request.+ </div>+ )}</form></Form></div>diff --git a/web/src/features/support-chat/plain/plainClient.ts b/web/src/features/support-chat/plain/plainClient.tsindex cb8a3a6e7e..11fbb8aa70 100644--- a/web/src/features/support-chat/plain/plainClient.ts+++ b/web/src/features/support-chat/plain/plainClient.ts@@ -137,7 +137,7 @@ export async function createAttachmentUploadUrls(customerId,fileName: f.fileName,fileSizeBytes: f.fileSizeBytes,- attachmentType: AttachmentType.CustomTimelineEntry,+ attachmentType: AttachmentType.Email,});const data = unwrap("createAttachmentUploadUrl", r);@@ -476,3 +476,155 @@ export async function createThreadEvent(logger.error("createThreadEvent failed", describeSdkError(res.error));}}++// ===== Notifications (best-effort / non-throwing) =====+export async function replyToThread(+ ctx: PlainCtx,+ input: {+ threadId: string;+ userEmail: string;+ originalMessage: string;+ attachmentIds?: string[];+ impersonate?: boolean;+ },+) {+ const { client } = ctx;+ const res = await client.replyToThread({+ threadId: input.threadId,+ textContent: input.originalMessage,+ markdownContent: input.originalMessage,+ attachmentIds:+ input.attachmentIds && input.attachmentIds.length+ ? input.attachmentIds+ : undefined,+ impersonation:+ input.impersonate === true+ ? {+ asCustomer: {+ customerIdentifier: {+ emailAddress: input.userEmail,+ },+ },+ }+ : undefined,+ });++ if (res.error) {+ logger.error("replyToThread failed", describeSdkError(res.error));+ }++ return res;+}++// ===== Threads (no initial message) =====+export async function createThread(+ ctx: PlainCtx,+ input: {+ email: string;+ title: string;+ messageType: string;+ severity: string;+ topicTopLevel: "Operations" | "Product Features";+ topicSubtype: string;+ url?: string;+ integrationType?: string;+ tenantExternalId?: string;+ },+): Promise<CreateSupportThreadResult> {+ const { client } = ctx;++ const threadFields = buildThreadFields({+ messageType: input.messageType,+ severity: input.severity,+ topLevel: input.topicTopLevel,+ subtype: input.topicSubtype,+ url: input.url,+ integrationType: input.integrationType,+ });++ // Try WITH threadFields+ const createdWithFields = await client.createThread({+ title: input.title,+ customerIdentifier: { emailAddress: input.email },+ threadFields,+ tenantIdentifier: input.tenantExternalId+ ? { externalId: input.tenantExternalId }+ : undefined,+ });++ if (createdWithFields.error) {+ logger.error(+ "createThread (no initial message) with threadFields failed — retrying without threadFields",+ describeSdkError(createdWithFields.error),+ );++ // Retry WITHOUT threadFields+ const retry = await client.createThread({+ title: input.title,+ customerIdentifier: { emailAddress: input.email },+ tenantIdentifier: input.tenantExternalId+ ? { externalId: input.tenantExternalId }+ : undefined,+ });++ const thread = unwrap(+ "createThread (no initial message, retry without threadFields)",+ retry,+ );+ const createdAt =+ thread.createdAt?.__typename === "DateTime"+ ? thread.createdAt.iso8601+ : undefined;++ return {+ threadId: thread.id,+ status: thread.status,+ createdAt,+ createdWithThreadFields: false,+ };+ }++ const thread = unwrap("createThread (no initial message)", createdWithFields);+ const createdAt =+ thread.createdAt?.__typename === "DateTime"+ ? thread.createdAt.iso8601+ : undefined;++ return {+ threadId: thread.id,+ status: thread.status,+ createdAt,+ createdWithThreadFields: true,+ };+}++// ===== Email acknowledgement (best-effort / non-throwing) =====+export async function sendAcknowledgementEmail(+ ctx: PlainCtx,+ input: {+ threadId: string;+ customerId: string;+ userEmail: string;+ originalMessage: string;+ },+) {+ const { client } = ctx;+ const subject = "Langfuse: We received your message";+ const textContent = `You have opened a new thread with Langfuse Support.\n\nYour message:\n\n${input.originalMessage}\n\nRespond to this email to add any additional context.`;+ const markdownContent = `You have opened a new thread with Langfuse Support\n\n\n**Your message:**\n\n\n${input.originalMessage}\n\n\nRespond to this email to add any additional context.`;++ const res = await client.sendNewEmail({+ customerId: input.customerId,+ threadId: input.threadId,+ subject,+ textContent,+ markdownContent,+ });++ if (res.error) {+ logger.error(+ "sendNewEmail (acknowledgement) failed",+ describeSdkError(res.error),+ );+ }+}diff --git a/web/src/features/support-chat/trpc/plainRouter.ts b/web/src/features/support-chat/trpc/plainRouter.tsindex a3207a342c..24c611fe26 100644--- a/web/src/features/support-chat/trpc/plainRouter.ts+++ b/web/src/features/support-chat/trpc/plainRouter.ts@@ -18,8 +18,9 @@ import {initPlain,ensureCustomer,createAttachmentUploadUrls,- createSupportThread as plainCreateSupportThread,+ createThread as plainCreateSupportThread,createThreadEvent,+ replyToThread,generateTenantExternalId,syncTenantsAndTiers,syncCustomerTenantMemberships,@@ -219,12 +220,11 @@ export const plainRouter = createTRPCRouter({const { topLevel, subtype } = splitTopic(input.topic);- // (3) Create thread (with fallback inside)+ // (3) Create thread (no initial message; with fallback inside)const { threadId, createdAt, status, createdWithThreadFields } =await plainCreateSupportThread(plain, {email,- title: `${input.messageType}: ${input.topic}`,- message: input.message,+ title: `[${input.messageType}] ${input.topic} • ${topLevel}/${subtype}`,messageType: input.messageType,severity: input.severity,topicTopLevel: topLevel,@@ -232,35 +232,63 @@ export const plainRouter = createTRPCRouter({url: input.url,tenantExternalId: currentSupportRequestContext.tenantExternalId,integrationType: input.integrationType,- attachmentIds: input.attachmentIds ?? [],});- // (4) Fire-and-forget metadata event- // eslint-disable-next-line @typescript-eslint/no-floating-promises- (async () => {- try {- const { title: eventTitle, components: eventComponents } =- buildPlainEventSupportRequestMetadataComponents({- userEmail: email,- url: input.url,- organizationId: currentSupportRequestContext.organizationId,- projectId: currentSupportRequestContext.projectId,- version: VERSION,- plan: currentSupportRequestContext.plan,- cloudRegion: currentSupportRequestContext.region,- browserMetadata: input.browserMetadata,- });-- await createThreadEvent(plain, {- threadId,- title: eventTitle,- components: eventComponents,- externalId: `support-metadata:${threadId}`,+ try {+ const { title: eventTitle, components: eventComponents } =+ buildPlainEventSupportRequestMetadataComponents({+ userEmail: email,+ url: input.url,+ organizationId: currentSupportRequestContext.organizationId,+ projectId: currentSupportRequestContext.projectId,+ version: VERSION,+ plan: currentSupportRequestContext.plan,+ cloudRegion: currentSupportRequestContext.region,+ browserMetadata: input.browserMetadata,});- } catch {- // best-effort; errors are logged in helpers- }- })();++ await createThreadEvent(plain, {+ threadId,+ title: eventTitle,+ components: eventComponents,+ externalId: `support-metadata:${threadId}`,+ });+ } catch {+ // best-effort; errors are logged in helpers+ }++ // (5) Post the user's original message as the first reply (impersonated), including attachments+ await replyToThread(plain, {+ threadId,+ userEmail: email,+ originalMessage: input.message,+ attachmentIds: input.attachmentIds ?? [],+ impersonate: true,+ });++ // Note: Plain seems to process the message asynchronously, so we need to wait a bit+ // to ensure the first message is processed. If we send the second message too early, the user+ // will receive only the second message and not their own below it.+ //+ // Monkey-Testing:+ // - 1000ms: doesn't work+ // - 2000ms: doesn't work+ // - 3000ms: doesn't work+ // - 4000ms: works sometimes+ // - 5000ms: works sometimes+ //+ // Observation: The more attachments, the longer we need to wait and PDFs seem to+ // take longer to process on plain's side.+ const waitTimeInMs = 5000 + (input.attachmentIds?.length ?? 0) * 1000;+ await new Promise((resolve) => setTimeout(resolve, waitTimeInMs));++ // (6) Acknowledge non-impersonated so it appears from Langfuse Cloud+ await replyToThread(plain, {+ threadId,+ userEmail: email,+ originalMessage: `Hi there,\n\n thanks for reaching out! We’ve received your request and will follow up as soon as possible.\n\nTo help us move faster, feel free to reply to this email with:\n- any error messages or screenshots\n- links to where you’re seeing the issue (trace, page, dataset)\n- steps to reproduce (if relevant)\n\nThanks,\n\nTeam Langfuse`,+ impersonate: false,+ });return {threadId,