Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(ui): support form to write to Pylon (#12378)

Jannik Maierhöfera9cbf0f1e1da
diff --git a/.env.prod.example b/.env.prod.example
index af24ceb3b1..41aa89efa1 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -287,6 +287,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# PLAIN_API_KEY=
# PLAIN_CARDS_API_TOKEN=
+# Pylon Support
+# PYLON_API_KEY=
+
# Admin API
# ADMIN_API_KEY=
# LANGFUSE_CACHE_MODEL_MATCH_ENABLED=
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 838fc5bda3..7abae4f861 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -354,6 +354,7 @@ export const env = createEnv({
PLAIN_AUTHENTICATION_SECRET: z.string().optional(),
PLAIN_API_KEY: z.string().optional(),
PLAIN_CARDS_API_TOKEN: z.string().optional(),
+ PYLON_API_KEY: z.string().optional(),
// UI customization - comma-separated list of visible product modules
LANGFUSE_UI_VISIBLE_PRODUCT_MODULES: z.string().optional(),
@@ -677,6 +678,7 @@ export const env = createEnv({
PLAIN_AUTHENTICATION_SECRET: process.env.PLAIN_AUTHENTICATION_SECRET,
PLAIN_API_KEY: process.env.PLAIN_API_KEY,
PLAIN_CARDS_API_TOKEN: process.env.PLAIN_CARDS_API_TOKEN,
+ PYLON_API_KEY: process.env.PYLON_API_KEY,
// clickhouse
CLICKHOUSE_URL: process.env.CLICKHOUSE_URL,
CLICKHOUSE_CLUSTER_NAME: process.env.CLICKHOUSE_CLUSTER_NAME,
diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsx
index bd202eb691..ff7e9083d7 100644
--- a/web/src/features/support-chat/SupportFormSection.tsx
+++ b/web/src/features/support-chat/SupportFormSection.tsx
@@ -188,7 +188,7 @@ export function SupportFormSection({
);
const createSupportThread = api.plainRouter.createSupportThread.useMutation({
- onSuccess: () => {
+ onSuccess: (data) => {
form.reset({
messageType: "Question",
severity: "Question or feature request",
@@ -197,6 +197,13 @@ export function SupportFormSection({
});
setWarnedShortOnce(false);
setFiles(undefined);
+ if (data.pylonIssueFailed) {
+ showErrorToast(
+ "Pylon Sync Failed",
+ "The support ticket was created but failed to sync to Pylon. Check server logs for details.",
+ "WARNING",
+ );
+ }
onSuccess();
},
onSettled: () => setIsSubmittingLocal(false),
@@ -230,6 +237,38 @@ export function SupportFormSection({
}
}
+ async function uploadFilesToPylon(filesToUpload: File[]): Promise<string[]> {
+ const filePayloads = await Promise.all(
+ filesToUpload.map(async (file) => {
+ const arrayBuffer = await file.arrayBuffer();
+ const base64 = btoa(
+ new Uint8Array(arrayBuffer).reduce(
+ (data, byte) => data + String.fromCharCode(byte),
+ "",
+ ),
+ );
+ return { fileName: file.name, fileBase64: base64 };
+ }),
+ );
+
+ const res = await fetch("/api/support/upload-attachments", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ files: filePayloads }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(
+ (body as { error?: string }).error ??
+ "Failed to upload attachments to Pylon.",
+ );
+ }
+
+ const body = (await res.json()) as { attachment_urls: string[] };
+ return body.attachment_urls;
+ }
+
const onSubmit = async (values: SupportFormInput) => {
const parsed: SupportFormValues = SupportFormSchema.parse(values);
const msgLen = (parsed.message ?? "").trim().length;
@@ -262,9 +301,10 @@ export function SupportFormSection({
customerId: undefined as string | undefined,
};
- // 2) Upload blobs
+ // 2) Upload blobs to Plain S3 and Pylon in parallel
+ let pylonAttachmentUrls: string[] = [];
if (files && files.length) {
- await Promise.all(
+ const plainUploadPromise = Promise.all(
files.map(async (file, idx) => {
const plan = uploadPlans.uploads[idx];
if (!plan) throw new Error("Missing upload plan for a file.");
@@ -275,9 +315,20 @@ export function SupportFormSection({
);
}),
);
+
+ const pylonUploadPromise = uploadFilesToPylon(files).catch((err) => {
+ console.warn("Pylon attachment upload failed (best-effort):", err);
+ return [] as string[];
+ });
+
+ const [, pylonUrls] = await Promise.all([
+ plainUploadPromise,
+ pylonUploadPromise,
+ ]);
+ pylonAttachmentUrls = pylonUrls;
}
- // 3) Create thread with attachmentIds
+ // 3) Create thread with attachmentIds (Plain) and pylonAttachmentUrls (Pylon)
const attachmentIds =
uploadPlans.uploads?.map((u: any) => u.attachmentId) ?? [];
@@ -297,6 +348,7 @@ export function SupportFormSection({
viewport: { w: window.innerWidth, h: window.innerHeight },
},
attachmentIds,
+ pylonAttachmentUrls,
});
} catch (err: any) {
console.error(err);
@@ -507,7 +559,14 @@ export function SupportFormSection({
className="mt-1 border-none p-0 text-left"
maxFiles={FILE_UPLOAD_CONSTRAINTS.maxFiles}
maxSize={FILE_UPLOAD_CONSTRAINTS.maxFileSizeBytes}
- onDrop={(accepted) => setFiles(accepted)}
+ onDrop={(accepted) =>
+ setFiles((prev) => {
+ const existing = prev ?? [];
+ const merged = [...existing, ...accepted];
+ const maxFiles = FILE_UPLOAD_CONSTRAINTS.maxFiles;
+ return merged.slice(0, maxFiles);
+ })
+ }
onError={(error) => {
const userMessage = formatFileError(error);
showErrorToast("File Upload Error", userMessage, "WARNING");
diff --git a/web/src/features/support-chat/pylon/pylonClient.ts b/web/src/features/support-chat/pylon/pylonClient.ts
new file mode 100644
index 0000000000..6e12fe1216
--- /dev/null
+++ b/web/src/features/support-chat/pylon/pylonClient.ts
@@ -0,0 +1,292 @@
+import { logger } from "@langfuse/shared/src/server";
+
+const PYLON_API_BASE = "https://api.usepylon.com";
+
+type CreatePylonIssueParams = {
+ apiKey: string;
+ title: string;
+ bodyHtml: string;
+ requesterEmail: string;
+ requesterName?: string;
+ tags?: string[];
+ priority?: "urgent" | "high" | "medium" | "low";
+ attachmentUrls?: string[];
+ customFields?: { slug: string; value?: string; values?: string[] }[];
+};
+
+type PylonIssueResponse = {
+ data?: {
+ id: string;
+ number: number;
+ link: string;
+ state: string;
+ account?: { id: string };
+ };
+ request_id?: string;
+ errors?: string[];
+};
+
+export async function createPylonIssue(
+ params: CreatePylonIssueParams,
+): Promise<PylonIssueResponse> {
+ const {
+ apiKey,
+ title,
+ bodyHtml,
+ requesterEmail,
+ requesterName,
+ tags,
+ priority,
+ attachmentUrls,
+ } = params;
+
+ const body: Record<string, unknown> = {
+ title,
+ body_html: bodyHtml,
+ requester_email: requesterEmail,
+ destination_metadata: {
+ destination: "email",
+ email: "[email protected]",
+ },
+ };
+
+ if (requesterName) body.requester_name = requesterName;
+ if (tags?.length) body.tags = tags;
+ if (priority) body.priority = priority;
+ if (attachmentUrls?.length) body.attachment_urls = attachmentUrls;
+ if (params.customFields?.length) body.custom_fields = params.customFields;
+
+ const res = await fetch(`${PYLON_API_BASE}/issues`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+
+ const json = (await res.json()) as PylonIssueResponse;
+
+ if (!res.ok) {
+ const errorMsg = json.errors?.join(", ") ?? res.statusText;
+ logger.error("Pylon createIssue failed", {
+ status: res.status,
+ errors: json.errors,
+ requestId: json.request_id,
+ });
+ throw new Error(`Pylon API error (${res.status}): ${errorMsg}`);
+ }
+
+ return json;
+}
+
+type UploadPylonAttachmentParams = {
+ apiKey: string;
+ file: Buffer;
+ fileName: string;
+};
+
+type PylonAttachmentResponse = {
+ data?: {
+ id: string;
+ url: string;
+ name: string;
+ };
+ request_id?: string;
+ errors?: string[];
+};
+
+export async function uploadPylonAttachment(
+ params: UploadPylonAttachmentParams,
+): Promise<PylonAttachmentResponse> {
+ const { apiKey, file, fileName } = params;
+
+ const arrayBuffer = file.buffer.slice(
+ file.byteOffset,
+ file.byteOffset + file.byteLength,
+ ) as ArrayBuffer;
+ const formData = new FormData();
+ formData.append("file", new Blob([arrayBuffer]), fileName);
+
+ const res = await fetch(`${PYLON_API_BASE}/attachments`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: formData,
+ });
+
+ const json = (await res.json()) as PylonAttachmentResponse;
+
+ if (!res.ok) {
+ const errorMsg = json.errors?.join(", ") ?? res.statusText;
+ logger.error("Pylon uploadAttachment failed", {
+ status: res.status,
+ errors: json.errors,
+ requestId: json.request_id,
+ });
+ throw new Error(
+ `Pylon attachment upload error (${res.status}): ${errorMsg}`,
+ );
+ }
+
+ return json;
+}
+
+type UpdatePylonAccountParams = {
+ apiKey: string;
+ accountId: string;
+ customFields: { slug: string; value: string }[];
+};
+
+export async function updatePylonAccountCustomFields(
+ params: UpdatePylonAccountParams,
+): Promise<void> {
+ const { apiKey, accountId, customFields } = params;
+
+ const res = await fetch(`${PYLON_API_BASE}/accounts/${accountId}`, {
+ method: "PATCH",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ custom_fields: customFields }),
+ });
+
+ if (!res.ok) {
+ const json = (await res.json().catch(() => ({}))) as {
+ errors?: string[];
+ request_id?: string;
+ };
+ const errorMsg = json.errors?.join(", ") ?? res.statusText;
+ logger.error("Pylon updateAccount failed", {
+ status: res.status,
+ errors: json.errors,
+ requestId: json.request_id,
+ });
+ throw new Error(`Pylon account update error (${res.status}): ${errorMsg}`);
+ }
+}
+
+export function mapSeverityToPylonPriority(
+ severity: string,
+): "urgent" | "high" | "medium" | "low" {
+ switch (severity) {
+ case "Outage, data loss, or data breach":
+ return "urgent";
+ case "Feature is not working at all":
+ return "high";
+ case "Feature not working as expected":
+ return "medium";
+ case "Question or feature request":
+ default:
+ return "low";
+ }
+}
+
+export function buildPylonIssueBodyHtml(params: {
+ message: string;
+ requesterEmail: string;
+}): string {
+ const escapedEmail = escapeHtml(params.requesterEmail);
+ const escapedMessage = escapeHtml(params.message);
+
+ const lines: string[] = [
+ `<p>Hi there,</p>`,
+ `<p>thanks for reaching out! We've received your request and will follow up as soon as possible.</p>`,
+ `<p>To help us move faster, feel free to reply to this email with:</p>`,
+ `<ul>`,
+ `<li>any error messages or screenshots</li>`,
+ `<li>links to where you're seeing the issue (trace, page, dataset)</li>`,
+ `<li>steps to reproduce (if relevant)</li>`,
+ `</ul>`,
+ `<p>Thanks,</p>`,
+ `<p>Team Langfuse</p>`,
+ `<hr>`,
+ `<p><b>${escapedEmail} wrote:</b></p>`,
+ `<blockquote>${escapedMessage.replace(/\n/g, "<br>")}</blockquote>`,
+ ];
+
+ return lines.join("\n");
+}
+
+export function buildPylonMetadataString(params: {
+ messageType?: string;
+ severity?: string;
+ topic?: string;
+ integrationType?: string;
+ url?: string;
+ organizationId?: string;
+ projectId?: string;
+ plan?: string;
+ cloudRegion?: string;
+ version?: string;
+ browserMetadata?: Record<string, unknown>;
+}): string {
+ const rows: string[] = [];
+ if (params.messageType) rows.push(`Type: ${params.messageType}`);
+ if (params.severity) rows.push(`Severity: ${params.severity}`);
+ if (params.topic) rows.push(`Topic: ${params.topic}`);
+ if (params.integrationType)
+ rows.push(`Integration: ${params.integrationType}`);
+ if (params.url) rows.push(`URL: ${params.url}`);
+ if (params.organizationId)
+ rows.push(`Organization ID: ${params.organizationId}`);
+ if (params.projectId) rows.push(`Project ID: ${params.projectId}`);
+ if (params.plan) rows.push(`Plan: ${params.plan}`);
+ if (params.cloudRegion) rows.push(`Cloud Region: ${params.cloudRegion}`);
+ if (params.version) rows.push(`Version: ${params.version}`);
+ if (params.browserMetadata)
+ rows.push(`Browser: ${JSON.stringify(params.browserMetadata)}`);
+ return rows.join("\n");
+}
+
+export function mapMessageTypeToPylonQuestionType(messageType: string): string {
+ switch (messageType) {
+ case "Bug":
+ return "bug";
+ case "Feedback":
+ return "feature_request";
+ case "Question":
+ default:
+ return "question";
+ }
+}
+
+export function mapToPylonCaseSeverity(params: {
+ severity: string;
+ plan?: string;
+}): "Sev-1" | "Sev-2" | "Sev-3" {
+ const { severity, plan } = params;
+ const isHighTierPlan =
+ plan === "cloud:team" ||
+ plan === "cloud:enterprise" ||
+ plan === "self-hosted:enterprise";
+
+ if (severity === "Outage, data loss, or data breach" && isHighTierPlan) {
+ return "Sev-1";
+ }
+
+ if (
+ severity === "Outage, data loss, or data breach" ||
+ severity === "Feature is not working at all"
+ ) {
+ return "Sev-2";
+ }
+
+ return "Sev-3";
+}
+
+export function mapPlanToPylonCustomerTier(plan: string): string {
+ if (plan === "oss") return "self_hosted_free";
+ return plan.replace(/[:-]/g, "_");
+}
+
+function escapeHtml(str: string): string {
+ return str
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#039;");
+}
diff --git a/web/src/features/support-chat/trpc/plainRouter.ts b/web/src/features/support-chat/trpc/plainRouter.ts
index db74da5540..31ae30330d 100644
--- a/web/src/features/support-chat/trpc/plainRouter.ts
+++ b/web/src/features/support-chat/trpc/plainRouter.ts
@@ -8,6 +8,7 @@ import { z } from "zod";
import { env } from "@/src/env.mjs";
import { VERSION } from "@/src/constants";
import { nanoid } from "nanoid";
+import { logger } from "@langfuse/shared/src/server";
import {
MessageTypeSchema,
@@ -17,6 +18,16 @@ import {
} from "../formConstants";
import { buildPlainEventSupportRequestMetadataComponents } from "../plain/events/supportRequestMetadataEvent";
+import {
+ createPylonIssue,
+ buildPylonIssueBodyHtml,
+ buildPylonMetadataString,
+ mapSeverityToPylonPriority,
+ updatePylonAccountCustomFields,
+ mapPlanToPylonCustomerTier,
+ mapToPylonCaseSeverity,
+ mapMessageTypeToPylonQuestionType,
+} from "../pylon/pylonClient";
import {
initPlain,
@@ -46,8 +57,10 @@ const CreateSupportThreadInput = z.object({
projectId: z.string().optional(),
browserMetadata: z.record(z.string(), z.any()).optional(),
integrationType: z.string().optional(),
- /** IDs of attachments already uploaded via prepareAttachmentUploads */
+ /** IDs of attachments already uploaded via prepareAttachmentUploads (Plain) */
attachmentIds: z.array(z.string()).optional(),
+ /** URLs of attachments already uploaded to Pylon */
+ pylonAttachmentUrls: z.array(z.string().url()).optional(),
});
const PrepareAttachmentUploadsInput = z.object({
@@ -312,6 +325,105 @@ export const plainRouter = createTRPCRouter({
impersonate: false,
});
+ // (6) Dual-write: create issue in Pylon (best-effort, blocking)
+ // TEMPORARY: only route clickhouse.com and langfuse.com to Pylon for testing
+ let pylonIssueFailed = false;
+ const emailDomain = email.split("@")[1]?.toLowerCase();
+ const pylonTestDomains = ["clickhouse.com", "langfuse.com"];
+ if (env.PYLON_API_KEY && pylonTestDomains.includes(emailDomain ?? "")) {
+ try {
+ const pylonTitle = `[${uniqueId}] ${input.messageType}: ${input.topic} • ${topLevel}/${subtype}`;
+ const pylonBodyHtml = buildPylonIssueBodyHtml({
+ message: input.message,
+ requesterEmail: email,
+ });
+ const pylonMetadata = buildPylonMetadataString({
+ messageType: input.messageType,
+ severity: input.severity,
+ topic: input.topic,
+ integrationType: input.integrationType,
+ url: input.url,
+ organizationId: currentSupportRequestContext.organizationId,
+ projectId: currentSupportRequestContext.projectId,
+ plan: currentSupportRequestContext.plan,
+ cloudRegion: currentSupportRequestContext.region,
+ version: VERSION,
+ browserMetadata: input.browserMetadata,
+ });
+ const pylonCustomerTier = currentSupportRequestContext.plan
+ ? mapPlanToPylonCustomerTier(currentSupportRequestContext.plan)
+ : undefined;
+ const pylonIssue = await createPylonIssue({
+ apiKey: env.PYLON_API_KEY,
+ title: pylonTitle,
+ bodyHtml: pylonBodyHtml,
+ requesterEmail: email,
+ requesterName: fullName,
+ tags: ["Langfuse"],
+ priority: mapSeverityToPylonPriority(input.severity),
+ attachmentUrls: input.pylonAttachmentUrls,
+ customFields: [
+ ...(input.url
+ ? [{ slug: "langfuse_page_url", value: input.url }]
+ : []),
+ {
+ slug: "question_type",
+ values: [mapMessageTypeToPylonQuestionType(input.messageType)],
+ },
+ { slug: "langfuse_topic", value: input.topic },
+ ...(input.integrationType
+ ? [
+ {
+ slug: "langfuse_integration_type",
+ value: input.integrationType,
+ },
+ ]
+ : []),
+ { slug: "langfuse_metadata", value: pylonMetadata },
+ ...(pylonCustomerTier
+ ? [
+ {
+ slug: "langfuse_customer_tier",
+ value: pylonCustomerTier,
+ },
+ ]
+ : []),
+ {
+ slug: "case_severity",
+ value: mapToPylonCaseSeverity({
+ severity: input.severity,
+ plan: currentSupportRequestContext.plan,
+ }),
+ },
+ ],
+ });
+
+ const pylonAccountId = pylonIssue.data?.account?.id;
+ if (pylonAccountId && pylonCustomerTier) {
+ try {
+ await updatePylonAccountCustomFields({
+ apiKey: env.PYLON_API_KEY,
+ accountId: pylonAccountId,
+ customFields: [
+ {
+ slug: "langfuse_customer_tier",
+ value: pylonCustomerTier,
+ },
+ ],
+ });
+ } catch (e) {
+ logger.error(
+ "Pylon account custom field update failed (best-effort)",
+ e,
+ );
+ }
+ }
+ } catch (e) {
+ pylonIssueFailed = true;
+ logger.error("Pylon issue creation failed (best-effort)", e);
+ }
+ }
+
return {
threadId,
customerId,
@@ -319,6 +431,7 @@ export const plainRouter = createTRPCRouter({
createdAt,
createdWithThreadFields,
attachmentCount: (input.attachmentIds ?? []).length,
+ pylonIssueFailed,
};
}),
});
diff --git a/web/src/pages/api/support/upload-attachments.ts b/web/src/pages/api/support/upload-attachments.ts
new file mode 100644
index 0000000000..6924ff2fed
--- /dev/null
+++ b/web/src/pages/api/support/upload-attachments.ts
@@ -0,0 +1,108 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { getServerAuthSession } from "@/src/server/auth";
+import { env } from "@/src/env.mjs";
+import { logger } from "@langfuse/shared/src/server";
+import { uploadPylonAttachment } from "@/src/features/support-chat/pylon/pylonClient";
+
+export const config = {
+ api: {
+ bodyParser: {
+ sizeLimit: "50mb",
+ },
+ },
+};
+
+type FilePayload = {
+ fileName: string;
+ fileBase64: string;
+};
+
+type RequestBody = {
+ files: FilePayload[];
+};
+
+type ResponseBody = { attachment_urls: string[] } | { error: string };
+
+const MAX_FILES = 5;
+const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse<ResponseBody>,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", "POST");
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ const session = await getServerAuthSession({ req, res });
+ if (!session?.user) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const pylonApiKey = env.PYLON_API_KEY;
+ if (!pylonApiKey) {
+ return res
+ .status(503)
+ .json({ error: "Pylon integration is not configured" });
+ }
+
+ const body = req.body as RequestBody;
+ if (!body?.files || !Array.isArray(body.files)) {
+ return res.status(400).json({ error: "Missing files array in body" });
+ }
+
+ if (body.files.length > MAX_FILES) {
+ return res
+ .status(400)
+ .json({ error: `Maximum ${MAX_FILES} files allowed` });
+ }
+
+ try {
+ const validatedFiles: { buffer: Buffer; fileName: string }[] = [];
+
+ for (const file of body.files) {
+ if (!file.fileName || !file.fileBase64) {
+ return res
+ .status(400)
+ .json({ error: "Each file must have fileName and fileBase64" });
+ }
+
+ const buffer = Buffer.from(file.fileBase64, "base64");
+
+ if (buffer.length > MAX_FILE_SIZE_BYTES) {
+ return res.status(400).json({
+ error: `File "${file.fileName}" exceeds maximum size of ${MAX_FILE_SIZE_BYTES / (1024 * 1024)}MB`,
+ });
+ }
+
+ validatedFiles.push({ buffer, fileName: file.fileName });
+ }
+
+ const results = await Promise.all(
+ validatedFiles.map((file) =>
+ uploadPylonAttachment({
+ apiKey: pylonApiKey,
+ file: file.buffer,
+ fileName: file.fileName,
+ }),
+ ),
+ );
+
+ const attachmentUrls = results.map((result, idx) => {
+ if (!result.data?.url) {
+ throw new Error(
+ `Pylon returned no URL for file "${validatedFiles[idx]?.fileName}"`,
+ );
+ }
+ return result.data.url;
+ });
+
+ return res.status(200).json({ attachment_urls: attachmentUrls });
+ } catch (err) {
+ logger.error("Failed to upload attachments to Pylon", err);
+ return res
+ .status(500)
+ .json({ error: "Failed to upload attachments. Please try again." });
+ }
+}