🪢 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
refactor(web): remove support thread creation in Plain (#14081)
Jannik Maierhöferfdf8ab592515
diff --git a/.env.prod.example b/.env.prod.exampleindex af323fbe62..24631cc66f 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -309,7 +309,6 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# Plain Chat# NEXT_PUBLIC_PLAIN_APP_ID=# PLAIN_AUTHENTICATION_SECRET=-# PLAIN_API_KEY=# PLAIN_CARDS_API_TOKEN=# Pylon Supportdiff --git a/web/src/env.mjs b/web/src/env.mjsindex c55c2e7927..d4af969ecf 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -371,7 +371,6 @@ export const env = createEnv({.positive().default(50_000),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(),@@ -741,7 +740,6 @@ export const env = createEnv({// OtherNEXT_PUBLIC_PLAIN_APP_ID: process.env.NEXT_PUBLIC_PLAIN_APP_ID,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,// clickhousediff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsxindex 3a01b0d1cf..fcc58b89e9 100644--- a/web/src/features/support-chat/SupportFormSection.tsx+++ b/web/src/features/support-chat/SupportFormSection.tsx@@ -43,7 +43,7 @@ import {} from "@/src/components/ui/shadcn-io/dropzone";import { Paperclip, Trash2 } from "lucide-react";import { showErrorToast } from "@/src/features/notifications/showErrorToast";-import { PLAIN_MAX_FILE_SIZE_BYTES } from "./plain/plainConstants";+import { PYLON_MAX_FILE_SIZE_BYTES } from "./pylon/pylonConstants";import Spinner from "@/src/components/design-system/Spinner/Spinner";/** Make RHF generics match the resolver (Zod defaults => input can be undefined) */@@ -52,12 +52,16 @@ type SupportFormValues = z.output<typeof SupportFormSchema>;/*** File upload constraints - single source of truth for validation- * Uses Plain API's file size limit+ * Uses Pylon's file size limit*/const FILE_UPLOAD_CONSTRAINTS = {maxFiles: 5,- maxFileSizeBytes: PLAIN_MAX_FILE_SIZE_BYTES, // 6MB (Plain API limit)- maxCombinedBytes: 50 * 1024 * 1024, // 50MB+ maxFileSizeBytes: PYLON_MAX_FILE_SIZE_BYTES, // 10MB (Pylon API limit)+ // Files are sent to /api/support/upload-attachments as base64-encoded JSON,+ // which inflates the body by ~33%. The endpoint's bodyParser caps the body+ // at 50MB, so the raw combined size must stay below ~37.5MB to fit. Use 35MB+ // for headroom (JSON overhead, multiple files).+ maxCombinedBytes: 35 * 1024 * 1024, // 35MB raw (~47MB once base64-encoded)} as const;/**@@ -188,55 +192,32 @@ export function SupportFormSection({selectedTopic as any,);- const createSupportThread = api.plainRouter.createSupportThread.useMutation({- onSuccess: (data) => {- form.reset({- messageType: "Question",- severity: "Question or feature request",- topic: "",- message: "",- });- setWarnedShortOnce(false);- setFiles(undefined);- if (data.pylonIssueFailed) {- showErrorToast(- "Support request was not sent",- "Please contact [email protected]",- );- } else {+ const createSupportThread = api.supportRouter.createSupportThread.useMutation(+ {+ onSuccess: (data) => {+ // Pylon is the only destination, so a failed issue means no ticket+ // exists anywhere. Keep the form state (message, topic, severity,+ // attachments) intact so the user can retry instead of wiping it.+ if (data.pylonIssueFailed) {+ showErrorToast(+ "Support request was not sent",+ "Please contact [email protected]",+ );+ return;+ }+ form.reset({+ messageType: "Question",+ severity: "Question or feature request",+ topic: "",+ message: "",+ });+ setWarnedShortOnce(false);+ setFiles(undefined);onSuccess();- }- },- onSettled: () => setIsSubmittingLocal(false),- });-- const prepareUploads = api.plainRouter.prepareAttachmentUploads.useMutation({- onError: (error) => {- setIsSubmittingLocal(false);- showErrorToast(- "Upload Preparation Failed",- error.message || "Failed to prepare file uploads. Please try again.",- "ERROR",- );+ },+ onSettled: () => setIsSubmittingLocal(false),},- });-- async function uploadToPlainS3(- uploadFormUrl: string,- uploadFormData: { key: string; value: string }[],- file: File,- ) {- const form = new FormData();- uploadFormData.forEach(({ key, value }) => form.append(key, value));- form.append("file", file, file.name);- const res = await fetch(uploadFormUrl, { method: "POST", body: form });- if (!res.ok) {- const text = await res.text().catch(() => "");- throw new Error(- `Attachment upload failed (${res.status} ${res.statusText}) ${text}`,- );- }- }+ );async function uploadFilesToPylon(filesToUpload: File[]): Promise<string[]> {const filePayloads = await Promise.all(@@ -288,51 +269,16 @@ export function SupportFormSection({throw new Error(validation.error);}- // 1) Request presigned S3 upload forms- const uploadPlans =- files && files.length- ? await prepareUploads.mutateAsync({- files: files.map((f) => ({- fileName: f.name,- fileSizeBytes: f.size,- })),- })- : {- uploads: [] as any[],- customerId: undefined as string | undefined,- };-- // 2) Upload blobs to Plain S3 and Pylon in parallel+ // 1) Upload attachments to Pylon. This is the only attachment path, so+ // do NOT swallow failures: let them propagate to the outer catch (which+ // surfaces the error via form.setError) instead of silently dropping the+ // user's files while still creating the thread.let pylonAttachmentUrls: string[] = [];if (files && files.length) {- 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.");- await uploadToPlainS3(- plan.uploadFormUrl,- plan.uploadFormData,- file,- );- }),- );-- 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;+ pylonAttachmentUrls = await uploadFilesToPylon(files);}- // 3) Create thread with attachmentIds (Plain) and pylonAttachmentUrls (Pylon)- const attachmentIds =- uploadPlans.uploads?.map((u: any) => u.attachmentId) ?? [];-+ // 2) Create the support thread in Pylonawait createSupportThread.mutateAsync({messageType: parsed.messageType,severity: parsed.severity,@@ -353,7 +299,6 @@ export function SupportFormSection({language: navigator.language,viewport: { w: window.innerWidth, h: window.innerHeight },},- attachmentIds,pylonAttachmentUrls,});} catch (err: any) {diff --git a/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.ts b/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.tsdeleted file mode 100644index 5990521e8e..0000000000--- a/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.ts+++ /dev/null@@ -1,106 +0,0 @@-import {- ComponentTextColor,- ComponentTextSize,- ComponentSpacerSize,- ComponentDividerSpacingSize,- type EventComponentInput,-} from "@team-plain/typescript-sdk";--/**- * Input for the Support Request Metadata event UI.- * Compact layout using Text/PlainText, markdown links, small muted labels,- * minimal spacers, and copy buttons under values.- */-export type SupportRequestMetadataInput = {- userEmail?: string;- url?: string;- organizationId?: string;- projectId?: string;- version?: string;- plan?: string;- cloudRegion?: string;- browserMetadata?: unknown; // JSON.stringified if provided-};--/**- * Builds a Plain thread event:- * - title- * - compact components (ditch rows, use markdown link, copy buttons)- */-export function buildPlainEventSupportRequestMetadataComponents(- input: SupportRequestMetadataInput,-): { title: string; components: EventComponentInput[] } {- const components: EventComponentInput[] = [];-- // Helpers (avoid null props)- const pushText = (- text: string,- size?: ComponentTextSize,- color?: ComponentTextColor,- ) => {- const payload: Record<string, unknown> = { text };- if (size) payload.textSize = size;- if (color) payload.textColor = color;- components.push({ componentText: payload as any });- };- const pushLabel = (text: string) =>- pushText(text, ComponentTextSize.S, ComponentTextColor.Muted);- const pushPlain = (plainText: string) =>- components.push({ componentPlainText: { plainText } });- const pushSpacer = (size: ComponentSpacerSize) =>- components.push({ componentSpacer: { spacerSize: size } });- const pushDivider = (size: ComponentDividerSpacingSize) =>- components.push({ componentDivider: { dividerSpacingSize: size } });-- // ---------- Header (compact, link in markdown) ----------- const url = input.url;- const urlMd = url ? `[${url}](${url})` : undefined;- const headline = url- ? `In-app support request submitted on ${urlMd} from [${input.userEmail}](mailto:${input.userEmail})`- : `In-app support request submitted from [${input.userEmail}](mailto:${input.userEmail})`;- pushText(headline);- pushDivider(ComponentDividerSpacingSize.S);-- // ---------- Identifiers ----------- if (input.organizationId || input.projectId) {- pushLabel("Identifiers");- pushText(- `Organization: ${input.organizationId ?? "—"} | Project: ${- input.projectId ?? "—"- }`,- );- }-- // ---------- Environment ----------- if (input.version || input.plan || input.cloudRegion) {- pushLabel("Environment");- const parts: string[] = [];- if (input.plan) parts.push(`Plan: ${input.plan}`);- if (input.cloudRegion) parts.push(`Cloud Region: ${input.cloudRegion}`);- if (input.version) parts.push(`Version: ${input.version}`);- pushPlain(parts.join(" | "));- pushSpacer(ComponentSpacerSize.Xs);- }-- // ---------- Browser ----------- if (typeof input.browserMetadata !== "undefined") {- pushLabel("Browser");- const json =- typeof input.browserMetadata === "string"- ? input.browserMetadata- : JSON.stringify(input.browserMetadata);- pushPlain(json);- }-- // Fallback if nothing provided- if (components.length === 0) {- pushText("No metadata provided.", undefined, ComponentTextColor.Muted);- } else {- pushDivider(ComponentDividerSpacingSize.S);- }-- return {- title: "Page context on submit:",- components,- };-}diff --git a/web/src/features/support-chat/plain/plainClient.ts b/web/src/features/support-chat/plain/plainClient.tsdeleted file mode 100644index 35f81070b7..0000000000--- a/web/src/features/support-chat/plain/plainClient.ts+++ /dev/null@@ -1,694 +0,0 @@-import {- PlainClient as SdkPlainClient,- ThreadFieldSchemaType,- AttachmentType,- type EventComponentInput,-} from "@team-plain/typescript-sdk";-import { TRPCError } from "@trpc/server";-import { logger } from "@langfuse/shared/src/server";-import { PLAIN_MAX_FILE_SIZE_BYTES } from "./plainConstants";--// Re-export for backward compatibility-export { PLAIN_MAX_FILE_SIZE_BYTES };--// ===== App-level types exported for router use =====-export type Project = { id: string };-export type Organization = {- id: string;- name: string;- plan?: string;- projects?: Project[];-};-export type SessionUser = {- email?: string | null;- name?: string | null;- organizations?: Organization[];-};--export type PrepareAttachmentUploadInput = {- fileName: string;- fileSizeBytes: number;-};--export type PrepareAttachmentUploadResult = {- attachmentId: string;- uploadFormUrl: string;- uploadFormData: { key: string; value: string }[];- fileName: string;- fileSizeBytes: number;-};--export type CreateSupportThreadResult = {- threadId: string;- createdAt?: string;- status?: string;- createdWithThreadFields: boolean;-};--// ===== Context & init (DI) =====-export type PlainCtx = { client: SdkPlainClient };--export function initPlain(params: { apiKey?: string | null }): PlainCtx {- const apiKey = params.apiKey ?? "";- if (!apiKey) {- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: "Missing PLAIN_API_KEY",- });- }- return { client: new SdkPlainClient({ apiKey }) };-}--// ===== Internal helpers =====-function describeSdkError(err: unknown) {- const e = err as any;- return {- name: e?.name,- message: e?.message,- type: e?.type,- code: e?.code,- fields: e?.fields,- errorDetails: e?.errorDetails,- status: e?.status,- };-}--/**- * Formats Plain API errors into user-friendly messages- * @returns User-friendly error message and appropriate HTTP status code- */-function formatPlainError(error: unknown): {- message: string;- code: "BAD_REQUEST" | "INTERNAL_SERVER_ERROR";-} {- const e = error as any;- const errorMessage =- e?.message || e?.errorDetails?.message || String(error) || "";- const msg = errorMessage.toLowerCase();-- // File size errors- if (- msg.includes("file size") ||- msg.includes("too large") ||- msg.includes(">6mb") ||- msg.includes("larger than")- ) {- return {- message: `File is too large. Maximum file size is ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB per file.`,- code: "BAD_REQUEST",- };- }-- // File type errors- if (msg.includes("file type") || msg.includes("not supported")) {- return {- message: "File type not supported. Please select a different file.",- code: "BAD_REQUEST",- };- }-- // Rate limit errors- if (msg.includes("rate limit") || msg.includes("too many requests")) {- return {- message: "Too many requests. Please try again in a moment.",- code: "BAD_REQUEST",- };- }-- // Extract original message if available and meaningful- if (errorMessage && errorMessage.length > 0 && errorMessage.length < 200) {- return {- message: errorMessage,- code: "BAD_REQUEST",- };- }-- // Fallback for unknown errors- return {- message: "Failed to prepare file upload. Please try again.",- code: "INTERNAL_SERVER_ERROR",- };-}--function unwrap<T>(label: string, res: { data?: T; error?: unknown }): T {- if (res.error) {- logger.error(`${label} failed`, describeSdkError(res.error));- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: `Plain Client: ${label} failed`,- cause: res.error,- });- }- if (!res.data) {- logger.error(`${label} returned no data`, res);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: `Plain Client: ${label} returned no data`,- });- }- return res.data;-}--export function generateTenantExternalId(orgId: string, region: string) {- return `cloud_${region}_org_${orgId}`;-}--// ===== Customers =====-export async function ensureCustomer(- ctx: PlainCtx,- params: { email: string; fullName?: string },-): Promise<string> {- const { client } = ctx;- const { email, fullName } = params;-- const upsert = await client.upsertCustomer({- identifier: { emailAddress: email },- onCreate: {- fullName: fullName ?? "",- email: { email, isVerified: true },- },- onUpdate: {- fullName: fullName ? { value: fullName } : undefined,- email: { email, isVerified: true },- },- });-- const upsertData = unwrap("upsertCustomer", upsert); // throws on error- const customerId = upsertData.customer?.id;- if (!customerId) {- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Plain did not return a customer id.",- });- }- return customerId;-}--// ===== Attachments =====-export async function createAttachmentUploadUrls(- ctx: PlainCtx,- customerId: string,- files: PrepareAttachmentUploadInput[],-): Promise<PrepareAttachmentUploadResult[]> {- const { client } = ctx;- const out: PrepareAttachmentUploadResult[] = [];-- for (const f of files) {- const r = await client.createAttachmentUploadUrl({- customerId,- fileName: f.fileName,- fileSizeBytes: f.fileSizeBytes,- attachmentType: AttachmentType.Email,- });-- // Handle Plain API errors with user-friendly messages- if (r.error) {- const formatted = formatPlainError(r.error);- logger.error(- "createAttachmentUploadUrl failed",- describeSdkError(r.error),- );- throw new TRPCError({- code: formatted.code,- message: formatted.message,- cause: r.error,- });- }-- if (!r.data) {- logger.error("createAttachmentUploadUrl returned no data", r);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Plain Client: createAttachmentUploadUrl returned no data",- });- }-- out.push({- attachmentId: r.data.attachment.id,- uploadFormUrl: r.data.uploadFormUrl,- uploadFormData: r.data.uploadFormData,- fileName: f.fileName,- fileSizeBytes: f.fileSizeBytes,- });- }- return out;-}--// ===== Tenants & tiers (best-effort / non-throwing) =====-export async function syncTenantsAndTiers(- ctx: PlainCtx,- params: { user: SessionUser; region: string; demoOrgId?: string },-) {- const { client } = ctx;- const { user, region, demoOrgId } = params;- if (!Array.isArray(user?.organizations)) return;-- await Promise.all(- user.organizations.map(async (org: Organization) => {- const extId = generateTenantExternalId(org.id, region);- const upsertTenantRes = await client.upsertTenant({- identifier: { externalId: extId },- name: `${region} - ${org.name}`,- externalId: extId,- });- if (upsertTenantRes.error) {- logger.error(- "upsertTenant failed",- describeSdkError(upsertTenantRes.error),- );- return;- }-- const tierExternalId =- org?.id === demoOrgId ? "cloud:demo" : (org?.plan ?? "default");- const tierRes = await client.updateTenantTier({- tenantIdentifier: { externalId: extId },- tierIdentifier: { externalId: tierExternalId },- });- if (tierRes.error) {- logger.error(- "updateTenantTier failed",- describeSdkError(tierRes.error),- );- }- }),- );-}--// ===== Tenant memberships (best-effort / non-throwing) =====-async function fetchAllCustomerTenantMemberships(- ctx: PlainCtx,- customerId: string,-) {- const { client } = ctx;- type Membership = { tenant: { externalId: string } };- const out: Membership[] = [];- let after: string | undefined = undefined;- const pageSize = 100;-- while (true) {- const r = await client.getCustomerTenantMemberships({- customerId,- first: pageSize,- after,- });- if (r.error) {- logger.error(- "getCustomerTenantMemberships failed",- describeSdkError(r.error),- );- break;- }- const memberships = r.data?.tenantMemberships as Membership[] | undefined;- if (memberships?.length) out.push(...memberships);-- const pageInfo = r.data?.pageInfo as- | { hasNextPage?: boolean; endCursor?: string }- | undefined;- if (pageInfo?.hasNextPage && pageInfo.endCursor) {- after = pageInfo.endCursor;- } else {- break;- }- }- return out;-}--export async function syncCustomerTenantMemberships(- ctx: PlainCtx,- params: {- email: string;- customerId: string;- user: SessionUser;- region: string;- },-) {- const { client } = ctx;- const { email, customerId, user, region } = params;- if (!region) return;- if (!Array.isArray(user?.organizations)) return;-- const currentMemberships = await fetchAllCustomerTenantMemberships(- ctx,- customerId,- );-- const regionPrefix = `cloud_${region}_org_`;- const existingTenantIdsInRegion = currentMemberships- .map((m) => m.tenant.externalId)- .filter((id) => id?.startsWith(regionPrefix));-- const targetTenantIds: string[] = user.organizations.map((org) =>- generateTenantExternalId(org.id, region),- );-- const toRemove = existingTenantIdsInRegion.filter(- (id) => !targetTenantIds.includes(id),- );- const toAdd = targetTenantIds.filter(- (id) => !existingTenantIdsInRegion.includes(id),- );-- if (toRemove.length) {- const r = await client.removeCustomerFromTenants({- customerIdentifier: { emailAddress: email },- tenantIdentifiers: toRemove.map((externalId) => ({ externalId })),- });- if (r.error)- logger.error(- "removeCustomerFromTenants failed",- describeSdkError(r.error),- );- }-- if (toAdd.length) {- const r = await client.addCustomerToTenants({- customerIdentifier: { emailAddress: email },- tenantIdentifiers: toAdd.map((externalId) => ({ externalId })),- });- if (r.error)- logger.error("addCustomerToTenants failed", describeSdkError(r.error));- }-}--// ===== Thread field mapping (domain → Plain fields) =====-const THREAD_FIELDS = {- messageType: "message_type",- severity: "severity",- topic: "topic",- topicOperationsSubtype: "operations_subtype",- topicProductFeaturesSubtype: "product_features_subtype",- integrationType: "integration_type",- url: "url",-} as const;--function buildThreadFields(input: {- messageType: string;- severity: string;- topLevel: "Operations" | "Product Features";- subtype: string;- url?: string;- integrationType?: string;-}) {- const enumFields = [- {- key: THREAD_FIELDS.messageType,- type: ThreadFieldSchemaType.Enum,- stringValue: input.messageType,- },- {- key: THREAD_FIELDS.severity,- type: ThreadFieldSchemaType.Enum,- stringValue: input.severity,- },- {- key: THREAD_FIELDS.topic,- type: ThreadFieldSchemaType.Enum,- stringValue: input.topLevel,- },- ...(input.topLevel === "Operations" && THREAD_FIELDS.topicOperationsSubtype- ? [- {- key: THREAD_FIELDS.topicOperationsSubtype,- type: ThreadFieldSchemaType.Enum,- stringValue: input.subtype,- } as const,- ]- : []),- ...(input.topLevel === "Product Features" &&- THREAD_FIELDS.topicProductFeaturesSubtype- ? [- {- key: THREAD_FIELDS.topicProductFeaturesSubtype,- type: ThreadFieldSchemaType.Enum,- stringValue: input.subtype,- } as const,- ]- : []),- ];-- const textFields = [- input.url && {- key: THREAD_FIELDS.url,- type: ThreadFieldSchemaType.String,- stringValue: input.url,- },- input.integrationType && {- key: THREAD_FIELDS.integrationType,- type: ThreadFieldSchemaType.String,- stringValue: input.integrationType,- },- ].filter(Boolean) as {- key: string;- type: ThreadFieldSchemaType;- stringValue?: string;- }[];-- return [...enumFields, ...textFields];-}--// ===== Threads =====-export async function createSupportThread(- ctx: PlainCtx,- input: {- email: string;- title: string;- message: string;- messageType: string;- severity: string;- topicTopLevel: "Operations" | "Product Features";- topicSubtype: string;- url?: string;- integrationType?: string;- attachmentIds?: string[];- tenantExternalId?: string;- },-): Promise<CreateSupportThreadResult> {- const { client } = ctx;-- const components = [{ componentText: { text: input.message } }];-- const threadFields = buildThreadFields({- messageType: input.messageType,- severity: input.severity,- topLevel: input.topicTopLevel,- subtype: input.topicSubtype,- url: input.url,- integrationType: input.integrationType,- });-- const attachmentIds = input.attachmentIds ?? [];-- // Try WITH threadFields- const createdWithFields = await client.createThread({- title: input.title,- customerIdentifier: { emailAddress: input.email },- components,- threadFields,- tenantIdentifier: input.tenantExternalId- ? { externalId: input.tenantExternalId }- : undefined,- attachmentIds: attachmentIds.length ? attachmentIds : undefined,- });-- if (createdWithFields.error) {- logger.error(- "createThread with threadFields failed — retrying without threadFields",- describeSdkError(createdWithFields.error),- );-- // Retry WITHOUT threadFields- const retry = await client.createThread({- title: input.title,- customerIdentifier: { emailAddress: input.email },- components,- tenantIdentifier: input.tenantExternalId- ? { externalId: input.tenantExternalId }- : undefined,- attachmentIds: attachmentIds.length ? attachmentIds : undefined,- });-- const thread = unwrap("createThread (retry without threadFields)", retry); // throws on error- const createdAt =- thread.createdAt?.__typename === "DateTime"- ? thread.createdAt.iso8601- : undefined;-- return {- threadId: thread.id,- status: thread.status,- createdAt,- createdWithThreadFields: false,- };- }-- const thread = unwrap("createThread", createdWithFields); // throws on error- const createdAt =- thread.createdAt?.__typename === "DateTime"- ? thread.createdAt.iso8601- : undefined;-- return {- threadId: thread.id,- status: thread.status,- createdAt,- createdWithThreadFields: true,- };-}--// ===== Events (best-effort logging on failure) =====-export async function createThreadEvent(- ctx: PlainCtx,- input: {- threadId: string;- title: string;- components: EventComponentInput[];- externalId?: string;- },-) {- const { client } = ctx;- const res = await client.createThreadEvent({- title: input.title,- threadId: input.threadId,- components: input.components,- externalId: input.externalId,- });-- if (res.error) {- logger.error("createThreadEvent failed", describeSdkError(res.error));- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Plain Client: createThreadEvent failed",- cause: 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));- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Plain Client: replyToThread failed",- cause: 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;- message?: 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,- description: input.message,- });-- 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,- description: input.message,- });-- 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,- };-}diff --git a/web/src/features/support-chat/plain/plainConstants.ts b/web/src/features/support-chat/plain/plainConstants.tsdeleted file mode 100644index c1a7ebfc7b..0000000000--- a/web/src/features/support-chat/plain/plainConstants.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * Client-safe constants for Plain API integration- * These can be safely imported in both client and server code- */--/**- * Maximum file size allowed by Plain API for attachments- * This is enforced by Plain's API, so we must match it on client and server- */-export const PLAIN_MAX_FILE_SIZE_BYTES = 6 * 1024 * 1024; // 6MBdiff --git a/web/src/features/support-chat/pylon/pylonConstants.ts b/web/src/features/support-chat/pylon/pylonConstants.tsnew file mode 100644index 0000000000..2e70d9e3c6--- /dev/null+++ b/web/src/features/support-chat/pylon/pylonConstants.ts@@ -0,0 +1,11 @@+/**+ * Client-safe constants for the Pylon support integration.+ * These can be safely imported in both client and server code.+ */++/**+ * Maximum file size allowed for support attachments uploaded to Pylon.+ * Kept in sync with the limit enforced by the+ * `/api/support/upload-attachments` endpoint.+ */+export const PYLON_MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10MBdiff --git a/web/src/features/support-chat/trpc/plainRouter.ts b/web/src/features/support-chat/trpc/supportRouter.tssimilarity index 57%rename from web/src/features/support-chat/trpc/plainRouter.tsrename to web/src/features/support-chat/trpc/supportRouter.tsindex 29a5a3483e..f9f8ccd86f 100644--- a/web/src/features/support-chat/trpc/plainRouter.ts+++ b/web/src/features/support-chat/trpc/supportRouter.ts@@ -1,4 +1,4 @@-// trpc/plainRouter.ts+// trpc/supportRouter.tsimport {createTRPCRouter,authenticatedProcedure,@@ -17,7 +17,6 @@ import {TopicGroups,} from "../formConstants";-import { buildPlainEventSupportRequestMetadataComponents } from "../plain/events/supportRequestMetadataEvent";import {createPylonIssue,buildPylonIssueBodyHtml,@@ -29,20 +28,6 @@ import {mapMessageTypeToPylonQuestionType,} from "../pylon/pylonClient";-import {- initPlain,- ensureCustomer,- createAttachmentUploadUrls,- createThread as plainCreateSupportThread,- createThreadEvent,- generateTenantExternalId,- syncTenantsAndTiers,- syncCustomerTenantMemberships,- type SessionUser,- type Organization,-} from "../plain/plainClient";-import { PLAIN_MAX_FILE_SIZE_BYTES } from "../plain/plainConstants";-// =========================// Input Schemas// =========================@@ -56,40 +41,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 (Plain) */- attachmentIds: z.array(z.string()).optional(),/** URLs of attachments already uploaded to Pylon */pylonAttachmentUrls: z.array(z.url()).optional(),});-const PrepareAttachmentUploadsInput = z.object({- files: z- .array(- z.object({- fileName: z.string().min(1),- fileSizeBytes: z.number().int().positive(),- }),- )- .max(- 5,- `Maximum 5 files allowed (each ≤ ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB)`,- )- .refine(- (files) =>- files.every((f) => f.fileSizeBytes <= PLAIN_MAX_FILE_SIZE_BYTES),- {- message: `Each file must be ≤ ${(PLAIN_MAX_FILE_SIZE_BYTES / (1024 * 1024)).toFixed(0)}MB`,- },- )- .refine(- (files) =>- files.reduce((sum, f) => sum + f.fileSizeBytes, 0) <= 50 * 1024 * 1024,- { message: "Total attachment size must be ≤ 50MB" },- )- .optional()- .default([]),-});-// =========================// Local domain helpers// =========================@@ -103,9 +58,19 @@ function splitTopic(topic: z.infer<typeof TopicSchema>): {return { topLevel: "Product Features", subtype: topic };}+type SessionUser = {+ organizations: Organization[];+};++type Organization = {+ id: string;+ plan?: string;+ projects?: { id: string }[];+};+function deriveOrganizationFromProject(user: SessionUser, projectId?: string) {if (!projectId || !Array.isArray(user.organizations)) return undefined;- for (const org of user.organizations as Organization[]) {+ for (const org of user.organizations) {if (org.projects?.some((p) => p.id === projectId)) return org;}return undefined;@@ -114,46 +79,12 @@ function deriveOrganizationFromProject(user: SessionUser, projectId?: string) {// =========================/** Router */// =========================-export const plainRouter = createTRPCRouter({- /**- * Prepare presigned S3 upload forms for attachments.- * - Ensures customer exists (returns customerId)- * - Returns uploadFormUrl + uploadFormData + attachmentId per file- */- prepareAttachmentUploads: authenticatedProcedure- .input(PrepareAttachmentUploadsInput)- .mutation(async ({ ctx, input }) => {- const email = ctx.session.user.email;- const fullName = getFullName(ctx.session.user);- if (!email) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "User email required to prepare attachment uploads.",- });- }-- const plain = initPlain({ apiKey: env.PLAIN_API_KEY });- const customerId = await ensureCustomer(plain, { email, fullName });- const uploads = await createAttachmentUploadUrls(- plain,- customerId,- input.files,- );-- return {- customerId,- uploads,- };- }),-+export const supportRouter = createTRPCRouter({/**- * Creates a thread after synchronously ensuring:- * (1) Upsert customer- * (2) Ensure tenants/tiers & sync tenant memberships- * (3) Create thread WITH threadFields (+ attachments if provided)- * - If this fails, retry creating the thread WITHOUT threadFields (attachments still included)- * (4) Fire-and-forget: create a compact "Support request metadata" thread event- * using the new UI builder (Url, Organization ID, Project ID, Version, Plan, Cloud Region, Browser Metadata).+ * Creates a support thread in Pylon.+ * (1) Resolve the organization/plan from the provided org or project+ * (2) Create the issue in Pylon (best-effort, blocking)+ * (3) Update the Pylon account's customer tier custom field (best-effort)*/createSupportThread: authenticatedProcedure.input(CreateSupportThreadInput)@@ -172,7 +103,6 @@ export const plainRouter = createTRPCRouter({projectId: input.projectId,region: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,plan: undefined as string | undefined,- tenantExternalId: undefined as string | undefined,};// Validate that, if organizationId is provided the user has access to it@@ -218,82 +148,19 @@ export const plainRouter = createTRPCRouter({currentSupportRequestContext.organizationId = organization.id;}- if (- currentSupportRequestContext.organizationId &&- currentSupportRequestContext.region- ) {- currentSupportRequestContext.tenantExternalId =- generateTenantExternalId(- currentSupportRequestContext.organizationId,- currentSupportRequestContext.region,- );- }-- const plain = initPlain({ apiKey: env.PLAIN_API_KEY });-- // (1) Ensure customer- const customerId = await ensureCustomer(plain, { email, fullName });-- // (2) Ensure tenants/tiers and sync memberships — best-effort- const demoOrgId = env.NEXT_PUBLIC_DEMO_ORG_ID;- if (currentSupportRequestContext.region) {- await syncTenantsAndTiers(plain, {- user: ctx.session.user as SessionUser,- region: currentSupportRequestContext.region,- demoOrgId,- });- await syncCustomerTenantMemberships(plain, {- email,- customerId,- user: ctx.session.user as SessionUser,- region: currentSupportRequestContext.region,- });- }-const { topLevel, subtype } = splitTopic(input.topic);- // (3) Create thread (no initial message; with fallback inside)// Generate a short unique identifier to prevent Gmail from merging threadsconst uniqueId = nanoid(5);- const { threadId, createdAt, status, createdWithThreadFields } =- await plainCreateSupportThread(plain, {- email,- title: `[${uniqueId}] ${input.messageType}: ${input.topic} • ${topLevel}/${subtype}`,- messageType: input.messageType,- severity: input.severity,- topicTopLevel: topLevel,- topicSubtype: subtype,- url: input.url,- tenantExternalId: currentSupportRequestContext.tenantExternalId,- integrationType: input.integrationType,- });-- 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}`,- });- } catch {- // best-effort; errors are logged in helpers- }-- // (5) Create issue in Pylon (best-effort, blocking)+ // Create issue in Pylon (best-effort, blocking)let pylonIssueFailed = false;- if (env.PYLON_API_KEY) {+ if (!env.PYLON_API_KEY) {+ pylonIssueFailed = true;+ logger.error(+ "Pylon integration is not configured (PYLON_API_KEY missing); cannot create support thread",+ );+ } else {try {const pylonTitle = `[${uniqueId}] ${input.messageType}: ${input.topic} • ${topLevel}/${subtype}`;const pylonBodyHtml = buildPylonIssueBodyHtml({@@ -375,17 +242,11 @@ export const plainRouter = createTRPCRouter({}} catch (e) {pylonIssueFailed = true;- logger.error("Pylon issue creation failed (best-effort)", e);+ logger.error("Pylon issue creation failed", e);}}return {- threadId,- customerId,- status,- 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.tsindex 6924ff2fed..6635b84d31 100644--- a/web/src/pages/api/support/upload-attachments.ts+++ b/web/src/pages/api/support/upload-attachments.ts@@ -3,6 +3,7 @@ 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";+import { PYLON_MAX_FILE_SIZE_BYTES } from "@/src/features/support-chat/pylon/pylonConstants";export const config = {api: {@@ -24,7 +25,6 @@ type RequestBody = {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,@@ -70,9 +70,9 @@ export default async function handler(const buffer = Buffer.from(file.fileBase64, "base64");- if (buffer.length > MAX_FILE_SIZE_BYTES) {+ if (buffer.length > PYLON_MAX_FILE_SIZE_BYTES) {return res.status(400).json({- error: `File "${file.fileName}" exceeds maximum size of ${MAX_FILE_SIZE_BYTES / (1024 * 1024)}MB`,+ error: `File "${file.fileName}" exceeds maximum size of ${PYLON_MAX_FILE_SIZE_BYTES / (1024 * 1024)}MB`,});}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 4be97163dd..eb26671e2f 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -51,7 +51,7 @@ import { automationsRouter } from "@/src/features/automations/server/router";import { monitorsRouter } from "@/src/server/api/routers/monitors";import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";import { slackRouter } from "@/src/features/slack/server/router";-import { plainRouter } from "@/src/features/support-chat/trpc/plainRouter";+import { supportRouter } from "@/src/features/support-chat/trpc/supportRouter";import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/annotationQueueAssignmentsRouter";import { surveysRouter } from "@/src/server/api/routers/surveys";import { naturalLanguageFilterRouter } from "@/src/features/natural-language-filters/server/router";@@ -117,7 +117,7 @@ export const appRouter = createTRPCRouter({automations: automationsRouter,monitors: monitorsRouter,slack: slackRouter,- plainRouter: plainRouter,+ supportRouter: supportRouter,surveys: surveysRouter,naturalLanguageFilters: naturalLanguageFilterRouter,notificationPreferences: notificationPreferencesRouter,