🪢 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): Extract presentational `SupportForm` (#16947)
Ben Bachemc98a624baa11
diff --git a/web/src/features/support-chat/ConnectedSupportFormSection.tsx b/web/src/features/support-chat/ConnectedSupportFormSection.tsxnew file mode 100644index 0000000000..32b28b02cd--- /dev/null+++ b/web/src/features/support-chat/ConnectedSupportFormSection.tsx@@ -0,0 +1,138 @@+"use client";++import { api } from "@/src/utils/api";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";+import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";+import { isEnterpriseSupportPlan } from "./formConstants";+import {+ SupportForm,+ type SupportFormSubmitStatus,+ type SupportFormValues,+} from "./SupportForm";++export function ConnectedSupportFormSection({+ onCancel,+ onSuccess,+}: {+ onCancel: () => void;+ onSuccess: () => void;+}) {+ const { organization, project } = useQueryProjectOrOrganization();+ const { initialTopic } = useSupportDrawer();+ const showV4MigrationTopic = useV4UpgradeUiEnabled(project?.id);+ // The support drawer is mounted globally and reachable from pages without an+ // org/project in the URL (home, setup, onboarding, account settings), where+ // `organization` is null. Without an org context the plan is unknown, so+ // Severity 1/2 are gated there. The server applies the same rule.+ const canSelectHighSeverity = isEnterpriseSupportPlan(organization?.plan);++ const createSupportThread =+ api.supportRouter.createSupportThread.useMutation();++ 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 handleSubmit = async (+ values: SupportFormValues,+ files: File[],+ ): Promise<SupportFormSubmitStatus> => {+ // Upload attachments to Pylon. This is the only attachment path, so+ // do NOT swallow failures: let them propagate to SupportForm+ // (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.length) {+ pylonAttachmentUrls = await uploadFilesToPylon(files);+ }++ const data = await createSupportThread.mutateAsync({+ messageType: values.messageType,+ severity: values.severity,+ topic: values.topic,+ integrationType: values.integrationType,+ message: values.message,+ url: window.location.href,+ organizationId: organization?.id,+ projectId: project?.id,+ browserMetadata: {+ userAgent: navigator.userAgent,+ platform:+ (+ navigator as Navigator & {+ userAgentData?: { platform?: string };+ }+ ).userAgentData?.platform ?? undefined,+ language: navigator.language,+ viewport: { w: window.innerWidth, h: window.innerHeight },+ },+ pylonAttachmentUrls,+ });++ // 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 "kept";+ }++ return "success";+ };++ return (+ <div className="mt-1 flex flex-col gap-3">+ <div className="flex items-center gap-2 text-base font-bold">+ E-Mail a Support Engineer+ </div>+ <p className="text-muted-foreground text-sm">+ Details speed things up. The clearer your request, the quicker you get+ the answer you need.+ </p>+ <SupportForm+ canSelectHighSeverity={canSelectHighSeverity}+ initialTopic={initialTopic ?? ""}+ showV4MigrationTopic={showV4MigrationTopic}+ onCancel={onCancel}+ onSuccess={onSuccess}+ onSubmit={handleSubmit}+ onFileError={(message) =>+ showErrorToast("File Upload Error", message, "WARNING")+ }+ />+ </div>+ );+}diff --git a/web/src/features/support-chat/SupportDrawer.tsx b/web/src/features/support-chat/SupportDrawer.tsxindex a9c383922f..0dfa584d85 100644--- a/web/src/features/support-chat/SupportDrawer.tsx+++ b/web/src/features/support-chat/SupportDrawer.tsx@@ -13,7 +13,7 @@ import {} from "@/src/components/ui/breadcrumb";import { IntroSection } from "@/src/features/support-chat/IntroSection";import { SuccessSection } from "@/src/features/support-chat/SuccessSection";-import { SupportFormSection } from "@/src/features/support-chat/SupportFormSection";+import { ConnectedSupportFormSection } from "@/src/features/support-chat/ConnectedSupportFormSection";import { cn } from "@/src/utils/tailwind";export const SupportDrawer = (props: {@@ -100,7 +100,7 @@ const SupportDrawerContent = ({<IntroSection onStartForm={() => setCurrentMode("form")} />)}{currentMode === "form" && (- <SupportFormSection+ <ConnectedSupportFormSectiononSuccess={() => setCurrentMode("success")}onCancel={() => setCurrentMode("intro")}/>diff --git a/web/src/features/support-chat/SupportForm.stories.tsx b/web/src/features/support-chat/SupportForm.stories.tsxnew file mode 100644index 0000000000..166a31c475--- /dev/null+++ b/web/src/features/support-chat/SupportForm.stories.tsx@@ -0,0 +1,169 @@+import { type ComponentProps } from "react";+import { expect, fn, userEvent, within } from "storybook/test";++import preview from "../../../.storybook/preview";+import { SEVERITY_1, SEVERITY_3 } from "./formConstants";+import { SupportForm } from "./SupportForm";++const defaultArgs = {+ canSelectHighSeverity: false,+ initialTopic: "",+ showV4MigrationTopic: false,+ onCancel: fn(),+ onSuccess: fn(),+ onSubmit: fn(async () => "success" as const),+ onFileError: fn(),+} satisfies ComponentProps<typeof SupportForm>;++const LONG_MESSAGE =+ "I need help understanding why my traces are missing spans after the latest deploy.";++const meta = preview.meta({+ component: SupportForm,+});++export const Default = meta.story({+ args: defaultArgs,+});++export const Enterprise = meta.story({+ args: {+ ...defaultArgs,+ canSelectHighSeverity: true,+ },+});++export const WithInitialTopic = meta.story({+ args: {+ ...defaultArgs,+ initialTopic: "Observability",+ },+});++export const WithV4MigrationTopic = meta.story({+ args: {+ ...defaultArgs,+ showV4MigrationTopic: true,+ },+});++async function selectTopic(canvasElement: HTMLElement, topic: string) {+ const body = within(canvasElement.ownerDocument.body);+ const comboboxes = body.getAllByRole("combobox");+ await userEvent.click(comboboxes[1]!);+ await userEvent.click(await body.findByRole("option", { name: topic }));+}++function getMessageField(canvasElement: HTMLElement) {+ return within(canvasElement).getByPlaceholderText(+ /Please explain as fully as possible/,+ );+}++export const WarnsOnShortMessage = meta.story({+ name: "(Test) Warns on short message",+ args: defaultArgs,+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await selectTopic(canvasElement, "Observability");+ await userEvent.type(getMessageField(canvasElement), "Too short");+ await userEvent.click(canvas.getByRole("button", { name: "Submit" }));++ await expect(canvas.getByText(/The message seems short/i)).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: "Submit Anyways" }),+ ).toBeVisible();+ await expect(args.onSubmit).not.toHaveBeenCalled();+ },+});++export const SubmitsRequest = meta.story({+ name: "(Test) Submits request",+ args: {+ ...defaultArgs,+ onSubmit: fn(async () => "success" as const),+ onSuccess: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await selectTopic(canvasElement, "Observability");+ await userEvent.type(getMessageField(canvasElement), LONG_MESSAGE);+ await userEvent.click(canvas.getByRole("button", { name: "Submit" }));++ await expect(args.onSubmit).toHaveBeenCalledWith(+ {+ messageType: "Question",+ severity: SEVERITY_3,+ topic: "Observability",+ message: LONG_MESSAGE,+ integrationType: "",+ },+ [],+ );+ await expect(args.onSuccess).toHaveBeenCalled();+ },+});++export const ConfirmsSeverity1 = meta.story({+ name: "(Test) Confirms severity 1",+ args: {+ ...defaultArgs,+ canSelectHighSeverity: true,+ onSubmit: fn(async () => "success" as const),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(body.getAllByRole("combobox")[0]!);+ await userEvent.click(+ await body.findByRole("option", { name: SEVERITY_1 }),+ );++ await selectTopic(canvasElement, "Observability");+ await userEvent.type(getMessageField(canvasElement), LONG_MESSAGE);+ await userEvent.click(canvas.getByRole("button", { name: "Submit" }));++ const confirmTitle = await body.findByRole("heading", {+ name: "Confirm Severity 1 (Critical Business Impact)",+ });+ await expect(confirmTitle).toBeInTheDocument();+ await expect(args.onSubmit).not.toHaveBeenCalled();++ await userEvent.click(+ await body.findByRole("button", { name: "Confirm & Submit" }),+ );++ await expect(args.onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ severity: SEVERITY_1,+ topic: "Observability",+ message: LONG_MESSAGE,+ }),+ [],+ );+ },+});++export const KeepsFormWhenSubmitIsKept = meta.story({+ name: "(Test) Keeps form when submit is kept",+ args: {+ ...defaultArgs,+ initialTopic: "Observability",+ onSubmit: fn(async () => "kept" as const),+ onSuccess: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await userEvent.type(getMessageField(canvasElement), LONG_MESSAGE);+ await userEvent.click(canvas.getByRole("button", { name: "Submit" }));++ await expect(args.onSubmit).toHaveBeenCalled();+ await expect(args.onSuccess).not.toHaveBeenCalled();+ await expect(getMessageField(canvasElement)).toHaveValue(LONG_MESSAGE);+ await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();+ },+});diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportForm.tsxsimilarity index 79%rename from web/src/features/support-chat/SupportFormSection.tsxrename to web/src/features/support-chat/SupportForm.tsxindex 0b06a46944..ccf87c0267 100644--- a/web/src/features/support-chat/SupportFormSection.tsx+++ b/web/src/features/support-chat/SupportForm.tsx@@ -7,15 +7,16 @@ import {MESSAGE_TYPES,SEVERITIES,SEVERITY_1,+ SEVERITY_2,SEVERITY_3,INTEGRATION_TYPES,TopicGroups,type MessageType,+ type Topic,SupportFormSchema,- isSeverityAllowedForPlan,} from "./formConstants";-import { api, reportNonTrpcError } from "@/src/utils/api";+import { reportNonTrpcError } from "@/src/utils/api";import { Button } from "@/src/components/ui/button";import {@@ -51,20 +52,32 @@ import {SelectValue,} from "@/src/components/ui/select";import { Textarea } from "@/src/components/ui/textarea";-import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";import { useEffect, useState } from "react";import { Dropzone } from "@/src/components/design-system/Dropzone/Dropzone";import { Trash2 } from "lucide-react";-import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { PYLON_MAX_FILE_SIZE_BYTES } from "./pylon/pylonConstants";import Spinner from "@/src/components/design-system/Spinner/Spinner";-import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";-import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";/** Make RHF generics match the resolver (Zod defaults => input can be undefined) */type SupportFormInput = z.input<typeof SupportFormSchema>;-type SupportFormValues = z.output<typeof SupportFormSchema>;+export type SupportFormValues = z.output<typeof SupportFormSchema>;++/** `kept` leaves the draft intact after an expected, already-surfaced failure. */+export type SupportFormSubmitStatus = "success" | "kept";++export type SupportFormProps = {+ canSelectHighSeverity: boolean;+ initialTopic: Topic | "";+ showV4MigrationTopic: boolean;+ onCancel: () => void;+ onSuccess: () => void;+ onSubmit: (+ values: SupportFormValues,+ files: File[],+ ) => Promise<SupportFormSubmitStatus>;+ onFileError: (message: string) => void;+};/*** File upload constraints - single source of truth for validation@@ -169,21 +182,25 @@ function formatFileError(error: Error): string {return error.message || "File upload failed. Please try again.";}-export function SupportFormSection({+function isSeveritySelectable(+ severity: string,+ canSelectHighSeverity: boolean,+): boolean {+ if (severity === SEVERITY_1 || severity === SEVERITY_2) {+ return canSelectHighSeverity;+ }+ return true;+}++export function SupportForm({+ canSelectHighSeverity,+ initialTopic,+ showV4MigrationTopic,onCancel,onSuccess,-}: {- onCancel: () => void;- onSuccess: () => void;-}) {- const { organization, project } = useQueryProjectOrOrganization();-- // The support drawer is mounted globally and reachable from pages without an- // org/project in the URL (home, setup, onboarding, account settings), where- // `organization` is null. Without an org context the plan is unknown, so- // Severity 1/2 are gated there. The server applies the same rule.- const effectivePlan = organization?.plan;-+ onSubmit,+ onFileError,+}: SupportFormProps) {// Tracks whether we've already warned about a short messageconst [warnedShortOnce, setWarnedShortOnce] = useState(false);@@ -197,10 +214,8 @@ export function SupportFormSection({// confirmation step.const [sev1ConfirmOpen, setSev1ConfirmOpen] = useState(false);- const { initialTopic } = useSupportDrawer();- const v4UpgradeUiEnabled = useV4UpgradeUiEnabled(project?.id);const productFeatureTopics = TopicGroups["Product Features"].filter(- (topic) => topic !== "V4 Migration" || v4UpgradeUiEnabled,+ (topic) => topic !== "V4 Migration" || showV4MigrationTopic,);const form = useForm<SupportFormInput>({@@ -208,7 +223,7 @@ export function SupportFormSection({defaultValues: {messageType: "Question" as MessageType,severity: SEVERITY_3,- topic: initialTopic ?? "",+ topic: initialTopic,message: "",integrationType: "",},@@ -217,7 +232,7 @@ export function SupportFormSection({const selectedTopic = form.watch("topic");const isProductFeatureTopic = TopicGroups["Product Features"].includes(- selectedTopic as any,+ selectedTopic as (typeof TopicGroups)["Product Features"][number],);// The drawer is globally mounted, so a severity selected under one org's@@ -228,72 +243,13 @@ export function SupportFormSection({useEffect(() => {if (selectedSeverity &&- !isSeverityAllowedForPlan(selectedSeverity, effectivePlan)+ !isSeveritySelectable(selectedSeverity, canSelectHighSeverity)) {form.setValue("severity", SEVERITY_3);}- }, [selectedSeverity, effectivePlan, form]);-- 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: SEVERITY_3,- topic: "",- message: "",- });- setWarnedShortOnce(false);- setFiles(undefined);- onSuccess();- },- onSettled: () => setIsSubmittingLocal(false),- },- );-- 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.",- );- }+ }, [selectedSeverity, canSelectHighSeverity, form]);- const body = (await res.json()) as { attachment_urls: string[] };- return body.attachment_urls;- }-- const onSubmit = async (values: SupportFormInput) => {+ const handleFormSubmit = async (values: SupportFormInput) => {const parsed: SupportFormValues = SupportFormSchema.parse(values);const msgLen = (parsed.message ?? "").trim().length;@@ -327,45 +283,31 @@ export function SupportFormSection({throw new Error(validation.error);}- // 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) {- pylonAttachmentUrls = await uploadFilesToPylon(files);+ const status = await onSubmit(parsed, files ?? []);+ if (status === "kept") {+ return;}- // 2) Create the support thread in Pylon- await createSupportThread.mutateAsync({- messageType: parsed.messageType,- severity: parsed.severity,- topic: parsed.topic as any,- integrationType: parsed.integrationType,- message: parsed.message,- url: window.location.href,- organizationId: organization?.id,- projectId: project?.id,- browserMetadata: {- userAgent: navigator.userAgent,- platform:- (- navigator as Navigator & {- userAgentData?: { platform?: string };- }- ).userAgentData?.platform ?? undefined,- language: navigator.language,- viewport: { w: window.innerWidth, h: window.innerHeight },- },- pylonAttachmentUrls,+ form.reset({+ messageType: "Question",+ severity: SEVERITY_3,+ topic: "",+ message: "",});- } catch (err: any) {+ setWarnedShortOnce(false);+ setFiles(undefined);+ onSuccess();+ } catch (err: unknown) {reportNonTrpcError(err, "support");- setIsSubmittingLocal(false);form.setError("message", {type: "manual",- message: err?.message ?? "Failed to submit support request.",+ message:+ err instanceof Error+ ? err.message+ : "Failed to submit support request.",});+ } finally {+ setIsSubmittingLocal(false);}};@@ -373,18 +315,10 @@ export function SupportFormSection({warnedShortOnce && (form.getValues("message") ?? "").trim().length < 50;return (- <div className="mt-1 flex flex-col gap-3">- <div className="flex items-center gap-2 text-base font-bold">- E-Mail a Support Engineer- </div>- <p className="text-muted-foreground text-sm">- Details speed things up. The clearer your request, the quicker you get- the answer you need.- </p>-+ <><Form {...form}><form- onSubmit={form.handleSubmit(onSubmit)}+ onSubmit={form.handleSubmit(handleFormSubmit)}className="flex flex-col gap-4">{/* Message Type */}@@ -438,7 +372,7 @@ export function SupportFormSection({</SelectTrigger><SelectContent>{SEVERITIES.map((s) =>- isSeverityAllowedForPlan(s, effectivePlan) ? (+ isSeveritySelectable(s, canSelectHighSeverity) ? (<SelectItem key={s} value={s}>{s}</SelectItem>@@ -599,12 +533,7 @@ export function SupportFormSection({})}onError={(error) => {- const userMessage = formatFileError(error);- showErrorToast(- "File Upload Error",- userMessage,- "WARNING",- );+ onFileError(formatFileError(error));}}src={files}variant="compact"@@ -706,6 +635,6 @@ export function SupportFormSection({</AlertDialogFooter></AlertDialogContent></AlertDialog>- </div>+ </>);}