Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(support): revamp in-app support experience (#8875)

Michael FrΓΆhlich43a98141a84a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6e5e13b63a..d45ad9fe3d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -58,7 +58,7 @@ importers:
next-auth:
specifier: ^4.24.11
zod:
specifier: ^3.25.62
version: 3.25.62
@@ -238,7 +238,7 @@ importers:
version: 4.1.1
next-auth:
specifier: ^4.24.11
nodemailer:
specifier: ^6.9.15
version: 6.9.15
@@ -626,7 +626,7 @@ importers:
next-auth:
specifier: ^4.24.11
next-query-params:
specifier: ^5.0.1
@@ -663,6 +663,9 @@ importers:
react-dom:
specifier: 18.2.0
version: 18.2.0([email protected])
+ react-dropzone:
+ specifier: ^14.3.8
+ version: 14.3.8([email protected])
react-grid-layout:
specifier: ^1.5.1
@@ -6139,6 +6142,10 @@ packages:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
+ resolution: {integrity: sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-BaENR2+zBZ8xXhM4pUaKUxlVdxZ0EZhjvbopwnXmxRUfqDmwSpC2lAi/QXvx7NRdPCo1WKEcEF6mV64si1z4Ew==}
engines: {node: ^10 || ^12 || >=14}
@@ -7791,6 +7798,10 @@ packages:
resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}
engines: {node: ^10.12.0 || >=12.0.0}
+ resolution: {integrity: sha512-QgXo+mXTe8ljeqUFaX3QVHc5osSItJ/Km+xpocx0aSqWGMSCf6qYs/VnzZgS864Pjn5iceMRFigeAV7AfTlaig==}
+ engines: {node: '>= 12'}
+
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'}
@@ -10551,6 +10562,12 @@ packages:
react: '>= 16.3.0'
react-dom: '>= 16.3.0'
+ resolution: {integrity: sha512-sBgODnq+lcA4P296DY4wacOZz3JFpD99fp+hb//iBO2HHnyeZU3FwWyXJ6salNpqQdsZrgMrotuko/BdJMV8Ug==}
+ engines: {node: '>= 10.13'}
+ peerDependencies:
+ react: '>= 16.8 || 18.0.0'
+
resolution: {integrity: sha512-4Fr+kKMk0+m1HL/BWfHxi/lRuaOmDNNKQDcu7m12+NEYcen20wIuZFo789u3qWCyvUsNUxCiyf0eKq4WiJSNYw==}
peerDependencies:
@@ -15244,7 +15261,7 @@ snapshots:
dependencies:
dependencies:
@@ -18643,7 +18660,7 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
+ eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
@@ -19140,6 +19157,8 @@ snapshots:
+
dependencies:
browserslist: 4.23.0
@@ -20607,7 +20626,7 @@ snapshots:
eslint-plugin-turbo: 2.5.6([email protected])([email protected])
turbo: 2.5.6
dependencies:
@@ -20698,7 +20717,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -20725,7 +20744,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.0
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -21166,6 +21185,10 @@ snapshots:
dependencies:
flat-cache: 3.2.0
+ dependencies:
+ tslib: 2.8.1
+
dependencies:
to-regex-range: 5.0.1
@@ -23414,7 +23437,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
dependencies:
'@babel/runtime': 7.26.0
'@panva/hkdf': 1.1.1
@@ -24370,6 +24393,13 @@ snapshots:
react: 18.2.0
react-dom: 18.2.0([email protected])
+ dependencies:
+ attr-accept: 2.2.5
+ file-selector: 2.1.2
+ prop-types: 15.8.1
+ react: 18.2.0
+
dependencies:
clsx: 2.1.1
diff --git a/web/next.config.mjs b/web/next.config.mjs
index 45a6e3bf29..8aa11465ef 100644
--- a/web/next.config.mjs
+++ b/web/next.config.mjs
@@ -13,7 +13,7 @@ import bundleAnalyzer from "@next/bundle-analyzer";
*/
const cspHeader = `
default-src 'self' https://*.langfuse.com https://*.langfuse.dev https://*.posthog.com https://*.sentry.io;
- script-src 'self' 'unsafe-eval' 'unsafe-inline' https://*.langfuse.com https://*.langfuse.dev https://challenges.cloudflare.com https://*.sentry.io https://static.cloudflareinsights.com https://*.stripe.com https://uptime.betterstack.com https://chat.cdn-plain.com;
+ script-src 'self' 'unsafe-eval' 'unsafe-inline' https://*.langfuse.com https://*.langfuse.dev https://challenges.cloudflare.com https://*.sentry.io https://static.cloudflareinsights.com https://*.stripe.com https://uptime.betterstack.com;
style-src 'self' 'unsafe-inline' https://uptime.betterstack.com https://fonts.googleapis.com;
img-src 'self' https: blob: data: http://localhost:* https://prod-uk-services-workspac-workspacefilespublicbuck-vs4gjqpqjkh6.s3.amazonaws.com https://prod-uk-services-attachm-attachmentsbucket28b3ccf-uwfssb4vt2us.s3.eu-west-2.amazonaws.com https://i0.wp.com;
font-src 'self';
diff --git a/web/package.json b/web/package.json
index f892916438..8c1a6021d5 100644
--- a/web/package.json
+++ b/web/package.json
@@ -133,6 +133,7 @@
"react": "18.2.0",
"react-day-picker": "^8.10.1",
"react-dom": "18.2.0",
+ "react-dropzone": "^14.3.8",
"react-grid-layout": "^1.5.1",
"react-hook-form": "^7.57.0",
"react-icons": "^5.5.0",
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsx
index be7c9eac21..26ab5d24fc 100644
--- a/web/src/components/layouts/layout.tsx
+++ b/web/src/components/layouts/layout.tsx
@@ -16,6 +16,21 @@ import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizati
import { SidebarInset, SidebarProvider } from "@/src/components/ui/sidebar";
import { AppSidebar } from "@/src/components/nav/app-sidebar";
import { CommandMenu } from "@/src/features/command-k-menu/CommandMenu";
+import { SupportDrawer } from "@/src/features/support-chat/SupportDrawer";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/src/components/ui/resizable";
+import {
+ Drawer,
+ DrawerContent,
+ DrawerDescription,
+ DrawerHeader,
+ DrawerTitle,
+} from "@/src/components/ui/drawer";
+import { useMediaQuery } from "react-responsive";
import {
processNavigation,
type NavigationItem,
@@ -328,7 +343,7 @@ export default function Layout(props: PropsWithChildren) {
}}
/>
<SidebarInset className="h-dvh max-w-full md:peer-data-[state=collapsed]:w-[calc(100vw-var(--sidebar-width-icon))] md:peer-data-[state=expanded]:w-[calc(100vw-var(--sidebar-width))]">
- <main className="h-full">{props.children}</main>
+ <ResizableContent>{props.children}</ResizableContent>
<Toaster visibleToasts={1} />
<CommandMenu mainNavigation={navigation} />
</SidebarInset>
@@ -337,3 +352,112 @@ export default function Layout(props: PropsWithChildren) {
</>
);
}
+
+/** Resizable content for support drawer on the right side of the screen (desktop).
+ * On mobile, renders a Drawer instead of a resizable sidebar.
+ */
+export function ResizableContent({ children }: PropsWithChildren) {
+ const { open, setOpen } = useSupportDrawer();
+ const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });
+
+ // Keep cookie-based layout only for desktop
+ const COOKIE_KEY = "react-resizable-panels:layout:supportDrawer";
+ const [mounted, setMounted] = useState(false);
+ const [defaultLayout, setDefaultLayout] = useState<number[] | undefined>(
+ undefined,
+ );
+
+ useEffect(() => {
+ setMounted(true);
+ if (!isDesktop /* || !open */) return; // no layout restore needed on mobile (and you can also gate on open if you want)
+ try {
+ if (typeof document !== "undefined") {
+ const match = document.cookie.match(
+ new RegExp(
+ "(?:^|; )" +
+ COOKIE_KEY.replace(/([.$?*|{}()\[\]\\\/\+^])/g, "\\$1") +
+ "=([^;]*)",
+ ),
+ );
+ if (match?.[1]) {
+ const parsed = JSON.parse(decodeURIComponent(match[1]));
+ if (Array.isArray(parsed) && parsed.length === 2) {
+ setDefaultLayout(parsed as number[]);
+ }
+ }
+ }
+ } catch {
+ // ignore cookie parse errors
+ }
+ }, [isDesktop /*, open */]);
+
+ const onLayout = (sizes: number[]) => {
+ if (!isDesktop) return;
+ try {
+ document.cookie = `${COOKIE_KEY}=${encodeURIComponent(
+ JSON.stringify(sizes),
+ )}; path=/; max-age=${60 * 60 * 24 * 365}`;
+ } catch {
+ // ignore cookie write errors
+ }
+ };
+
+ // MOBILE: main + overlay drawer
+ if (!isDesktop) {
+ return (
+ <>
+ <main className="h-full flex-1">{children}</main>
+
+ <Drawer open={open} onOpenChange={setOpen} forceDirection="bottom">
+ <DrawerContent
+ id="support-drawer"
+ className="inset-x-0 bottom-0 top-10 min-h-full"
+ size="full"
+ >
+ <DrawerHeader className="absolute inset-x-0 top-0 p-0 text-left">
+ <div className="flex w-full items-center justify-center pt-3">
+ <div className="h-2 w-20 rounded-full bg-muted" />
+ </div>
+ {/* sr-only for screen readers and accessibility */}
+ <DrawerTitle className="sr-only">Support</DrawerTitle>
+ <DrawerDescription className="sr-only">
+ A list of resources and options to help you with your questions.
+ </DrawerDescription>
+ </DrawerHeader>
+ <div className="mt-4 max-h-full">
+ <SupportDrawer showCloseButton={false} className="h-full pb-20" />
+ </div>
+ </DrawerContent>
+ </Drawer>
+ </>
+ );
+ }
+
+ // πŸ‘‰ DESKTOP: if drawer isn't open, render only the main content (like before)
+ if (isDesktop && !open) {
+ return <main className="h-full flex-1">{children}</main>;
+ }
+
+ if (!mounted) {
+ return <main className="h-full flex-1">{children}</main>;
+ }
+
+ const mainDefault = defaultLayout?.[0] ?? 70;
+ const drawerDefault = defaultLayout?.[1] ?? 30;
+
+ return (
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="flex h-full w-full"
+ onLayout={onLayout}
+ >
+ <ResizablePanel defaultSize={mainDefault} minSize={30}>
+ <main className="h-full w-full">{children}</main>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel defaultSize={drawerDefault} minSize={20} maxSize={60}>
+ <SupportDrawer />
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsx
index fd0eda4b15..d152c094df 100644
--- a/web/src/components/layouts/routes.tsx
+++ b/web/src/components/layouts/routes.tsx
@@ -23,7 +23,7 @@ import { type ReactNode } from "react";
import { type Entitlement } from "@/src/features/entitlements/constants/entitlements";
import { type User } from "next-auth";
import { type OrganizationScope } from "@/src/features/rbac/constants/organizationAccessRights";
-import { SupportMenuDropdown } from "@/src/components/nav/support-menu-dropdown";
+import { SupportButton } from "@/src/components/nav/support-button";
import { SidebarMenuButton } from "@/src/components/ui/sidebar";
import { useCommandMenu } from "@/src/features/command-k-menu/CommandMenuProvider";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -209,7 +209,7 @@ export const ROUTES: Route[] = [
icon: LifeBuoy,
section: RouteSection.Secondary,
pathname: "", // Empty pathname since this is a dropdown
- menuNode: <SupportMenuDropdown />,
+ menuNode: <SupportButton />,
},
];
diff --git a/web/src/components/magicui/rainbow-button.tsx b/web/src/components/magicui/rainbow-button.tsx
new file mode 100644
index 0000000000..5b27c16500
--- /dev/null
+++ b/web/src/components/magicui/rainbow-button.tsx
@@ -0,0 +1,62 @@
+import { cn } from "@/src/utils/tailwind";
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+import React from "react";
+
+interface RainbowButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement> {}
+
+const rainbowButtonVariants = cva(
+ cn(
+ "relative cursor-pointer group transition-all animate-rainbow",
+ "inline-flex items-center justify-center gap-2 shrink-0",
+ "rounded-sm outline-none focus-visible:ring-[3px] aria-invalid:border-destructive",
+ "text-sm font-medium whitespace-nowrap",
+ "disabled:pointer-events-none disabled:opacity-50",
+ "[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0",
+ ),
+ {
+ variants: {
+ variant: {
+ default:
+ "border-0 bg-[linear-gradient(#121213,#121213),linear-gradient(#121213_50%,rgba(18,18,19,0.6)_80%,rgba(18,18,19,0)),linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))] bg-[length:200%] text-primary-foreground [background-clip:padding-box,border-box,border-box] [background-origin:border-box] [border:calc(0.125rem)_solid_transparent] before:absolute before:bottom-[-20%] before:left-1/2 before:z-0 before:h-1/5 before:w-3/5 before:-translate-x-1/2 before:animate-rainbow before:bg-[linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))] before:[filter:blur(0.75rem)] dark:bg-[linear-gradient(#fff,#fff),linear-gradient(#fff_50%,rgba(255,255,255,0.6)_80%,rgba(0,0,0,0)),linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))]",
+ outline:
+ "border border-input border-b-transparent bg-[linear-gradient(#ffffff,#ffffff),linear-gradient(#ffffff_50%,rgba(18,18,19,0.6)_80%,rgba(18,18,19,0)),linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))] bg-[length:200%] text-accent-foreground [background-clip:padding-box,border-box,border-box] [background-origin:border-box] before:absolute before:bottom-[-20%] before:left-1/2 before:z-0 before:h-1/5 before:w-3/5 before:-translate-x-1/2 before:animate-rainbow before:bg-[linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))] before:[filter:blur(0.75rem)] dark:bg-[linear-gradient(#0a0a0a,#0a0a0a),linear-gradient(#0a0a0a_50%,rgba(255,255,255,0.6)_80%,rgba(0,0,0,0)),linear-gradient(90deg,var(--color-1),var(--color-5),var(--color-3),var(--color-4),var(--color-2))]",
+ },
+ size: {
+ default: "h-9 px-4 py-2",
+ sm: "h-8 rounded-xl px-3 text-xs",
+ lg: "h-11 rounded-xl px-8",
+ icon: "size-9",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+interface RainbowButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof rainbowButtonVariants> {
+ asChild?: boolean;
+}
+
+const RainbowButton = React.forwardRef<HTMLButtonElement, RainbowButtonProps>(
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+ return (
+ <Comp
+ data-slot="button"
+ className={cn(rainbowButtonVariants({ variant, size, className }))}
+ ref={ref}
+ {...props}
+ />
+ );
+ },
+);
+
+RainbowButton.displayName = "RainbowButton";
+
+export { RainbowButton, rainbowButtonVariants, type RainbowButtonProps };
diff --git a/web/src/components/nav/support-button.tsx b/web/src/components/nav/support-button.tsx
new file mode 100644
index 0000000000..ee5beaa6e6
--- /dev/null
+++ b/web/src/components/nav/support-button.tsx
@@ -0,0 +1,25 @@
+import { LifeBuoy } from "lucide-react";
+import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+
+export const SupportButton = () => {
+ const { setOpen: setSupportDrawerOpen } = useSupportDrawer();
+ const { isMobile, setOpenMobile: setOpenMobileSidebar } = useSidebar();
+
+ return (
+ <SidebarMenuButton
+ onClick={() => {
+ if (isMobile) {
+ setOpenMobileSidebar(false);
+ }
+ setTimeout(() => {
+ // push to next tick to avoid flickering when hiding sidebar on mobile
+ setSupportDrawerOpen(true);
+ }, 1);
+ }}
+ >
+ <LifeBuoy className="h-4 w-4" />
+ Support
+ </SidebarMenuButton>
+ );
+};
diff --git a/web/src/components/nav/support-menu-dropdown.tsx b/web/src/components/nav/support-menu-dropdown.tsx
deleted file mode 100644
index 367d33592b..0000000000
--- a/web/src/components/nav/support-menu-dropdown.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/src/components/ui/dropdown-menu";
-import {
- ArrowUpRight,
- Bug,
- Github,
- Radio,
- LibraryBig,
- LifeBuoy,
- Lightbulb,
- MessageCircle,
- MessageSquarePlus,
- Sparkles,
- type LucideIcon,
-} from "lucide-react";
-import { SiDiscord } from "react-icons/si";
-import { useMemo, type ReactNode } from "react";
-import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
-import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";
-import { env } from "@/src/env.mjs";
-import { chatAvailable, openChat } from "@/src/features/support-chat/PlainChat";
-
-type SupportMenuItem = {
- title: string;
- pathname: string;
- icon: LucideIcon | React.ElementType;
- menuNode?: ReactNode;
-};
-
-export const SupportMenuDropdown = () => {
- const uiCustomization = useUiCustomization();
-
- const supportMenuItems: (SupportMenuItem | "separator")[] = useMemo(() => {
- const items: (SupportMenuItem | "separator")[] = [
- {
- title: "Ask AI",
- pathname: "https://langfuse.com/docs/ask-ai",
- icon: Sparkles,
- },
- ];
-
- if (uiCustomization?.supportHref) {
- items.push({
- title: "Support",
- pathname: uiCustomization.supportHref,
- icon: LifeBuoy,
- });
- } else {
- if (chatAvailable) {
- items.push({
- title: "Chat",
- pathname: "#",
- menuNode: (
- <div className="flex items-center gap-2" onClick={() => openChat()}>
- <MessageCircle className="h-4 w-4" />
- <span>Contact Support</span>
- </div>
- ),
- icon: MessageCircle,
- });
- }
- items.push("separator");
- items.push({
- title: "GitHub Support",
- pathname: "https://langfuse.com/gh-support",
- icon: Github,
- });
- items.push({
- title: "Discord",
- pathname: "https://langfuse.com/discord",
- icon: SiDiscord,
- });
- }
-
- items.push("separator");
- items.push({
- title: "Docs",
- pathname:
- uiCustomization?.documentationHref ?? "https://langfuse.com/docs",
- icon: LibraryBig,
- });
- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- items.push({
- title: "Status Page",
- pathname: "https://status.langfuse.com",
- icon: Radio,
- });
- }
- items.push("separator");
-
- if (uiCustomization?.feedbackHref) {
- items.push({
- title: "Feedback",
- pathname: uiCustomization.feedbackHref,
- icon: MessageSquarePlus,
- });
- } else {
- items.push(
- ...[
- {
- title: "Feature Request",
- pathname: "https://langfuse.com/ideas",
- icon: Lightbulb,
- },
- {
- title: "Report a Bug",
- pathname: "https://langfuse.com/issues",
- icon: Bug,
- },
- ],
- );
- }
-
- return items;
- }, [uiCustomization]);
-
- const { isMobile } = useSidebar();
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <SidebarMenuButton>
- <LifeBuoy className="h-4 w-4" />
- Support
- </SidebarMenuButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side={isMobile ? "bottom" : "right"}
- align="end"
- sideOffset={4}
- >
- {supportMenuItems.map((item, index) => {
- if (item === "separator") {
- return <DropdownMenuSeparator key={`separator-${index}`} />;
- }
-
- return (
- <DropdownMenuItem key={item.title} asChild>
- {item.menuNode ?? (
- <a
- href={item.pathname}
- target={
- item.pathname.startsWith("http") ? "_blank" : undefined
- }
- rel={
- item.pathname.startsWith("http") ? "noopener" : undefined
- }
- className="flex cursor-pointer items-center"
- >
- <item.icon className="mr-2 h-4 w-4" />
- {item.title}
- {item.pathname.startsWith("http") && (
- <ArrowUpRight className="ml-1 h-3 w-3" />
- )}
- </a>
- )}
- </DropdownMenuItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
- );
-};
diff --git a/web/src/components/ui/drawer.tsx b/web/src/components/ui/drawer.tsx
index 5b3bd803a8..f43e472820 100644
--- a/web/src/components/ui/drawer.tsx
+++ b/web/src/components/ui/drawer.tsx
@@ -7,11 +7,15 @@ import { cn } from "@/src/utils/tailwind";
import { useMediaQuery } from "react-responsive";
import { cva } from "class-variance-authority";
+type DrawerProps = React.ComponentProps<typeof DrawerPrimitive.Root> & {
+ forceDirection?: "right" | "bottom" | "responsive";
+};
+
type DrawerContentProps = React.ComponentPropsWithoutRef<
typeof DrawerPrimitive.Content
> & {
overlayClassName?: string;
- size?: "default" | "md" | "lg";
+ size?: "default" | "md" | "lg" | "full";
position?: "top";
height?: "default" | "md";
};
@@ -27,6 +31,7 @@ const drawerVariants = cva(
default: "md:w-1/2 lg:w-2/5 xl:w-1/3 2xl:w-1/4",
md: "w-3/5",
lg: "w-2/3",
+ full: "w-full",
},
position: {
top: "md:inset-y-0",
@@ -46,12 +51,18 @@ const drawerVariants = cva(
const Drawer = ({
shouldScaleBackground = true,
+ forceDirection = "responsive",
...props
-}: React.ComponentProps<typeof DrawerPrimitive.Root>) => {
+}: DrawerProps) => {
const isMediumScreen = useMediaQuery({
query: `(min-width: ${TAILWIND_MD_MEDIA_QUERY}px)`,
});
- const direction = isMediumScreen ? "right" : "bottom";
+ const direction =
+ forceDirection === "responsive"
+ ? isMediumScreen
+ ? "right"
+ : "bottom"
+ : forceDirection;
return (
<DrawerPrimitive.Root
diff --git a/web/src/components/ui/shadcn-io/dropzone/index.tsx b/web/src/components/ui/shadcn-io/dropzone/index.tsx
new file mode 100644
index 0000000000..89b602a482
--- /dev/null
+++ b/web/src/components/ui/shadcn-io/dropzone/index.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+import { UploadIcon } from "lucide-react";
+import type { ReactNode } from "react";
+import { createContext, useContext } from "react";
+import type { DropEvent, DropzoneOptions, FileRejection } from "react-dropzone";
+import { useDropzone } from "react-dropzone";
+import { Button } from "@/src/components/ui/button";
+import { cn } from "@/src/utils/tailwind";
+
+type DropzoneContextType = {
+ src?: File[];
+ accept?: DropzoneOptions["accept"];
+ maxSize?: DropzoneOptions["maxSize"];
+ minSize?: DropzoneOptions["minSize"];
+ maxFiles?: DropzoneOptions["maxFiles"];
+};
+
+const renderBytes = (bytes: number) => {
+ const units = ["B", "KB", "MB", "GB", "TB", "PB"];
+ let size = bytes;
+ let unitIndex = 0;
+
+ while (size >= 1024 && unitIndex < units.length - 1) {
+ size /= 1024;
+ unitIndex++;
+ }
+
+ return `${size.toFixed(2)}${units[unitIndex]}`;
+};
+
+const DropzoneContext = createContext<DropzoneContextType | undefined>(
+ undefined,
+);
+
+export type DropzoneProps = Omit<DropzoneOptions, "onDrop"> & {
+ src?: File[];
+ className?: string;
+ onDrop?: (
+ acceptedFiles: File[],
+ fileRejections: FileRejection[],
+ event: DropEvent,
+ ) => void;
+ children?: ReactNode;
+};
+
+export const Dropzone = ({
+ accept,
+ maxFiles = 1,
+ maxSize,
+ minSize,
+ onDrop,
+ onError,
+ disabled,
+ src,
+ className,
+ children,
+ ...props
+}: DropzoneProps) => {
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({
+ accept,
+ maxFiles,
+ maxSize,
+ minSize,
+ onError,
+ disabled,
+ onDrop: (acceptedFiles, fileRejections, event) => {
+ if (fileRejections.length > 0) {
+ const message = fileRejections.at(0)?.errors.at(0)?.message;
+ onError?.(new Error(message));
+ return;
+ }
+
+ onDrop?.(acceptedFiles, fileRejections, event);
+ },
+ ...props,
+ });
+
+ return (
+ <DropzoneContext.Provider
+ key={JSON.stringify(src)}
+ value={{ src, accept, maxSize, minSize, maxFiles }}
+ >
+ <Button
+ className={cn(
+ "relative h-auto w-full flex-col overflow-hidden p-8",
+ isDragActive && "outline-none ring-1 ring-ring",
+ className,
+ )}
+ disabled={disabled}
+ type="button"
+ variant="outline"
+ {...getRootProps()}
+ >
+ <input {...getInputProps()} disabled={disabled} />
+ {children}
+ </Button>
+ </DropzoneContext.Provider>
+ );
+};
+
+const useDropzoneContext = () => {
+ const context = useContext(DropzoneContext);
+
+ if (!context) {
+ throw new Error("useDropzoneContext must be used within a Dropzone");
+ }
+
+ return context;
+};
+
+export type DropzoneContentProps = {
+ children?: ReactNode;
+ className?: string;
+};
+
+const maxLabelItems = 3;
+
+export const DropzoneContent = ({
+ children,
+ className,
+}: DropzoneContentProps) => {
+ const { src } = useDropzoneContext();
+
+ if (!src) {
+ return null;
+ }
+
+ if (children) {
+ return children;
+ }
+
+ return (
+ <div className={cn("flex flex-col items-center justify-center", className)}>
+ <div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <UploadIcon size={16} />
+ </div>
+ <p className="my-2 w-full truncate text-sm font-medium">
+ {src.length > maxLabelItems
+ ? `${new Intl.ListFormat("en").format(
+ src.slice(0, maxLabelItems).map((file) => file.name),
+ )} and ${src.length - maxLabelItems} more`
+ : new Intl.ListFormat("en").format(src.map((file) => file.name))}
+ </p>
+ <p className="w-full text-wrap text-xs text-muted-foreground">
+ Drag and drop or click to replace
+ </p>
+ </div>
+ );
+};
+
+export type DropzoneEmptyStateProps = {
+ children?: ReactNode;
+ className?: string;
+};
+
+export const DropzoneEmptyState = ({
+ children,
+ className,
+}: DropzoneEmptyStateProps) => {
+ const { src, accept, maxSize, minSize, maxFiles } = useDropzoneContext();
+
+ if (src) {
+ return null;
+ }
+
+ if (children) {
+ return children;
+ }
+
+ let caption = "";
+
+ if (accept) {
+ caption += "Accepts ";
+ caption += new Intl.ListFormat("en").format(Object.keys(accept));
+ }
+
+ if (minSize && maxSize) {
+ caption += ` between ${renderBytes(minSize)} and ${renderBytes(maxSize)}`;
+ } else if (minSize) {
+ caption += ` at least ${renderBytes(minSize)}`;
+ } else if (maxSize) {
+ caption += ` less than ${renderBytes(maxSize)}`;
+ }
+
+ return (
+ <div className={cn("flex flex-col items-center justify-center", className)}>
+ <div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <UploadIcon size={16} />
+ </div>
+ <p className="my-2 w-full truncate text-wrap text-sm font-medium">
+ Upload {maxFiles === 1 ? "a file" : "files"}
+ </p>
+ <p className="w-full truncate text-wrap text-xs text-muted-foreground">
+ Drag and drop or click to upload
+ </p>
+ {caption && (
+ <p className="text-wrap text-xs text-muted-foreground">{caption}.</p>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsx
index 7b807ebaf5..c9a7c36877 100644
--- a/web/src/ee/features/billing/components/BillingSettings.tsx
+++ b/web/src/ee/features/billing/components/BillingSettings.tsx
@@ -30,7 +30,7 @@ import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";
import { toast } from "sonner";
import { ActionButton } from "@/src/components/ActionButton";
import { useState } from "react";
-import { chatAvailable, openChat } from "@/src/features/support-chat/PlainChat";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
import { UsageAlerts } from "./UsageAlerts";
export const BillingSettings = () => {
@@ -154,6 +154,7 @@ const BillingPortalOrPricingPageButton = () => {
const organization = useQueryOrganization();
const router = useRouter();
const capture = usePostHogClientCapture();
+ const { setOpen } = useSupportDrawer();
const billingPortalUrl = api.cloudBilling.getStripeCustomerPortalUrl.useQuery(
{
orgId: organization?.id as string,
@@ -195,21 +196,11 @@ const BillingPortalOrPricingPageButton = () => {
// Do not show checkout or customer portal if manual plan is set in cloud config
if (organization?.cloudConfig?.plan) {
- if (chatAvailable)
- return (
- <Button
- variant="secondary"
- onClick={() =>
- // sendUserChatMessage(
- // `I'd like to change my current plan, region ${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}, organization id ${organization.id}`,
- // )
- openChat()
- }
- >
- Change plan (via support)
- </Button>
- );
- else return null;
+ return (
+ <Button variant="secondary" onClick={() => setOpen(true)}>
+ Change plan (via support)
+ </Button>
+ );
}
const switchPlan = (
diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.ts
index 683f5cb158..da305f777c 100644
--- a/web/src/features/entitlements/constants/entitlements.ts
+++ b/web/src/features/entitlements/constants/entitlements.ts
@@ -15,12 +15,14 @@ const entitlements = [
"scheduled-blob-exports",
"prompt-protected-labels",
"admin-api",
+ "in-app-support",
] as const;
export type Entitlement = (typeof entitlements)[number];
const cloudAllPlansEntitlements: Entitlement[] = [
"cloud-billing",
"trace-deletion",
+ "in-app-support",
];
const selfHostedAllPlansEntitlements: Entitlement[] = [
diff --git a/web/src/features/notifications/ErrorNotification.tsx b/web/src/features/notifications/ErrorNotification.tsx
index fe580dd5fb..43523e25cc 100644
--- a/web/src/features/notifications/ErrorNotification.tsx
+++ b/web/src/features/notifications/ErrorNotification.tsx
@@ -1,5 +1,5 @@
import { Button } from "@/src/components/ui/button";
-import { chatAvailable, openChat } from "@/src/features/support-chat/PlainChat";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
import { AlertTriangle, X } from "lucide-react";
interface ErrorNotificationProps {
@@ -19,6 +19,7 @@ export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
toast,
path,
}) => {
+ const { setOpen } = useSupportDrawer();
const isError = type === "ERROR";
const textColor = isError
? "text-destructive-foreground"
@@ -55,12 +56,12 @@ export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
</div>
)}
- {isError && chatAvailable && (
+ {isError && (
<Button
variant="errorNotification"
size={"sm"}
onClick={() => {
- openChat();
+ setOpen(true);
}}
>
Report issue to Langfuse team
diff --git a/web/src/features/projects/components/NewProjectForm.tsx b/web/src/features/projects/components/NewProjectForm.tsx
index ad9edccc14..6b44030bf5 100644
--- a/web/src/features/projects/components/NewProjectForm.tsx
+++ b/web/src/features/projects/components/NewProjectForm.tsx
@@ -16,7 +16,6 @@ import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { showChat } from "@/src/features/support-chat/PlainChat";
export const NewProjectForm = ({
orgId,
@@ -57,7 +56,6 @@ export const NewProjectForm = ({
.catch((error) => {
console.error(error);
});
- showChat();
}
return (
<Form {...form}>
diff --git a/web/src/features/setup/components/SetupPage.tsx b/web/src/features/setup/components/SetupPage.tsx
index a1abfe8595..5934dc9b6f 100644
--- a/web/src/features/setup/components/SetupPage.tsx
+++ b/web/src/features/setup/components/SetupPage.tsx
@@ -22,7 +22,6 @@ import {
inviteMembersRoute,
setupTracingRoute,
} from "@/src/features/setup/setupRoutes";
-import { showChat } from "@/src/features/support-chat/PlainChat";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
import { type RouterOutput } from "@/src/utils/types";
@@ -249,7 +248,6 @@ const TracingSetup = ({
onSuccess: (data) => {
utils.projectApiKeys.invalidate();
setApiKeys(data);
- showChat();
},
});
diff --git a/web/src/features/support-chat/IntroSection.tsx b/web/src/features/support-chat/IntroSection.tsx
new file mode 100644
index 0000000000..ddda5cefeb
--- /dev/null
+++ b/web/src/features/support-chat/IntroSection.tsx
@@ -0,0 +1,261 @@
+import { useMemo } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Github,
+ Bug,
+ Lightbulb,
+ Sparkles,
+ LibraryBig,
+ LifeBuoy,
+ Radio,
+} from "lucide-react";
+//eslint-disable-next-line no-restricted-imports
+import { SiDiscord } from "react-icons/si";
+import { RainbowButton } from "@/src/components/magicui/rainbow-button";
+import { Separator } from "@/src/components/ui/separator";
+import { usePlan } from "@/src/features/entitlements/hooks";
+import { isCloudPlan } from "@langfuse/shared";
+import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+
+type SupportType = "in-app-support" | "custom" | "community";
+
+export function IntroSection({
+ onStartForm,
+}: {
+ onStartForm: () => void;
+ displayDensity?: "default" | "compact";
+}) {
+ const uiCustomization = useUiCustomization();
+ const hasInAppSupportEntitlement = useHasEntitlement("in-app-support");
+ const plan = usePlan();
+
+ const supportType: SupportType = useMemo(() => {
+ if (uiCustomization?.supportHref) {
+ return "custom";
+ }
+ if (hasInAppSupportEntitlement) {
+ return "in-app-support";
+ }
+ return "community";
+ }, [hasInAppSupportEntitlement, uiCustomization]);
+
+ const showStatusPageLink = useMemo(() => {
+ return isCloudPlan(plan);
+ }, [plan]);
+
+ return (
+ <div className="mt-1 flex flex-col gap-6">
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <Sparkles className="h-4 w-4" /> Ask AI
+ </div>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Get instant, helpful answers. Our AI knows the docs, examples, and
+ best practices to guide you fast.
+ </p>
+
+ <RainbowButton asChild>
+ <a
+ href="https://langfuse.com/docs/ask-ai"
+ target="_blank"
+ rel="noopener"
+ >
+ Chat with AI
+ </a>
+ </RainbowButton>
+ </div>
+
+ <Separator />
+
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <LibraryBig className="h-4 w-4" /> Docs
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Dive into guides, concepts, and API reference β€” clear steps and
+ examples to move quickly.
+ </p>
+
+ <Button asChild variant="outline">
+ <a
+ href={
+ uiCustomization?.documentationHref ?? "https://langfuse.com/docs"
+ }
+ target="_blank"
+ rel="noopener"
+ >
+ View documentation
+ </a>
+ </Button>
+ </div>
+
+ <Separator />
+
+ {supportType === "custom" && (
+ <>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <LifeBuoy className="h-4 w-4" /> Support
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Ask AI & Docs did not unblock you? Get in touch with the support
+ team.
+ </p>
+ <Button variant="outline" asChild>
+ <a
+ href={uiCustomization?.supportHref}
+ target="_blank"
+ rel="noopener"
+ >
+ Open Support
+ </a>
+ </Button>
+ {uiCustomization?.feedbackHref && (
+ <Button variant="outline" asChild>
+ <a
+ href={uiCustomization?.feedbackHref}
+ target="_blank"
+ rel="noopener"
+ >
+ Submit Feedback
+ </a>
+ </Button>
+ )}
+ {!uiCustomization?.supportHref && (
+ <>
+ <Button variant="outline" asChild>
+ <a
+ href="https://langfuse.com/ideas"
+ target="_blank"
+ rel="noopener"
+ >
+ Feature request
+ </a>
+ </Button>
+ <Button variant="outline" asChild>
+ <a
+ href="https://langfuse.com/issues"
+ target="_blank"
+ rel="noopener"
+ >
+ Report a bug
+ </a>
+ </Button>
+ </>
+ )}
+ </div>
+
+ <Separator />
+ </>
+ )}
+
+ {supportType === "in-app-support" && (
+ <>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <LifeBuoy className="h-4 w-4" /> Email a Support Engineer
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Ask AI & Docs did not unblock you? One of our support engineers
+ will help you get unblocked.
+ </p>
+ <Button variant="outline" onClick={onStartForm}>
+ Email a Support Engineer
+ </Button>
+ </div>
+
+ <Separator />
+ </>
+ )}
+
+ {supportType === "community" && (
+ <>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <LifeBuoy className="h-4 w-4" /> Community Support
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Ask AI & Docs did not unblock you? Get help from and share
+ feedback with the community.
+ </p>
+ <Button variant="outline" asChild>
+ <a
+ href="https://langfuse.com/gh-support"
+ target="_blank"
+ rel="noopener"
+ >
+ <Github className="mr-2 h-4 w-4" /> Get Help β†—
+ </a>
+ </Button>
+ <Button variant="outline" asChild>
+ <a
+ href="https://langfuse.com/ideas"
+ target="_blank"
+ rel="noopener"
+ >
+ <Lightbulb className="mr-2 h-4 w-4" /> Feature request β†—
+ </a>
+ </Button>
+ <Button variant="outline" asChild>
+ <a
+ href="https://langfuse.com/issues"
+ target="_blank"
+ rel="noopener"
+ >
+ <Bug className="mr-2 h-4 w-4" /> Report a bug β†—
+ </a>
+ </Button>
+ </div>
+
+ <Separator />
+ </>
+ )}
+
+ {supportType !== "custom" && (
+ <div>
+ <div className="flex items-center gap-2 text-base font-semibold">
+ <Github className="h-4 w-4" /> Community & Resources
+ </div>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Join the conversation and connect with the Langfuse community.
+ </p>
+ <div className="mt-3 grid grid-cols-1 gap-2">
+ <Button asChild variant="ghost" className="justify-start px-1.5">
+ <a
+ href="https://langfuse.com/gh-support"
+ target="_blank"
+ rel="noopener"
+ >
+ <Github className="mr-2 h-4 w-4" /> GitHub β†—
+ </a>
+ </Button>
+ <Button asChild variant="ghost" className="justify-start px-1.5">
+ <a
+ href="https://langfuse.com/discord"
+ target="_blank"
+ rel="noopener"
+ className="flex items-center"
+ >
+ <SiDiscord className="mr-2 h-4 w-4" /> Discord β†—
+ </a>
+ </Button>
+
+ {showStatusPageLink && (
+ <Button asChild variant="ghost" className="justify-start px-1.5">
+ <a
+ href="https://status.langfuse.com"
+ target="_blank"
+ rel="noopener"
+ className="flex items-center"
+ >
+ <Radio className="mr-2 h-4 w-4" /> Status Page β†—
+ </a>
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/support-chat/PlainChat.tsx b/web/src/features/support-chat/PlainChat.tsx
deleted file mode 100644
index 61b844be28..0000000000
--- a/web/src/features/support-chat/PlainChat.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import { env } from "@/src/env.mjs";
-import { api } from "@/src/utils/api";
-import { type Plan } from "@langfuse/shared";
-import { useSession } from "next-auth/react";
-import { useEffect, useRef, useState } from "react";
-
-declare global {
- interface Window {
- Plain: any;
- }
-}
-
-// Add these at the top level
-let metadataQueue: Array<() => void> = [];
-let isWidgetLoaded = false;
-
-const PlainChat = () => {
- const scriptRef = useRef<HTMLScriptElement | null>(null);
- const updatePlainDataMut = api.plain.updatePlainData.useMutation({
- onError: () => {}, // Don't show default error toast
- });
- const session = useSession();
- const [isWidgetLoadedState, setIsWidgetLoadedState] = useState(false);
-
- const updateIsWidgetLoaded = (value: boolean) => {
- setIsWidgetLoadedState(value); // for use in useEffect
- isWidgetLoaded = value; // for use in global functions
- };
-
- useEffect(() => {
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return;
- if (!env.NEXT_PUBLIC_PLAIN_APP_ID) {
- console.error("NEXT_PUBLIC_PLAIN_APP_ID is not set");
- return;
- }
-
- // Check if URL contains supportChat parameter
- const shouldShowChat =
- typeof window !== "undefined" &&
- new URLSearchParams(window.location.search).get("supportChat") === "1";
-
- // Load the script only once
- if (!scriptRef.current) {
- const script = document.createElement("script");
- script.async = false;
- script.src = "https://chat.cdn-plain.com/index.js";
- script.onload = () => {
- window.Plain.init({
- appId: env.NEXT_PUBLIC_PLAIN_APP_ID,
- hideLauncher: !shouldShowChat,
- hideBranding: true,
- hideThreadRefs: true,
- logo: {
- url: "/icon256.png",
- alt: "Langfuse logo",
- },
- style: {
- brandColor: "#000000", // This will be used in various places in the chat widget such as the primary chat button and send message button
- brandBackgroundColor: "#0A60B5", // Used for the background of the chat widget on the intro screen
- launcherBackgroundColor: "#666666", // These can also be passed in this format { light: '#FFFFFF', dark: '#000000' }
- launcherIconColor: "#FFFFFF",
- },
- chatButtons: [
- {
- icon: "email",
- text: "Contact Support",
- },
- ],
- links: [
- {
- icon: "chat",
- text: "Ask AI Chat",
- url: "https://langfuse.com/ask-ai",
- },
- {
- icon: "book",
- text: "View Langfuse docs",
- url: "https://langfuse.com/docs",
- },
- ],
- });
-
- // Mark widget as loaded and process queued metadata updates
- updateIsWidgetLoaded(true);
- for (const metadataUpdate of metadataQueue) {
- try {
- metadataUpdate();
- } catch (error) {
- console.error("Error updating Plain metadata", error);
- }
- }
- metadataQueue = [];
-
- // If URL parameter is present, open the chat immediately
- if (shouldShowChat) {
- window.Plain.open();
- }
- };
-
- document.head.appendChild(script);
- scriptRef.current = script;
-
- // Cleanup function to remove the script when the component unmounts
- return () => {
- if (scriptRef.current && document.head.contains(scriptRef.current)) {
- document.head.removeChild(scriptRef.current);
- }
- };
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Update Plain.com data when user is authenticated and chat is loaded
- // Trigger not be authenticated to prevent trigger on every auth session refresh (status=loading)
- const isNotUnauthenticated = session.status !== "unauthenticated";
-
- useEffect(() => {
- if (
- isNotUnauthenticated &&
- isWidgetLoaded &&
- session.status === "authenticated" &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
- ) {
- updatePlainDataMut.mutate();
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isNotUnauthenticated, isWidgetLoadedState]);
-
- return null;
-};
-
-export default PlainChat;
-
-export const chatAvailable = !!env.NEXT_PUBLIC_PLAIN_APP_ID;
-
-export const chatLoaded = () => {
- return (
- chatAvailable && typeof window !== "undefined" && window.Plain !== undefined
- );
-};
-
-const runOrQueuePlainCallback = (cb: () => void) => {
- if (isWidgetLoaded) {
- cb();
- } else {
- metadataQueue.push(cb);
- }
-};
-
-export const showChat = (): void => {
- runOrQueuePlainCallback(() => {
- if (chatLoaded()) {
- window.Plain.update({
- hideLauncher: false,
- });
- }
- });
-};
-
-export const hideChat = (): void => {
- if (chatLoaded()) {
- window.Plain.update({
- hideLauncher: true,
- });
- }
-};
-
-export const closeChat = (): void => {
- if (chatLoaded()) {
- window.Plain.close();
- }
-};
-
-export const openChat = (): void => {
- runOrQueuePlainCallback(() => {
- if (chatLoaded()) {
- showChat();
- window.Plain.open();
- }
- });
-};
-
-export const getUnreadMessageCount = (): number | null => {
- if (chatLoaded()) {
- return window.Plain.getUnreadMessageCount();
- }
- return null;
-};
-
-export const chatSetCustomer = (customer: {
- email?: string;
- fullName?: string;
- emailHash?: string;
- chatAvatarUrl?: string;
-}) => {
- runOrQueuePlainCallback(() => {
- if (chatLoaded()) {
- window.Plain.update({
- customerDetails: customer,
- });
- }
- });
-};
-
-export const chatSetThreadDetails = (p: { orgId?: string; plan?: Plan }) => {
- runOrQueuePlainCallback(() => {
- if (chatLoaded()) {
- window.Plain.update({
- threadDetails: {
- ...(p.orgId && {
- tenantIdentifier: {
- externalId: `cloud_${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}_org_${p.orgId}`,
- },
- }),
- },
- });
- }
- });
-};
diff --git a/web/src/features/support-chat/SuccessSection.tsx b/web/src/features/support-chat/SuccessSection.tsx
new file mode 100644
index 0000000000..254cc93496
--- /dev/null
+++ b/web/src/features/support-chat/SuccessSection.tsx
@@ -0,0 +1,39 @@
+import { Button } from "@/src/components/ui/button";
+import { Separator } from "@/src/components/ui/separator";
+import { CheckCircle2 } from "lucide-react";
+import { IntroSection } from "@/src/features/support-chat/IntroSection";
+
+export function SuccessSection({
+ onAnother,
+}: {
+ onClose: () => void;
+ onAnother: () => void;
+}) {
+ return (
+ <div className="mt-1 flex flex-col gap-6">
+ {/* Success card */}
+ <div className="rounded-md border p-4">
+ <div className="flex items-start gap-3">
+ <CheckCircle2 className="mt-0.5 h-5 w-5 text-green-600" />
+ <div className="space-y-0.5">
+ <div className="text-sm font-medium">Thanks for your message</div>
+ <div className="text-sm text-muted-foreground">
+ We created a support ticket and will reply via email.
+ </div>
+ </div>
+ </div>
+
+ {/* Primary actions */}
+ <div className="mt-4 flex flex-wrap items-center justify-start gap-2 pl-7">
+ <Button variant="outline" size="sm" onClick={onAnother}>
+ Submit another
+ </Button>
+ </div>
+ </div>
+
+ <Separator />
+
+ <IntroSection onStartForm={() => onAnother()} />
+ </div>
+ );
+}
diff --git a/web/src/features/support-chat/SupportDrawer.tsx b/web/src/features/support-chat/SupportDrawer.tsx
new file mode 100644
index 0000000000..addd1755ac
--- /dev/null
+++ b/web/src/features/support-chat/SupportDrawer.tsx
@@ -0,0 +1,108 @@
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { X, Slash } from "lucide-react";
+import {
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+} 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 { cn } from "@/src/utils/tailwind";
+
+export const SupportDrawer = ({
+ showCloseButton = true,
+ className,
+}: {
+ showCloseButton?: boolean;
+ className?: string;
+}) => {
+ const { open, setOpen } = useSupportDrawer();
+ const [currentMode, setCurrentMode] = useState<"intro" | "form" | "success">(
+ "intro",
+ );
+ const close = () => setOpen(false);
+
+ if (!open) return null;
+
+ return (
+ <div
+ className={cn([
+ "flex h-dvh w-full min-w-0 flex-col bg-background",
+ className,
+ ])}
+ >
+ <div className="bg-background">
+ <div className="flex min-h-12 w-full items-center justify-between gap-1 px-3 py-1">
+ <Breadcrumb>
+ <BreadcrumbList>
+ {currentMode === "intro" ? (
+ <BreadcrumbItem>
+ <BreadcrumbPage>Support</BreadcrumbPage>
+ </BreadcrumbItem>
+ ) : (
+ <>
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <button
+ type="button"
+ onClick={() => setCurrentMode("intro")}
+ className="text-foreground"
+ >
+ Support
+ </button>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ <BreadcrumbSeparator>
+ <Slash />
+ </BreadcrumbSeparator>
+ <BreadcrumbItem>
+ <BreadcrumbPage>Email Engineer</BreadcrumbPage>
+ </BreadcrumbItem>
+ </>
+ )}
+ </BreadcrumbList>
+ </Breadcrumb>
+ {showCloseButton && (
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={close}
+ aria-label="Close"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ <div className="flex-1 overflow-y-auto border-t">
+ <div className="p-4">
+ <div className="h-full bg-background">
+ <div className="p-2">
+ {currentMode === "intro" && (
+ <IntroSection onStartForm={() => setCurrentMode("form")} />
+ )}
+ {currentMode === "form" && (
+ <SupportFormSection
+ onSuccess={() => setCurrentMode("success")}
+ onCancel={() => setCurrentMode("intro")}
+ />
+ )}
+ {currentMode === "success" && (
+ <SuccessSection
+ onClose={close}
+ onAnother={() => setCurrentMode("form")}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/features/support-chat/SupportDrawerProvider.tsx b/web/src/features/support-chat/SupportDrawerProvider.tsx
new file mode 100644
index 0000000000..7958939037
--- /dev/null
+++ b/web/src/features/support-chat/SupportDrawerProvider.tsx
@@ -0,0 +1,41 @@
+import {
+ createContext,
+ useContext,
+ useState,
+ type PropsWithChildren,
+} from "react";
+
+type SupportDrawerContextType = {
+ open: boolean;
+ setOpen: (v: boolean) => void;
+};
+
+const SupportDrawerContext = createContext<SupportDrawerContextType | null>(
+ null,
+);
+
+export interface SupportDrawerProviderProps extends PropsWithChildren {
+ defaultOpen?: boolean;
+}
+
+// SupportDrawerProvider to allow us to open the drawer from anywhere in the app
+export function SupportDrawerProvider({
+ children,
+ defaultOpen = false,
+}: SupportDrawerProviderProps) {
+ const [open, setOpen] = useState(defaultOpen);
+ return (
+ <SupportDrawerContext.Provider value={{ open, setOpen }}>
+ {children}
+ </SupportDrawerContext.Provider>
+ );
+}
+
+export function useSupportDrawer() {
+ const ctx = useContext(SupportDrawerContext);
+ if (!ctx)
+ throw new Error(
+ "useSupportDrawer must be used within SupportDrawerProvider",
+ );
+ return ctx;
+}
diff --git a/web/src/features/support-chat/SupportFormSection.tsx b/web/src/features/support-chat/SupportFormSection.tsx
new file mode 100644
index 0000000000..b93294cfc8
--- /dev/null
+++ b/web/src/features/support-chat/SupportFormSection.tsx
@@ -0,0 +1,503 @@
+"use client";
+
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useForm } from "react-hook-form";
+import { type z } from "zod";
+import {
+ MESSAGE_TYPES,
+ SEVERITIES,
+ INTEGRATION_TYPES,
+ TopicGroups,
+ type MessageType,
+ SupportFormSchema,
+} from "./formConstants";
+
+import { api } from "@/src/utils/api";
+
+import { Button } from "@/src/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { RadioGroup } from "@/src/components/ui/radio-group";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { Textarea } from "@/src/components/ui/textarea";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { useMemo, useState } from "react";
+
+import {
+ Dropzone,
+ DropzoneContent,
+ DropzoneEmptyState,
+} from "@/src/components/ui/shadcn-io/dropzone";
+import { Paperclip, Loader2, Trash2 } from "lucide-react";
+
+/** 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 function SupportFormSection({
+ onCancel,
+ onSuccess,
+}: {
+ onCancel: () => void;
+ onSuccess: () => void;
+}) {
+ const projectId = useProjectIdFromURL();
+
+ // Tracks whether we've already warned about a short message
+ const [warnedShortOnce, setWarnedShortOnce] = useState(false);
+
+ // Local file state from Dropzone
+ const [files, setFiles] = useState<File[] | undefined>(undefined);
+ const totalUploadBytes = useMemo(
+ () => (files ?? []).reduce((sum, f) => sum + f.size, 0),
+ [files],
+ );
+
+ // Local submit guard to avoid flicker across multiple mutations
+ const [isSubmittingLocal, setIsSubmittingLocal] = useState(false);
+
+ const form = useForm<SupportFormInput>({
+ resolver: zodResolver(SupportFormSchema),
+ defaultValues: {
+ messageType: "Question" as MessageType,
+ severity: "Question or feature request",
+ topic: "",
+ message: "",
+ integrationType: "",
+ },
+ mode: "onChange",
+ });
+
+ const selectedTopic = form.watch("topic");
+ const isProductFeatureTopic = TopicGroups["Product Features"].includes(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ selectedTopic as any,
+ );
+
+ const createSupportThread = api.plainRouter.createSupportThread.useMutation({
+ onSuccess: () => {
+ 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: () => 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}`,
+ );
+ }
+ }
+
+ const onSubmit = async (values: SupportFormInput) => {
+ const parsed: SupportFormValues = SupportFormSchema.parse(values);
+ const msgLen = (parsed.message ?? "").trim().length;
+
+ if (msgLen < 20 && !warnedShortOnce) {
+ setWarnedShortOnce(true);
+ return;
+ }
+
+ try {
+ setIsSubmittingLocal(true);
+
+ // UI-side constraints
+ const maxFiles = 5;
+ const maxFileSize = 10 * 1024 * 1024;
+ const maxCombined = 50 * 1024 * 1024;
+ if ((files?.length ?? 0) > maxFiles) {
+ throw new Error(`Please upload at most ${maxFiles} files.`);
+ }
+ if ((files ?? []).some((f) => f.size > maxFileSize)) {
+ throw new Error("Each file must be ≀ 10MB.");
+ }
+ if (totalUploadBytes > maxCombined) {
+ throw new Error("Total attachment size must be ≀ 50MB.");
+ }
+
+ // 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
+ if (files && files.length) {
+ await 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,
+ );
+ }),
+ );
+ }
+
+ // 3) Create thread with attachmentIds
+ const attachmentIds =
+ uploadPlans.uploads?.map((u: any) => u.attachmentId) ?? [];
+
+ await createSupportThread.mutateAsync({
+ messageType: parsed.messageType,
+ severity: parsed.severity,
+ topic: parsed.topic as any,
+ integrationType: parsed.integrationType,
+ message: parsed.message,
+ url: window.location.href,
+ projectId,
+ browserMetadata: {
+ userAgent: navigator.userAgent,
+ platform: navigator.platform,
+ language: navigator.language,
+ viewport: { w: window.innerWidth, h: window.innerHeight },
+ },
+ attachmentIds,
+ });
+ } catch (err: any) {
+ console.error(err);
+ setIsSubmittingLocal(false);
+ form.setError("message", {
+ type: "manual",
+ message: err?.message ?? "Failed to submit support request.",
+ });
+ }
+ };
+
+ const isValid = form.formState.isValid;
+ const messageIsShortAfterWarning =
+ warnedShortOnce && (form.getValues("message") ?? "").trim().length < 20;
+
+ // --- Compact attachment row helpers
+ const totalMB = (totalUploadBytes / (1024 * 1024)).toFixed(2);
+ const hasFiles = (files?.length ?? 0) > 0;
+
+ return (
+ <div className="mt-1 flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-base font-semibold">
+ E-Mail a Support Engineer
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Details speed things up. The clearer your request, the quicker you get
+ the answer you need.
+ </p>
+
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-4"
+ >
+ {/* Message Type */}
+ <FormField
+ control={form.control}
+ name="messageType"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Message Type</FormLabel>
+ <FormControl>
+ <RadioGroup
+ className="grid grid-cols-3 gap-2"
+ value={field.value ?? "Question"}
+ onValueChange={field.onChange}
+ >
+ {MESSAGE_TYPES.map((v) => (
+ <Button
+ key={v}
+ variant={field.value === v ? "default" : "outline"}
+ className="flex w-full items-center gap-2 text-sm font-normal"
+ size="default"
+ onClick={() => field.onChange(v)}
+ >
+ <span className="truncate">{v}</span>
+ </Button>
+ ))}
+ </RadioGroup>
+ </FormControl>
+ <FormDescription className="sr-only">
+ Choose the type of your message.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Severity */}
+ <FormField
+ control={form.control}
+ name="severity"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Severity</FormLabel>
+ <FormControl>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger>
+ <SelectValue placeholder="Select severity" />
+ </SelectTrigger>
+ <SelectContent>
+ {SEVERITIES.map((s) => (
+ <SelectItem key={s} value={s}>
+ {s}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Topic */}
+ <FormField
+ control={form.control}
+ name="topic"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Topic</FormLabel>
+ <FormControl>
+ <Select
+ value={(field.value as string | undefined) ?? undefined}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select a topic" />
+ </SelectTrigger>
+ <SelectContent>
+ <div className="p-2">
+ <div className="mb-2 text-xs font-medium text-muted-foreground">
+ Product Features
+ </div>
+ {TopicGroups["Product Features"].map((t) => (
+ <SelectItem key={t} value={t}>
+ {t}
+ </SelectItem>
+ ))}
+ </div>
+ <div className="border-t p-2">
+ <div className="mb-2 text-xs font-medium text-muted-foreground">
+ Operations
+ </div>
+ {TopicGroups.Operations.map((t) => (
+ <SelectItem key={t} value={t}>
+ {t}
+ </SelectItem>
+ ))}
+ </div>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Integration Type */}
+ {isProductFeatureTopic && (
+ <FormField
+ control={form.control}
+ name="integrationType"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Integration Type (optional)</FormLabel>
+ <FormControl>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger>
+ <SelectValue placeholder="Select integration type" />
+ </SelectTrigger>
+ <SelectContent>
+ {INTEGRATION_TYPES.map((it) => (
+ <SelectItem key={it} value={it}>
+ {it}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {/* Message */}
+ <FormField
+ control={form.control}
+ name="message"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Message</FormLabel>
+ <div className="text-xs text-muted-foreground">
+ We will email you at your account address. Replies may take up
+ to one business day.
+ </div>
+ <FormControl>
+ <div className="relative w-full">
+ <Textarea
+ {...field}
+ rows={8}
+ placeholder={
+ isProductFeatureTopic
+ ? "Please explain as fully as possible what you're aiming to do, and what you'd like help with.\n\nIf your question involves a specific trace, prompt, score, etc. please include a link to it."
+ : "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>
+
+ {messageIsShortAfterWarning && (
+ <p
+ className="mt-2 text-sm text-red-500"
+ role="status"
+ aria-live="polite"
+ >
+ The message seems short β€” adding a bit more context can help
+ us get you a quicker, smarter answer. You can submit again
+ as is, or add more details.
+ </p>
+ )}
+
+ <FormMessage />
+ </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
+ type="button"
+ variant="outline"
+ onClick={() => {
+ setWarnedShortOnce(false);
+ setFiles(undefined);
+ onCancel();
+ }}
+ className="w-full"
+ >
+ Cancel
+ </Button>
+
+ <Button
+ type="submit"
+ disabled={isSubmittingLocal || !isValid}
+ className="w-full"
+ >
+ {isSubmittingLocal ? (
+ <span className="inline-flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Submitting…
+ </span>
+ ) : messageIsShortAfterWarning ? (
+ "Submit Anyways"
+ ) : (
+ "Submit"
+ )}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </div>
+ );
+}
diff --git a/web/src/features/support-chat/formConstants.ts b/web/src/features/support-chat/formConstants.ts
new file mode 100644
index 0000000000..653788a6d3
--- /dev/null
+++ b/web/src/features/support-chat/formConstants.ts
@@ -0,0 +1,79 @@
+// formModels.ts
+import { z } from "zod";
+
+/** ── Message Type ────────────────────────────────────────────────────────── */
+export const MessageTypeSchema = z.enum(["Question", "Feedback", "Bug"]);
+export type MessageType = z.infer<typeof MessageTypeSchema>;
+
+/** ── Form Sections (for your stepper/wizard) ─────────────────────────────── */
+export const FormSectionSchema = z.enum(["intro", "form", "success"]);
+export type FormSection = z.infer<typeof FormSectionSchema>;
+
+/** ── Topics (grouped + flattened) ────────────────────────────────────────── */
+export const TopicGroups = {
+ Operations: [
+ "Account Changes",
+ "Account Deletion",
+ "Billing / Usage",
+ "Inviting Users",
+ "Set Up SSO",
+ "Slack Connect Channel",
+ ],
+ "Product Features": [
+ "Observability",
+ "Prompt Management",
+ "Evaluation",
+ "Platform",
+ ],
+} as const;
+
+export type TopicGroup = keyof typeof TopicGroups;
+
+export const ALL_TOPICS = [
+ ...TopicGroups.Operations,
+ ...TopicGroups["Product Features"],
+] as const;
+
+export const TopicSchema = z.enum(ALL_TOPICS);
+export type Topic = z.infer<typeof TopicSchema>;
+
+export const SeveritySchema = z.enum([
+ "Question or feature request",
+ "Feature not working as expected",
+ "Feature is not working at all",
+ "Outage, data loss, or data breach",
+]);
+export type Severity = z.infer<typeof SeveritySchema>;
+
+export const IntegrationTypeSchema = z.enum([
+ "Python SDK",
+ "TypeScript SDK",
+ "Other SDK",
+ "Public API",
+ "OpenAI SDK",
+ "Vercel AI SDK",
+ "LangChain",
+ "LangGraph",
+ "OTel Instrumentation",
+ "LLM Proxy (LiteLLM)",
+ "3rd Party (Dify / LangFlow / Flowise)",
+ "Other (please specify)",
+]);
+export type IntegrationType = z.infer<typeof IntegrationTypeSchema>;
+
+export const SupportFormSchema = z.object({
+ messageType: MessageTypeSchema.default("Question"),
+ severity: SeveritySchema,
+ integrationType: z.string().optional(),
+ topic: z
+ .union([TopicSchema, z.literal("")])
+ .refine((val) => val !== "", { message: "Please select a topic." })
+ .transform((val) => val as z.infer<typeof TopicSchema>),
+ message: z.string().trim().min(1, "Message cannot be empty."), // 🚨 no empty strings allowed
+});
+export type SupportFormValues = z.infer<typeof SupportFormSchema>;
+
+export const MESSAGE_TYPES = MessageTypeSchema.options;
+export const FORM_SECTIONS = FormSectionSchema.options;
+export const SEVERITIES = SeveritySchema.options;
+export const INTEGRATION_TYPES = IntegrationTypeSchema.options;
diff --git a/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.ts b/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.ts
new file mode 100644
index 0000000000..5990521e8e
--- /dev/null
+++ b/web/src/features/support-chat/plain/events/supportRequestMetadataEvent.ts
@@ -0,0 +1,106 @@
+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.ts
new file mode 100644
index 0000000000..d421a01a67
--- /dev/null
+++ b/web/src/features/support-chat/plain/plainClient.ts
@@ -0,0 +1,471 @@
+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";
+
+// ===== 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,
+ };
+}
+
+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: "BAD_REQUEST",
+ message: `${label} failed`,
+ cause: res.error,
+ });
+ }
+ if (!res.data) {
+ logger.error(`${label} returned no data`, res);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: `${label} returned no data`,
+ });
+ }
+ return res.data;
+}
+
+function tenantExternalId(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);
+ 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.CustomTimelineEntry,
+ });
+
+ const data = unwrap("createAttachmentUploadUrl", r);
+ out.push({
+ attachmentId: data.attachment.id,
+ uploadFormUrl: data.uploadFormUrl,
+ uploadFormData: 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 = tenantExternalId(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) =>
+ tenantExternalId(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[];
+ },
+): 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,
+ 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,
+ attachmentIds: attachmentIds.length ? attachmentIds : undefined,
+ });
+
+ const thread = unwrap("createThread (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", createdWithFields);
+ 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));
+ }
+}
diff --git a/web/src/features/support-chat/trpc/plain.ts b/web/src/features/support-chat/trpc/plain.ts
deleted file mode 100644
index 19056da22c..0000000000
--- a/web/src/features/support-chat/trpc/plain.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
-import { TRPCError } from "@trpc/server";
-import { env } from "@/src/env.mjs";
-import { logger } from "@langfuse/shared/src/server";
-import { type CustomerTenantMembershipPartsFragment } from "@team-plain/typescript-sdk";
-import { PlainClient } from "@team-plain/typescript-sdk";
-
-const plainClient = env.PLAIN_API_KEY
- ? new PlainClient({
- apiKey: env.PLAIN_API_KEY,
- })
- : null;
-
-export const plainRouter = createTRPCRouter({
- updatePlainData: protectedProcedure.mutation(async ({ ctx }) => {
- try {
- const { session } = ctx;
- const user = session.user;
- const email = user.email;
-
- const CLOUD_REGION = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- if (!CLOUD_REGION) {
- return;
- }
-
- if (!email) {
- logger.error("User email is required for Plain.com profile update");
- return;
- }
-
- if (!plainClient) {
- logger.error("Plain.com client not configured");
- return;
- }
-
- // Upsert customer in Plain.com
- const plainCustomer = await plainClient.upsertCustomer({
- identifier: {
- emailAddress: email,
- },
- onCreate: {
- email: {
- email: email,
- isVerified: true,
- },
- fullName: user.name ?? "",
- },
- onUpdate: {
- email: {
- email: email,
- isVerified: true,
- },
- },
- });
- const plainCustomerId = plainCustomer.data?.customer.id;
- if (!plainCustomerId) {
- logger.error(
- "Failed to upsert customer in Plain.com",
- plainCustomer.error,
- );
- return;
- }
-
- // Upsert tenants in Plain.com
- const tenantIdentifier = (orgId: string) =>
- `cloud_${CLOUD_REGION}_org_${orgId}`;
- const isTenantInRegion = (plainTenantId: string) =>
- plainTenantId.startsWith(`cloud_${CLOUD_REGION}_org_`);
- const tenantPromises = user.organizations.map(async (org) => {
- await plainClient.upsertTenant({
- identifier: {
- externalId: tenantIdentifier(org.id),
- },
- name: `${CLOUD_REGION} - ${org.name}`,
- externalId: tenantIdentifier(org.id),
- });
- await plainClient.updateTenantTier({
- tenantIdentifier: {
- externalId: tenantIdentifier(org.id),
- },
- tierIdentifier: {
- externalId:
- org.id === env.NEXT_PUBLIC_DEMO_ORG_ID ? "cloud:demo" : org.plan,
- },
- });
- });
-
- await Promise.all(tenantPromises);
-
- // Associate user with tenants
- // Fetch all pages of customer tenant memberships
- let plainCustomerTenantMemberships: CustomerTenantMembershipPartsFragment[] =
- [];
- let after: string | undefined = undefined;
- const pageSize = 100;
- while (true) {
- const response = await plainClient.getCustomerTenantMemberships({
- customerId: plainCustomerId,
- first: pageSize,
- after,
- });
- if (response.data?.tenantMemberships) {
- plainCustomerTenantMemberships.push(
- ...response.data.tenantMemberships,
- );
- }
- const pageInfo = response.data?.pageInfo;
- if (pageInfo?.hasNextPage && pageInfo.endCursor) {
- after = pageInfo.endCursor;
- } else {
- break;
- }
- }
- // Remove tenants from this region that are not in the user's organizations anymore
- const tenantIdsOfUserInRegion = plainCustomerTenantMemberships
- .map((tenant) => tenant.tenant.externalId)
- .filter((id) => isTenantInRegion(id));
- const tenantIdsOfUserInRegionToRemove = tenantIdsOfUserInRegion.filter(
- (tenantId) =>
- !user.organizations
- .map((org) => tenantIdentifier(org.id))
- .includes(tenantId),
- );
- if (tenantIdsOfUserInRegionToRemove.length > 0) {
- await plainClient.removeCustomerFromTenants({
- customerIdentifier: {
- emailAddress: email,
- },
- tenantIdentifiers: tenantIdsOfUserInRegionToRemove.map((id) => ({
- externalId: id,
- })),
- });
- }
- // Add user to tenants
- const tenantIdsOfUserInRegionToAdd = user.organizations
- .map((org) => tenantIdentifier(org.id))
- .filter((tenantId) => !tenantIdsOfUserInRegion.includes(tenantId));
- if (tenantIdsOfUserInRegionToAdd.length > 0) {
- await plainClient.addCustomerToTenants({
- customerIdentifier: {
- emailAddress: email,
- },
- tenantIdentifiers: tenantIdsOfUserInRegionToAdd.map((tenantId) => ({
- externalId: tenantId,
- })),
- });
- }
- } catch (error) {
- logger.error("Failed to update Plain.com profiles", error);
-
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to update Plain.com profiles",
- cause: error,
- });
- }
- }),
-});
diff --git a/web/src/features/support-chat/trpc/plainRouter.ts b/web/src/features/support-chat/trpc/plainRouter.ts
new file mode 100644
index 0000000000..85c57deaf9
--- /dev/null
+++ b/web/src/features/support-chat/trpc/plainRouter.ts
@@ -0,0 +1,215 @@
+// trpc/plainRouter.ts
+import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+import { env } from "@/src/env.mjs";
+import { VERSION } from "@/src/constants";
+
+import {
+ MessageTypeSchema,
+ SeveritySchema,
+ TopicSchema,
+ TopicGroups,
+} from "../formConstants";
+
+import { buildPlainEventSupportRequestMetadataComponents } from "../plain/events/supportRequestMetadataEvent";
+
+import {
+ initPlain,
+ ensureCustomer,
+ createAttachmentUploadUrls,
+ createSupportThread as plainCreateSupportThread,
+ createThreadEvent,
+ syncTenantsAndTiers,
+ syncCustomerTenantMemberships,
+ type SessionUser,
+ type Organization,
+} from "../plain/plainClient";
+
+// =========================
+// Input Schemas
+// =========================
+const CreateSupportThreadInput = z.object({
+ messageType: MessageTypeSchema,
+ severity: SeveritySchema,
+ topic: TopicSchema,
+ message: z.string().trim().min(1),
+ url: z.string().url().optional(),
+ projectId: z.string().optional(),
+ browserMetadata: z.record(z.any()).optional(),
+ integrationType: z.string().optional(),
+ /** IDs of attachments already uploaded via prepareAttachmentUploads */
+ attachmentIds: z.array(z.string()).optional(),
+});
+
+const PrepareAttachmentUploadsInput = z.object({
+ files: z
+ .array(
+ z.object({
+ fileName: z.string().min(1),
+ fileSizeBytes: z.number().int().positive(),
+ }),
+ )
+ .max(100)
+ .optional()
+ .default([]),
+});
+
+// =========================
+// Local domain helpers
+// =========================
+function splitTopic(topic: z.infer<typeof TopicSchema>): {
+ topLevel: "Operations" | "Product Features";
+ subtype: string;
+} {
+ if ((TopicGroups.Operations as readonly string[]).includes(topic)) {
+ return { topLevel: "Operations", subtype: topic };
+ }
+ return { topLevel: "Product Features", subtype: topic };
+}
+
+function deriveOrganizationFromProject(user: SessionUser, projectId?: string) {
+ if (!projectId || !Array.isArray(user.organizations)) return undefined;
+ for (const org of user.organizations as Organization[]) {
+ if (org.projects?.some((p) => p.id === projectId)) return org;
+ }
+ return undefined;
+}
+
+// =========================
+/** Router */
+// =========================
+export const plainRouter = createTRPCRouter({
+ /**
+ * Prepare presigned S3 upload forms for attachments.
+ * - Ensures customer exists (returns customerId)
+ * - Returns uploadFormUrl + uploadFormData + attachmentId per file
+ */
+ prepareAttachmentUploads: protectedProcedure
+ .input(PrepareAttachmentUploadsInput)
+ .mutation(async ({ ctx, input }) => {
+ const email = ctx.session.user.email;
+ const fullName = ctx.session.user.name ?? undefined;
+ 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,
+ };
+ }),
+
+ /**
+ * 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).
+ */
+ createSupportThread: protectedProcedure
+ .input(CreateSupportThreadInput)
+ .mutation(async ({ ctx, input }) => {
+ const email = ctx.session.user.email;
+ const fullName = ctx.session.user.name ?? undefined;
+ if (!email) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "User email required to create a support thread.",
+ });
+ }
+
+ 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 region = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const demoOrgId = env.NEXT_PUBLIC_DEMO_ORG_ID;
+ if (region) {
+ await syncTenantsAndTiers(plain, {
+ user: ctx.session.user as SessionUser,
+ region,
+ demoOrgId,
+ });
+ await syncCustomerTenantMemberships(plain, {
+ email,
+ customerId,
+ user: ctx.session.user as SessionUser,
+ region,
+ });
+ }
+
+ // Domain prep
+ const derivedOrganization = deriveOrganizationFromProject(
+ ctx.session.user as SessionUser,
+ input.projectId,
+ );
+ const { topLevel, subtype } = splitTopic(input.topic);
+
+ // (3) Create thread (with fallback inside)
+ const { threadId, createdAt, status, createdWithThreadFields } =
+ await plainCreateSupportThread(plain, {
+ email,
+ title: `${input.messageType}: ${input.topic}`,
+ message: input.message,
+ messageType: input.messageType,
+ severity: input.severity,
+ topicTopLevel: topLevel,
+ topicSubtype: subtype,
+ url: input.url,
+ 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: derivedOrganization?.id,
+ projectId: input.projectId,
+ version: VERSION,
+ plan: derivedOrganization?.plan,
+ cloudRegion: region,
+ browserMetadata: input.browserMetadata,
+ });
+
+ await createThreadEvent(plain, {
+ threadId,
+ title: eventTitle,
+ components: eventComponents,
+ externalId: `support-metadata:${threadId}`,
+ });
+ } catch {
+ // best-effort; errors are logged in helpers
+ }
+ })();
+
+ return {
+ threadId,
+ customerId,
+ status,
+ createdAt,
+ createdWithThreadFields,
+ attachmentCount: (input.attachmentIds ?? []).length,
+ };
+ }),
+});
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index f80da5da12..3e2000471d 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -27,17 +27,13 @@ import "core-js/features/array/to-reversed";
import "core-js/features/array/to-spliced";
import "core-js/features/array/to-sorted";
-// Other CSS
import "react18-json-view/src/style.css";
+
import { DetailPageListsProvider } from "@/src/features/navigate-detail-pages/context";
import { env } from "@/src/env.mjs";
import { ThemeProvider } from "@/src/features/theming/ThemeProvider";
import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";
-import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
-import PlainChat, {
- chatSetCustomer,
- chatSetThreadDetails,
-} from "@/src/features/support-chat/PlainChat";
+import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";
// Check that PostHog is client-side (used to handle Next.js SSR) and that env vars are set
if (
@@ -103,14 +99,15 @@ const MyApp: AppType<{ session: Session | null }> = ({
enableSystem
disableTransitionOnChange
>
- <Layout>
- <Component {...pageProps} />
- <UserTracking />
- </Layout>
+ <SupportDrawerProvider defaultOpen={false}>
+ <Layout>
+ <Component {...pageProps} />
+ <UserTracking />
+ </Layout>
+ </SupportDrawerProvider>
<BetterStackUptimeStatusMessage />
</ThemeProvider>
</MarkdownContextProvider>
- <PlainChat />
</DetailPageListsProvider>
</SessionProvider>
</PostHogProvider>
@@ -125,7 +122,6 @@ export default api.withTRPC(MyApp);
function UserTracking() {
const session = useSession();
const sessionUser = session.data?.user;
- const { organization } = useQueryProjectOrOrganization();
// Track user identity and properties
const lastIdentifiedUser = useRef<string | null>(null);
@@ -158,14 +154,6 @@ function UserTracking() {
email: sessionUser.email ?? undefined,
id: sessionUser.id ?? undefined,
});
-
- // Chat
- chatSetCustomer({
- email: sessionUser.email ?? undefined,
- fullName: sessionUser.name ?? undefined,
- emailHash: sessionUser.emailSupportHash ?? undefined,
- chatAvatarUrl: sessionUser.image ?? undefined,
- });
} else if (session.status === "unauthenticated") {
lastIdentifiedUser.current = null;
// PostHog
@@ -177,22 +165,6 @@ function UserTracking() {
}
}, [sessionUser, session.status]);
- // update chat thread details
- const plan = organization?.plan;
- // const currentOrgIsDemoOrg =
- // env.NEXT_PUBLIC_DEMO_ORG_ID &&
- // organization?.id &&
- // organization.id === env.NEXT_PUBLIC_DEMO_ORG_ID;
- // const projectRole = project?.role;
- // const organizationRole = organization?.role;
- const organizationId = organization?.id;
- useEffect(() => {
- chatSetThreadDetails({
- orgId: organizationId ?? undefined,
- plan: plan ?? undefined,
- });
- }, [plan, organizationId]);
-
// add stripe link to chat
// const orgStripeLink = organization?.cloudConfig?.stripe?.customerId
// ? `https://dashboard.stripe.com/customers/${organization.cloudConfig.stripe.customerId}`
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index 303e027aee..380043cc88 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -38,7 +38,7 @@ import { Code } from "lucide-react";
import { useRouter } from "next/router";
import { captureException } from "@sentry/nextjs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { openChat } from "@/src/features/support-chat/PlainChat";
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
const credentialAuthForm = z.object({
email: z.string().email(),
@@ -405,6 +405,7 @@ export default function SignIn({
runningOnHuggingFaceSpaces,
}: PageProps) {
const router = useRouter();
+ const { setOpen: setSupportDrawerOpen } = useSupportDrawer();
useHuggingFaceRedirect(runningOnHuggingFaceSpaces);
// handle NextAuth error codes: https://next-auth.js.org/configuration/pages#sign-in-page
@@ -577,7 +578,7 @@ export default function SignIn({
on a solution.{" "}
<span
className="cursor-pointer whitespace-nowrap text-xs font-medium text-primary-accent hover:text-hover-primary-accent"
- onClick={() => openChat()}
+ onClick={() => setSupportDrawerOpen(true)}
>
(contact us)
</span>
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 1c10f56651..e8b5bef558 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -40,8 +40,8 @@ import { dashboardWidgetRouter } from "./routers/dashboardWidgets";
import { TableViewPresetsRouter } from "@/src/server/api/routers/tableViewPresets";
import { automationsRouter } from "@/src/features/automations/server/router";
import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";
-import { plainRouter } from "@/src/features/support-chat/trpc/plain";
import { slackRouter } from "@/src/features/slack/server/router";
+import { plainRouter } from "@/src/features/support-chat/trpc/plainRouter";
import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/annotationQueueAssignments";
import { surveysRouter } from "@/src/server/api/routers/surveys";
@@ -94,7 +94,7 @@ export const appRouter = createTRPCRouter({
TableViewPresets: TableViewPresetsRouter,
automations: automationsRouter,
slack: slackRouter,
- plain: plainRouter,
+ plainRouter: plainRouter,
surveys: surveysRouter,
});
diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css
index 0d2b6db121..537b6991f2 100644
--- a/web/src/styles/globals.css
+++ b/web/src/styles/globals.css
@@ -79,6 +79,11 @@
--chart-3: var(--dark-blue);
--chart-4: var(--dark-red);
--chart-grid: var(--muted-gray);
+ --color-1: oklch(66.2% 0.225 25.9);
+ --color-2: oklch(60.4% 0.26 302);
+ --color-3: oklch(69.6% 0.165 251);
+ --color-4: oklch(80.2% 0.134 225);
+ --color-5: oklch(90.7% 0.231 133);
}
.dark {
@@ -159,6 +164,14 @@
--chart-3: var(--dark-blue);
--chart-4: var(--dark-red);
--chart-grid: var(--muted-gray);
+ --color-1: oklch(66.2% 0.225 25.9);
+ --color-2: oklch(60.4% 0.26 302);
+ --color-3: oklch(69.6% 0.165 251);
+ --color-4: oklch(80.2% 0.134 225);
+ --color-5: oklch(90.7% 0.231 133);
+ }
+ .theme {
+ --animate-rainbow: rainbow var(--speed, 2s) infinite linear;
}
}
@@ -214,3 +227,14 @@
border-right: 2px solid currentColor !important;
border-bottom: 2px solid currentColor !important;
}
+
+@theme inline {
+ @keyframes rainbow {
+ 0% {
+ background-position: 0%;
+ }
+ 100% {
+ background-position: 200%;
+ }
+ }
+}