Skip to content

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

feat(ui): add in-product notifications (#1057)

Richard Krümmel7f7696e9ff22
diff --git a/package-lock.json b/package-lock.json
index 475c8a9b07..0a883877a0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -77,6 +77,7 @@
"react-icons": "^5.0.1",
"react-responsive": "^9.0.2",
"react18-json-view": "^0.2.7",
+ "sonner": "^1.4.0",
"superjson": "2.2.1",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7",
@@ -16872,6 +16873,15 @@
"integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==",
"dev": true
},
+ "node_modules/sonner": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/sonner/-/sonner-1.4.0.tgz",
+ "integrity": "sha512-nvkTsIuOmi9e5Wz5If8ldasJjZNVfwiXYijBi2dbijvTQnQppvMcXTFNxL/NUFWlI2yJ1JX7TREDsg+gYm9WyA==",
+ "peerDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
diff --git a/package.json b/package.json
index fdbf86c4d6..defd69c310 100644
--- a/package.json
+++ b/package.json
@@ -97,6 +97,7 @@
"react-icons": "^5.0.1",
"react-responsive": "^9.0.2",
"react18-json-view": "^0.2.7",
+ "sonner": "^1.4.0",
"superjson": "2.2.1",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7",
diff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsx
index 3939049662..8d91508312 100644
--- a/src/components/layouts/layout.tsx
+++ b/src/components/layouts/layout.tsx
@@ -8,7 +8,6 @@ import { useRouter } from "next/router";
import clsx from "clsx";
import { Code, MessageSquarePlus, Info, ChevronRightIcon } from "lucide-react";
import { signOut, useSession } from "next-auth/react";
-import { ChevronDownIcon } from "@heroicons/react/20/solid";
import { cn } from "@/src/utils/tailwind";
import {
Avatar,
@@ -24,6 +23,13 @@ import { env } from "@/src/env.mjs";
import { LangfuseLogo } from "@/src/components/LangfuseLogo";
import { Spinner } from "@/src/components/layouts/spinner";
import { hasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { Toaster } from "@/src/components/ui/sonner";
+import {
+ NOTIFICATIONS,
+ useCheckNotification,
+} from "@/src/features/notifications/checkNotifications";
+import { ChevronDownIcon } from "@heroicons/react/20/solid";
+import useLocalStorage from "@/src/components/useLocalStorage";
const userNavigation = [
{
@@ -46,6 +52,9 @@ export default function Layout(props: PropsWithChildren) {
const [sidebarOpen, setSidebarOpen] = useState(false);
const router = useRouter();
const session = useSession();
+
+ useCheckNotification(NOTIFICATIONS, session.status === "authenticated");
+
const enableExperimentalFeatures =
api.environment.enableExperimentalFeatures.useQuery().data ?? false;
@@ -503,6 +512,7 @@ export default function Layout(props: PropsWithChildren) {
</div>
) : null}
<main className="p-4">{props.children}</main>
+ <Toaster visibleToasts={1} />
</div>
</div>
</>
@@ -522,29 +532,11 @@ const MainNavigation: React.FC<{
nav: NavigationItem[];
onNavitemClick?: () => void;
}> = ({ nav, onNavitemClick }) => {
- const STORAGE_KEY = "sidebar-tracing-default-open";
- const getDefaultOpen = () => {
- const savedState = localStorage.getItem(STORAGE_KEY);
- if (savedState !== null) {
- try {
- return JSON.parse(savedState) as boolean;
- } catch (e) {
- console.error("Error parsing saved state: ", e);
- }
- }
- return false;
- };
+ const [isOpen, setIsOpen] = useLocalStorage(
+ "sidebar-tracing-default-open",
+ false,
+ );
- const handleDropDownClick = () => {
- const savedState = localStorage.getItem(STORAGE_KEY);
- const isOpen =
- savedState !== null ? (JSON.parse(savedState) as boolean) : false;
- const newState = !isOpen;
- localStorage.setItem(
- "sidebar-tracing-default-open",
- JSON.stringify(newState),
- );
- };
return (
<li>
<ul role="list" className="-mx-2 space-y-1">
@@ -590,15 +582,14 @@ const MainNavigation: React.FC<{
<Disclosure
as="div"
defaultOpen={
- item.children.some((child) => child.current) ||
- getDefaultOpen()
+ item.children.some((child) => child.current) || isOpen
}
>
{({ open }) => (
<>
<Disclosure.Button
className="group flex w-full items-center gap-x-3 rounded-md p-2 text-left text-sm font-semibold leading-6 hover:bg-gray-50 hover:text-indigo-600"
- onClick={handleDropDownClick}
+ onClick={() => setIsOpen(!isOpen)}
>
{item.icon && (
<item.icon
diff --git a/src/components/ui/sonner.tsx b/src/components/ui/sonner.tsx
new file mode 100644
index 0000000000..2471ecc039
--- /dev/null
+++ b/src/components/ui/sonner.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { Toaster as Sonner } from "sonner";
+
+type ToasterProps = React.ComponentProps<typeof Sonner>;
+
+const Toaster = ({ ...props }: ToasterProps) => {
+ return (
+ <Sonner
+ theme={"light"}
+ className="toaster group"
+ position="top-right"
+ toastOptions={{
+ classNames: {
+ toast:
+ "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
+ description: "group-[.toast]:text-muted-foreground",
+ actionButton:
+ "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
+ cancelButton:
+ "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
+ },
+ }}
+ {...props}
+ />
+ );
+};
+
+export { Toaster };
diff --git a/src/components/useLocalStorage.tsx b/src/components/useLocalStorage.tsx
index f227f7301a..b211e9c954 100644
--- a/src/components/useLocalStorage.tsx
+++ b/src/components/useLocalStorage.tsx
@@ -20,6 +20,9 @@ import { useState, useEffect } from "react";
*/
function useLocalStorage<T>(localStorageKey: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
+ if (typeof window === "undefined") {
+ return initialValue;
+ }
try {
const storedValue = localStorage.getItem(localStorageKey);
return storedValue ? (JSON.parse(storedValue) as T) : initialValue;
diff --git a/src/features/column-visibility/hooks/useColumnVisibility.ts b/src/features/column-visibility/hooks/useColumnVisibility.ts
index d6f8703b6c..5eed094d71 100644
--- a/src/features/column-visibility/hooks/useColumnVisibility.ts
+++ b/src/features/column-visibility/hooks/useColumnVisibility.ts
@@ -1,42 +1,28 @@
-import { useState, useEffect } from "react";
import { type VisibilityState } from "@tanstack/react-table";
import { type LangfuseColumnDef } from "@/src/components/table/types";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import { useEffect } from "react";
function useColumnVisibility<TData>(
localStorageKey: string,
columns: LangfuseColumnDef<TData>[],
) {
- const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
- () => {
- try {
- const savedVisibility = localStorage.getItem(localStorageKey);
- const visibilityState: VisibilityState = savedVisibility
- ? (JSON.parse(savedVisibility) as VisibilityState)
- : {};
- // set default visibility for columns that are not in the saved state
- columns.forEach((column) => {
- if (
- "accessorKey" in column &&
- typeof column.accessorKey === "string"
- ) {
- if (!(column.accessorKey in visibilityState)) {
- visibilityState[column.accessorKey] =
- column.defaultHidden === true ? false : true;
- }
- }
- });
- return visibilityState;
- } catch (e) {
- console.error("Error while loading saved column visibility", e);
- return {};
+ const initialVisibilityState = () => {
+ const visibilityState: VisibilityState = {};
+ columns.forEach((column) => {
+ if ("accessorKey" in column && typeof column.accessorKey === "string") {
+ visibilityState[column.accessorKey] =
+ column.defaultHidden === true ? false : true;
}
- },
- );
+ });
+ return visibilityState;
+ };
- useEffect(() => {
- const localStorageItem = localStorage.getItem(localStorageKey);
+ const [columnVisibility, setColumnVisibility] =
+ useLocalStorage<VisibilityState>(localStorageKey, initialVisibilityState());
- if (!localStorageItem || localStorageItem === "{}") {
+ useEffect(() => {
+ if (Object.keys(columnVisibility).length === 0) {
const initialVisibility: VisibilityState = {};
columns.forEach((column) => {
if ("accessorKey" in column && typeof column.accessorKey === "string") {
@@ -45,23 +31,8 @@ function useColumnVisibility<TData>(
}
});
setColumnVisibility(initialVisibility);
- } else {
- // make sure all columns are in the visibility state
- const visibilityState = JSON.parse(localStorageItem) as VisibilityState;
- columns.forEach((column) => {
- if ("accessorKey" in column && typeof column.accessorKey === "string") {
- if (!(column.accessorKey in visibilityState)) {
- visibilityState[column.accessorKey] =
- column.defaultHidden === true ? false : true;
- }
- }
- });
}
- }, [columns, localStorageKey]);
-
- useEffect(() => {
- localStorage.setItem(localStorageKey, JSON.stringify(columnVisibility));
- }, [columnVisibility, localStorageKey]);
+ }, [columnVisibility, columns, setColumnVisibility]);
return [columnVisibility, setColumnVisibility] as const;
}
diff --git a/src/features/notifications/Notification.tsx b/src/features/notifications/Notification.tsx
new file mode 100644
index 0000000000..3b9acd2cb6
--- /dev/null
+++ b/src/features/notifications/Notification.tsx
@@ -0,0 +1,47 @@
+import { X } from "lucide-react";
+
+export interface TNotification {
+ id: number;
+ releaseDate: Date;
+ message: string | JSX.Element;
+ description?: JSX.Element | string;
+}
+
+interface NotificationProps {
+ notification: TNotification;
+ setLastSeenId: (id: number) => void;
+ dismissToast: (t?: string | number | undefined) => void;
+ toast: string | number;
+}
+
+const Notification: React.FC<NotificationProps> = ({
+ notification,
+ setLastSeenId,
+ dismissToast,
+ toast,
+}) => (
+ <div className="flex justify-between">
+ <div className="flex min-w-[300px] flex-1 flex-col justify-center">
+ <div className="m-0 text-sm font-medium leading-tight text-gray-800">
+ {notification.message}
+ </div>
+ {notification.description && (
+ <div className="mt-2 flex-1 text-sm leading-tight text-gray-800">
+ {notification.description}
+ </div>
+ )}
+ </div>
+ <button
+ className="flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 text-gray-800 transition-colors duration-200"
+ onClick={() => {
+ setLastSeenId(notification.id);
+ dismissToast(toast);
+ }}
+ aria-label="Close"
+ >
+ <X size={14} />
+ </button>
+ </div>
+);
+
+export default Notification;
diff --git a/src/features/notifications/checkNotifications.tsx b/src/features/notifications/checkNotifications.tsx
new file mode 100644
index 0000000000..57bc3bc561
--- /dev/null
+++ b/src/features/notifications/checkNotifications.tsx
@@ -0,0 +1,95 @@
+import { useEffect } from "react";
+import Link from "next/link";
+import { toast } from "sonner";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import Notification, {
+ type TNotification,
+} from "@/src/features/notifications/Notification";
+import { Button } from "@/src/components/ui/button";
+import { env } from "@/src/env.mjs";
+
+export const NOTIFICATIONS: TNotification[] = [
+ {
+ id: 1,
+ releaseDate: new Date("2024-01-29"),
+ message: "New: Custom model prices",
+ description: (
+ <div>
+ <p>
+ Langfuse now supports any LLM model for usage and cost tracking. The
+ highlights:
+ </p>
+ <ul className="ms-4 mt-2 list-outside list-disc">
+ <li>Define your model definitions (price, usage).</li>
+ <li>Optionally, ingest cost via the API/SDK</li>
+ <li>Support for usage in tokens, seconds and characters</li>
+ </ul>
+ {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined && (
+ <p className="mt-2">
+ Self-hosted: The upgrade to v2 includes a breaking change. After
+ upgrading, you must run a migration script to ensure accurate usage
+ and cost calculation for previously ingested traces. Please refer to
+ the post for details.
+ </p>
+ )}
+ <Button size="sm" variant="secondary" className="mt-3">
+ <Link href="https://langfuse.com/changelog/2024-01-29-custom-model-prices">
+ Changelog post
+ </Link>
+ </Button>
+ </div>
+ ),
+ },
+];
+
+export const useCheckNotification = (
+ notification: TNotification[],
+ authenticated: boolean,
+) => {
+ const [lastSeenId, setLastSeenId] = useLocalStorage<number>(
+ "lastSeenNotificationId",
+ 0,
+ );
+ useEffect(() => {
+ if (!authenticated) {
+ return;
+ }
+
+ const timeoutId = setTimeout(() => {
+ notification
+ .reverse()
+ .filter(
+ (n) =>
+ // only show notifications that are less than 30 days old
+ (new Date().getTime() - n.releaseDate.getTime()) /
+ (1000 * 60 * 60 * 24) <=
+ 30,
+ )
+ .forEach((n) => {
+ if (n.id > lastSeenId) {
+ toast.custom(
+ (t) => (
+ <Notification
+ notification={n}
+ setLastSeenId={setLastSeenId}
+ dismissToast={toast.dismiss}
+ toast={t}
+ />
+ ),
+ {
+ // needed to upsert toasts in case it is rendered multiple times
+ id: n.id.toString(),
+ duration: 600_000, // 10 minutes
+ style: {
+ padding: "1rem",
+ border: "1px solid #e2e8f0",
+ borderRadius: "0.5rem",
+ },
+ },
+ );
+ }
+ });
+ }, 1500);
+ return () => clearTimeout(timeoutId);
+ }, [lastSeenId, notification, setLastSeenId, authenticated]);
+};
diff --git a/src/features/tag/components/TagMananger.tsx b/src/features/tag/components/TagMananger.tsx
index dc25592464..a451b5658d 100644
--- a/src/features/tag/components/TagMananger.tsx
+++ b/src/features/tag/components/TagMananger.tsx
@@ -9,6 +9,7 @@ import {
PopoverContent,
} from "@/src/components/ui/popover";
import { Command, CommandList, CommandGroup } from "cmdk";
+import { cn } from "@/src/utils/tailwind";
type TagManagerProps = {
tags: string[];
@@ -61,7 +62,7 @@ const TagManager = ({
setSelectedTags={setSelectedTags}
/>
<CommandList
- className={availableTags.length > 0 ? "mt-2" : undefined}
+ className={cn("overflow-auto", availableTags.length > 0 && "mt-2")}
>
<CommandGroup>
{availableTags.slice(0, 5).map((value: string) => (