Skip to content

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

feat(agent): Improve in-app agent UI (#14027)

Ben Bachemec5ac58183f3
diff --git a/web/src/components/layouts/app-layout/index.tsx b/web/src/components/layouts/app-layout/index.tsx
index 31339a7b62..a94b4bae5d 100644
--- a/web/src/components/layouts/app-layout/index.tsx
+++ b/web/src/components/layouts/app-layout/index.tsx
@@ -142,7 +142,6 @@ export function AppLayout(props: PropsWithChildren) {
session={session.data}
navigation={navigation}
metadata={metadata}
- aiFeaturesEnabled={organization?.aiFeaturesEnabled ?? false}
onSignOut={handleSignOut}
>
{props.children}
diff --git a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx
index ed77fb89ac..3ebd994d45 100644
--- a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx
+++ b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx
@@ -2,7 +2,6 @@ import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvi
import { type PropsWithChildren } from "react";
import { useMediaQuery } from "react-responsive";
import dynamic from "next/dynamic";
-import { useInAppAiAgent } from "@/src/features/in-app-agent/components/InAppAiAgentProvider";
import Spinner from "@/src/components/design-system/Spinner/Spinner";
import { ResizableSplitLayout } from "@/src/components/ui/resizable-split-layout";
@@ -27,17 +26,6 @@ const DynamicSupportDrawer = dynamic(
},
);
-const DynamicControlledInAppAgentDrawer = dynamic(
- () =>
- import("@/src/features/in-app-agent/components").then((mod) => ({
- default: mod.ControlledInAppAgentDrawer,
- })),
- {
- ssr: false,
- loading: () => <RightDrawerLoadingFallback />,
- },
-);
-
function RightDrawerLoadingFallback() {
return (
<div className="flex h-full w-full items-center justify-center">
@@ -47,47 +35,31 @@ function RightDrawerLoadingFallback() {
}
/**
- * App-shell content wrapper that attaches the support / AI assistant right drawer.
+ * App-shell content wrapper that attaches the support right drawer.
*
* Desktop keeps a stable split wrapper so routed page content does not remount
* when a right drawer opens or closes. Mobile uses a bottom drawer.
*/
-export function AppContentWithRightDrawer({
- aiAgentEnabled,
- children,
-}: PropsWithChildren<{ aiAgentEnabled?: boolean }>) {
+export function AppContentWithRightDrawer({ children }: PropsWithChildren) {
const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });
const { open: supportOpen } = useSupportDrawer();
- const { open: aiAgentOpen, setOpen: setAiAgentOpen } = useInAppAiAgent();
- const showAiAgent = Boolean(aiAgentEnabled && aiAgentOpen);
- const showRightDrawer = showAiAgent || supportOpen;
if (!isDesktop) {
- return (
- <DynamicMobileRightDrawer aiAgentEnabled={aiAgentEnabled}>
- {children}
- </DynamicMobileRightDrawer>
- );
+ return <DynamicMobileRightDrawer>{children}</DynamicMobileRightDrawer>;
}
- const rightDrawerContent = showAiAgent ? (
- <DynamicControlledInAppAgentDrawer onClose={() => setAiAgentOpen(false)} />
- ) : supportOpen ? (
- <DynamicSupportDrawer />
- ) : null;
+ const rightDrawerContent = supportOpen ? <DynamicSupportDrawer /> : null;
return (
<ResizableSplitLayout
primaryContent={children}
secondaryContent={rightDrawerContent}
- open={showRightDrawer}
- showHandle={showAiAgent}
- defaultPrimarySize={showAiAgent ? 72 : 70}
- defaultSecondarySize={showAiAgent ? 28 : 30}
+ open={supportOpen}
+ defaultPrimarySize={70}
+ defaultSecondarySize={30}
minPrimarySize={30}
maxSecondarySize={60}
keepSecondaryMounted={false}
- persistId={showAiAgent ? "assistant-sidebar" : undefined}
/>
);
}
diff --git a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx
index 214a4f7cc4..ca0517997c 100644
--- a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx
+++ b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx
@@ -8,16 +8,9 @@ import {
} from "@/src/components/ui/drawer";
import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
import { SupportDrawer } from "@/src/features/support-chat/SupportDrawer";
-import { useInAppAiAgent } from "@/src/features/in-app-agent/components/InAppAiAgentProvider";
-import { ControlledInAppAgentDrawer } from "@/src/features/in-app-agent/components";
-export function MobileRightDrawer({
- aiAgentEnabled,
- children,
-}: PropsWithChildren<{ aiAgentEnabled?: boolean }>) {
+export function MobileRightDrawer({ children }: PropsWithChildren) {
const { open: supportOpen, setOpen: setSupportOpen } = useSupportDrawer();
- const { open: aiAgentOpen, setOpen: setAiAgentOpen } = useInAppAiAgent();
- const showAiAgent = Boolean(aiAgentEnabled && aiAgentOpen);
return (
<>
@@ -26,10 +19,9 @@ export function MobileRightDrawer({
</main>
<Drawer
- open={showAiAgent || supportOpen}
+ open={supportOpen}
onOpenChange={(open) => {
if (!open) {
- setAiAgentOpen(false);
setSupportOpen(false);
}
}}
@@ -44,21 +36,14 @@ export function MobileRightDrawer({
<div className="flex w-full items-center justify-center pt-3">
<div className="bg-muted h-2 w-20 rounded-full" />
</div>
- <DrawerTitle className="sr-only">
- {showAiAgent ? "AI Assistant" : "Support"}
- </DrawerTitle>
+ {/* sr-only for screen readers and accessibility */}
+ <DrawerTitle className="sr-only">Support</DrawerTitle>
<DrawerDescription className="sr-only">
- {showAiAgent
- ? "An AI assistant to help you with your questions."
- : "A list of resources and options to help you with your questions."}
+ A list of resources and options to help you with your questions.
</DrawerDescription>
</DrawerHeader>
<div className="mt-4 max-h-full">
- {showAiAgent ? (
- <ControlledInAppAgentDrawer showCloseButton={false} />
- ) : (
- <SupportDrawer showCloseButton={false} className="h-full pb-20" />
- )}
+ <SupportDrawer showCloseButton={false} className="h-full pb-20" />
</div>
</DrawerContent>
</Drawer>
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
index cf690a8cbf..ec9f4df950 100644
--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
@@ -11,7 +11,6 @@ import { AppSidebar } from "@/src/components/nav/app-sidebar";
import { Toaster } from "@/src/components/ui/sonner";
import { TopBannerProvider } from "@/src/features/top-banner";
import { AppContentWithRightDrawer } from "../right-drawer/AppContentWithRightDrawer";
-import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
import { ThemeToggle } from "@/src/features/theming/ThemeToggle";
import {
getAvailableCloudRegionOptions,
@@ -83,7 +82,6 @@ type AuthenticatedLayoutProps = PropsWithChildren<{
favicon256Path: string;
appleTouchIconPath: string;
};
- aiFeaturesEnabled: boolean;
onSignOut: () => void;
}>;
@@ -101,12 +99,9 @@ export function AuthenticatedLayout({
session,
navigation,
metadata,
- aiFeaturesEnabled,
onSignOut,
}: AuthenticatedLayoutProps) {
const { isLangfuseCloud, region: currentRegion } = useLangfuseCloudRegion();
- const assistantEnabled =
- useIsFeatureEnabled("inAppAgent") && aiFeaturesEnabled;
// Safe assertion: AuthenticatedLayout is only rendered after auth checks pass
// in AppLayout, which guarantees session.user exists at this point
@@ -188,7 +183,7 @@ export function AuthenticatedLayout({
userNavProps={userNavProps}
/>
<SidebarInset className="h-screen-with-banner 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))]">
- <AppContentWithRightDrawer aiAgentEnabled={assistantEnabled}>
+ <AppContentWithRightDrawer>
{children}
</AppContentWithRightDrawer>
<Toaster visibleToasts={1} />
diff --git a/web/src/components/nav/in-app-ai-agent-button.tsx b/web/src/components/nav/in-app-ai-agent-button.tsx
index 3da7123982..fbed2e93f8 100644
--- a/web/src/components/nav/in-app-ai-agent-button.tsx
+++ b/web/src/components/nav/in-app-ai-agent-button.tsx
@@ -1,4 +1,11 @@
-import { useState } from "react";
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type CSSProperties,
+} from "react";
+import { createPortal } from "react-dom";
import { Bot } from "lucide-react";
import { Button } from "@/src/components/ui/button";
@@ -10,56 +17,136 @@ import {
DialogHeader,
DialogTitle,
} from "@/src/components/ui/dialog";
-import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";
+import { SidebarMenuButton } from "@/src/components/ui/sidebar";
+import { ControlledInAppAgentWindow } from "@/src/features/in-app-agent/components";
import { useInAppAiAgent } from "@/src/features/in-app-agent/components/InAppAiAgentProvider";
import { AIFeaturesDisabledNotice } from "@/src/features/organizations/components/AIFeaturesDisabledNotice";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { cn } from "@/src/utils/tailwind";
export const InAppAiAgentButton = () => {
const { organization } = useQueryProjectOrOrganization();
- const { isAvailable, setOpen } = useInAppAiAgent();
+ const { isAvailable, open, setOpen, isExpanded, setIsExpanded } =
+ useInAppAiAgent();
const { setOpen: setSupportDrawerOpen } = useSupportDrawer();
- const { isMobile, setOpenMobile: setOpenMobileSidebar } = useSidebar();
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const previousPanelRectRef = useRef<DOMRect | null>(null);
+ const [anchorStyle, setAnchorStyle] = useState<CSSProperties>();
+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(
+ null,
+ );
const [enableDialogOpen, setEnableDialogOpen] = useState(false);
- if (!isAvailable) {
- return null;
- }
- const toggleInAppAiAgent = () => {
- setSupportDrawerOpen(false);
- setOpen((currentOpen) => !currentOpen);
+ const updateAnchorStyle = () => {
+ const button = buttonRef.current;
+
+ if (!button) {
+ return;
+ }
+
+ const rect = button.getBoundingClientRect();
+
+ setAnchorStyle({
+ left: rect.right - 6,
+ });
};
- const handleClick = () => {
- if (isMobile) {
- setOpenMobileSidebar(false);
+ useEffect(() => {
+ setPortalContainer(document.body);
+ }, []);
+
+ useLayoutEffect(() => {
+ const previousRect = previousPanelRectRef.current;
+ const panel = panelRef.current;
+
+ previousPanelRectRef.current = null;
+
+ if (!previousRect || !panel) {
+ return;
}
- if (organization && !organization.aiFeaturesEnabled) {
- setSupportDrawerOpen(false);
- setEnableDialogOpen(true);
+ const nextRect = panel.getBoundingClientRect();
+
+ panel.animate(
+ [
+ {
+ transform: `translate(${previousRect.left - nextRect.left}px, ${previousRect.top - nextRect.top}px) scale(${nextRect.width > 0 ? previousRect.width / nextRect.width : 1}, ${nextRect.height > 0 ? previousRect.height / nextRect.height : 1})`,
+ },
+ { transform: "translate(0, 0) scale(1, 1)" },
+ ],
+ {
+ duration: 180,
+ easing: "cubic-bezier(0.2, 0, 0, 1)",
+ },
+ );
+ }, [isExpanded]);
+
+ useEffect(() => {
+ if (!open || isExpanded) {
return;
}
- if (isMobile) {
- setTimeout(() => {
- // push to next tick to avoid flickering when hiding sidebar on mobile
- toggleInAppAiAgent();
- }, 1);
+ updateAnchorStyle();
+
+ window.addEventListener("resize", updateAnchorStyle);
+ window.addEventListener("scroll", updateAnchorStyle, true);
+
+ return () => {
+ window.removeEventListener("resize", updateAnchorStyle);
+ window.removeEventListener("scroll", updateAnchorStyle, true);
+ };
+ }, [isExpanded, open]);
+
+ if (!isAvailable) {
+ return null;
+ }
+
+ const handleClick = () => {
+ if (organization && !organization.aiFeaturesEnabled) {
+ setSupportDrawerOpen(false);
+ setEnableDialogOpen(true);
return;
}
- toggleInAppAiAgent();
+ updateAnchorStyle();
+ setSupportDrawerOpen(false);
+ setOpen((currentOpen) => !currentOpen);
};
return (
<>
- <SidebarMenuButton isActive={false} onClick={handleClick}>
+ <SidebarMenuButton ref={buttonRef} isActive={open} onClick={handleClick}>
<Bot className="h-4 w-4" />
AI Assistant
</SidebarMenuButton>
-
+ {open && portalContainer
+ ? createPortal(
+ <div
+ ref={panelRef}
+ data-ignore-outside-interaction
+ className={cn(
+ "fixed z-51 origin-top-left",
+ isExpanded
+ ? "inset-x-3 top-[calc(var(--banner-offset)+0.75rem)] bottom-3"
+ : "bottom-2",
+ )}
+ style={isExpanded ? undefined : anchorStyle}
+ >
+ <ControlledInAppAgentWindow
+ isExpanded={isExpanded}
+ onExpandedChange={(nextIsExpanded) => {
+ previousPanelRectRef.current =
+ panelRef.current?.getBoundingClientRect() ?? null;
+ setIsExpanded(nextIsExpanded);
+ }}
+ onClose={() => setOpen(false)}
+ />
+ </div>,
+ portalContainer,
+ )
+ : null}
<Dialog open={enableDialogOpen} onOpenChange={setEnableDialogOpen}>
<DialogContent>
<DialogHeader>
diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsx
index a7b855c2c8..53bc4077fc 100644
--- a/web/src/components/table/peek.tsx
+++ b/web/src/components/table/peek.tsx
@@ -14,6 +14,7 @@ import { cn } from "@/src/utils/tailwind";
import { memo } from "react";
import { useRouter } from "next/router";
import { PeekTableStateProvider } from "@/src/components/table/peek/contexts/PeekTableStateContext";
+import { shouldIgnoreOutsideInteraction } from "@/src/utils/outside-interaction";
type PeekViewItemType = Extract<
LangfuseItemType,
@@ -109,6 +110,11 @@ function TablePeekViewComponent(props: TablePeekViewProps) {
// Prevent the default behavior of closing when clicking outside when we set modal={false}
e.preventDefault();
}}
+ onInteractOutside={(e) => {
+ if (shouldIgnoreOutsideInteraction(e.target)) {
+ e.preventDefault();
+ }
+ }}
side="right"
className="flex max-h-full min-h-0 min-w-[60vw] flex-col gap-0 overflow-hidden p-0"
>
diff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
similarity index 91%
rename from web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx
rename to web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index c8c0833ee4..fdcb326149 100644
--- a/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx
+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -3,9 +3,9 @@
import { useMemo } from "react";
import { z } from "zod";
import {
- InAppAgentDrawer,
- type InAppAgentDrawerMessage,
-} from "./InAppAgentDrawer";
+ InAppAgentWindow,
+ type InAppAgentWindowMessage,
+} from "./InAppAgentWindow";
import type { InAppAgentToolCallContent } from "./InAppAgentMessage";
import { useInAppAiAgent } from "./InAppAiAgentProvider";
import {
@@ -13,18 +13,22 @@ import {
type AgUiMessage,
} from "@/src/features/in-app-agent/schema";
-type ControlledInAppAgentDrawerProps =
+type ControlledInAppAgentWindowProps =
| {
+ isExpanded: boolean;
showCloseButton: false;
+ onExpandedChange: (isExpanded: boolean) => void;
onClose?: () => void;
}
| {
+ isExpanded: boolean;
showCloseButton?: true;
+ onExpandedChange: (isExpanded: boolean) => void;
onClose: () => void;
};
-export function ControlledInAppAgentDrawer(
- props: ControlledInAppAgentDrawerProps,
+export function ControlledInAppAgentWindow(
+ props: ControlledInAppAgentWindowProps,
) {
const {
conversations,
@@ -47,7 +51,7 @@ export function ControlledInAppAgentDrawer(
const parsedMessages = z.array(AgUiMessageSchema).parse(messages);
const toolResults = getToolResultsByToolCallId(parsedMessages);
- const mappedMessages: InAppAgentDrawerMessage[] = [];
+ const mappedMessages: InAppAgentWindowMessage[] = [];
let pendingTools: InAppAgentToolCallContent[] = [];
let pendingToolGroupId: string | null = null;
const flushPendingTools = () => {
@@ -199,7 +203,7 @@ export function ControlledInAppAgentDrawer(
content: hasAssistantAnswer
? { type: "loading" }
: { type: "loading", label: "Connecting..." },
- } satisfies InAppAgentDrawerMessage,
+ } satisfies InAppAgentWindowMessage,
];
}
@@ -212,8 +216,9 @@ export function ControlledInAppAgentDrawer(
: ({ showCloseButton: true, onClose: props.onClose } as const);
return (
- <InAppAgentDrawer
+ <InAppAgentWindow
error={error}
+ isExpanded={props.isExpanded}
isInputDisabled={isInputDisabled}
messages={drawerMessages}
conversations={conversations}
@@ -223,6 +228,7 @@ export function ControlledInAppAgentDrawer(
onLoadMoreConversations={loadMoreConversations}
onSelectConversation={selectConversation}
onNewConversation={() => selectConversation(null)}
+ onExpandedChange={props.onExpandedChange}
onSubmit={submit}
{...closeButtonProps}
/>
diff --git a/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx b/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx
deleted file mode 100644
index a628392ab0..0000000000
--- a/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx
+++ /dev/null
@@ -1,309 +0,0 @@
-"use client";
-
-import { type KeyboardEvent, useEffect, useRef, useState } from "react";
-import { PanelRightClose, Plus, SendHorizontal } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { cn } from "@/src/utils/tailwind";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectSeparator,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import {
- InAppAgentMessage,
- type InAppAgentMessageContent,
- type InAppAgentMessageRole,
-} from "./InAppAgentMessage";
-
-const AUTO_SCROLL_THRESHOLD_PX = 200;
-const NEW_CONVERSATION_VALUE = "__new__";
-const LOAD_MORE_CONVERSATIONS_VALUE = "__load_more__";
-
-export type InAppAgentDrawerMessage = {
- id: string;
- role: InAppAgentMessageRole;
- content: InAppAgentMessageContent;
-};
-
-export type InAppAgentDrawerConversation = {
- id: string;
- title: string | null;
- updatedAt: Date;
-};
-
-type InAppAgentDrawerCloseButtonProps =
- | {
- showCloseButton: false;
- onClose?: () => void;
- }
- | {
- showCloseButton?: true;
- onClose: () => void;
- };
-
-export type InAppAgentDrawerProps = {
- error: string | null;
- isInputDisabled: boolean;
- messages: InAppAgentDrawerMessage[];
- conversations: InAppAgentDrawerConversation[];
- hasMoreConversations: boolean;
- isLoadingMoreConversations: boolean;
- selectedConversationId: string | undefined;
- onLoadMoreConversations: () => void;
- onSelectConversation: (conversationId: string) => void;
- onNewConversation: () => void;
- onSubmit: (input: string) => Promise<boolean>;
-} & InAppAgentDrawerCloseButtonProps;
-
-export function InAppAgentDrawer(props: InAppAgentDrawerProps) {
- const {
- conversations,
- error,
- hasMoreConversations,
- isInputDisabled,
- isLoadingMoreConversations,
- messages,
- onLoadMoreConversations,
- onNewConversation,
- onSelectConversation,
- onSubmit,
- selectedConversationId,
- } = props;
- const viewportRef = useRef<HTMLDivElement>(null);
- const scrollPositionRef = useRef<{
- scrollHeight: number;
- scrollTop: number;
- clientHeight: number;
- } | null>(null);
- const inputRef = useRef<HTMLTextAreaElement>(null);
- const [input, setInput] = useState("");
-
- useEffect(() => {
- const viewport = viewportRef.current;
-
- if (!viewport) {
- return;
- }
-
- const scrollPosition = scrollPositionRef.current;
- const isNearBottom =
- !scrollPosition ||
- scrollPosition.scrollHeight -
- scrollPosition.scrollTop -
- scrollPosition.clientHeight <=
- AUTO_SCROLL_THRESHOLD_PX;
-
- if (!isNearBottom) {
- return;
- }
-
- viewport.scrollTo({
- top: viewport.scrollHeight,
- behavior: "smooth",
- });
- }, [messages]);
-
- useEffect(() => {
- const input = inputRef.current;
-
- if (!input) {
- return;
- }
-
- input.style.height = "auto";
- input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
- }, [input]);
-
- return (
- <section className="bg-background flex h-full min-w-0 flex-col">
- <header className="bg-background flex h-11.25 shrink-0 items-center justify-between border-b px-3">
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <div className="min-w-0">
- <p className="truncate text-sm font-semibold">AI Assistant</p>
- </div>
- <Select
- value={selectedConversationId ?? NEW_CONVERSATION_VALUE}
- onValueChange={(value) => {
- if (value === NEW_CONVERSATION_VALUE) {
- onNewConversation();
- return;
- }
-
- if (value === LOAD_MORE_CONVERSATIONS_VALUE) {
- onLoadMoreConversations();
- return;
- }
-
- onSelectConversation(value);
- }}
- disabled={isInputDisabled}
- >
- <SelectTrigger
- aria-label="Select agent conversation"
- className="h-8 max-w-52 min-w-0 flex-1"
- >
- <SelectValue placeholder="New conversation" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={NEW_CONVERSATION_VALUE}>
- New conversation
- </SelectItem>
- {conversations.map((conversation) => (
- <SelectItem key={conversation.id} value={conversation.id}>
- {conversation.title?.trim() || "Untitled conversation"}
- </SelectItem>
- ))}
- {hasMoreConversations ? (
- <>
- <SelectSeparator />
- <SelectItem
- value={LOAD_MORE_CONVERSATIONS_VALUE}
- className="h-8"
- disabled={isLoadingMoreConversations}
- >
- {isLoadingMoreConversations ? "Loading..." : "Load more"}
- </SelectItem>
- </>
- ) : null}
- </SelectContent>
- </Select>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="h-8 w-8 shrink-0"
- onClick={onNewConversation}
- disabled={isInputDisabled}
- aria-label="Start new AI agent conversation"
- >
- <Plus className="h-4 w-4" />
- </Button>
- </div>
- {props.showCloseButton !== false && (
- <Button
- variant="ghost"
- size="icon"
- onClick={props.onClose}
- aria-label="Close AI agent drawer"
- >
- <PanelRightClose className="h-4 w-4" />
- </Button>
- )}
- </header>
- <div className="flex min-h-0 flex-1 flex-col">
- <div
- ref={viewportRef}
- className="min-h-0 flex-1 overflow-y-auto"
- onScroll={(event) => {
- const viewport = event.currentTarget;
- scrollPositionRef.current = {
- scrollHeight: viewport.scrollHeight,
- scrollTop: viewport.scrollTop,
- clientHeight: viewport.clientHeight,
- };
- }}
- >
- <div className="flex w-full flex-col gap-4 px-3 py-4">
- {messages.length === 0 ? (
- <div className="border-border rounded-2xl border border-dashed px-4 py-3">
- <p className="text-muted-foreground text-sm">
- Ask about Langfuse
- </p>
- </div>
- ) : null}
-
- <ol className="flex w-full flex-col gap-3">
- {messages.map((message) => {
- const hasToolContent = message.content.type === "toolGroup";
-
- return (
- <li
- key={message.id}
- className={cn(
- "max-w-[92%]",
- hasToolContent ? "w-full" : "w-fit",
- message.role === "user" && "ml-auto",
- )}
- >
- <InAppAgentMessage
- role={message.role}
- content={message.content}
- />
- </li>
- );
- })}
- </ol>
-
- {error ? (
- <div
- role="alert"
- className="border-destructive/40 bg-destructive/10 text-destructive rounded-lg border px-3 py-2 text-sm"
- >
- {error}
- </div>
- ) : null}
- </div>
- </div>
- <div className="bg-background border-t p-3">
- <form
- className="flex w-full items-end gap-2"
- onSubmit={(event) => {
- event.preventDefault();
-
- const content = input.trim();
-
- if (!content || isInputDisabled) {
- return;
- }
-
- onSubmit(content)
- .then((accepted) => {
- if (!accepted) {
- return;
- }
-
- setInput((currentInput) =>
- currentInput.trim() === content ? "" : currentInput,
- );
- })
- .catch(() => undefined);
- }}
- >
- <textarea
- ref={inputRef}
- value={input}
- onChange={(event) => setInput(event.target.value)}
- onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (
- event.key === "Enter" &&
- !event.shiftKey &&
- !event.nativeEvent.isComposing
- ) {
- event.preventDefault();
- event.currentTarget.form?.requestSubmit();
- }
- }}
- disabled={isInputDisabled}
- aria-label="Ask about Langfuse"
- placeholder="Ask about Langfuse..."
- rows={1}
- className="bg-background placeholder:text-muted-foreground border-input max-h-40 min-h-10 flex-1 resize-none overflow-y-auto rounded-md px-3 py-2 text-sm leading-5 disabled:cursor-not-allowed disabled:opacity-60"
- />
- <Button
- type="submit"
- size="icon"
- className="h-10 w-10 rounded-md"
- aria-label="Send message"
- disabled={isInputDisabled || !input.trim()}
- >
- <SendHorizontal className="h-4 w-4" />
- </Button>
- </form>
- </div>
- </div>
- </section>
- );
-}
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
index a90d9e471f..723bfcabef 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
@@ -21,7 +21,12 @@ export const AssistantMarkdown = meta.story({
content: {
type: "text",
text: [
- "## Debugging checklist",
+ "# Heading 1",
+ "## Heading 2",
+ "### Heading 3",
+ "#### Heading 4",
+ "##### Heading 5",
+ "###### Heading 6",
"",
"You can use **Langfuse** to inspect _production traces_ and compare `input`, `output`, and metadata across releases.",
"",
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
index 170b48e288..db3d27c7ec 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -27,15 +27,31 @@ export type InAppAgentToolCallContent = {
export type InAppAgentMessageProps = {
role: InAppAgentMessageRole;
content: InAppAgentMessageContent;
+ isCompact?: boolean;
};
-export function InAppAgentMessage({ role, content }: InAppAgentMessageProps) {
+export function InAppAgentMessage({
+ role,
+ content,
+ isCompact = false,
+}: InAppAgentMessageProps) {
const isUser = role === "user";
if (content.type === "toolGroup") {
return (
- <div className="bg-card text-card-foreground border-border rounded-2xl border py-2 text-sm shadow-xs">
- <ToolCallGroup tools={content.tools} isLoading={content.isLoading} />
+ <div
+ className={cn(
+ "bg-card dark:bg-header text-card-foreground border-border rounded-2xl border py-2 shadow-xs",
+ isCompact
+ ? "rounded-xl py-1 text-[0.775rem]"
+ : "rounded-2xl py-1.5 text-sm",
+ )}
+ >
+ <ToolCallGroup
+ tools={content.tools}
+ isLoading={content.isLoading}
+ isCompact={isCompact}
+ />
</div>
);
}
@@ -43,16 +59,19 @@ export function InAppAgentMessage({ role, content }: InAppAgentMessageProps) {
return (
<div
className={cn(
- "rounded-2xl px-3.5 py-2.5 text-sm shadow-xs",
+ "shadow-xs",
+ isCompact
+ ? "rounded-xl px-2.5 py-1 text-[0.775rem]"
+ : "rounded-2xl px-3 py-1.5 text-sm",
isUser
? "bg-primary text-primary-foreground"
- : "bg-card text-card-foreground border-border border",
+ : "bg-card dark:bg-header text-card-foreground border-border border",
)}
>
{content.type === "loading" ? (
- <ThinkingIndicator label={content.label} />
+ <ThinkingIndicator label={content.label} isCompact={isCompact} />
) : (
- <MessageText role={role} text={content.text} />
+ <MessageText role={role} text={content.text} isCompact={isCompact} />
)}
</div>
);
@@ -61,19 +80,34 @@ export function InAppAgentMessage({ role, content }: InAppAgentMessageProps) {
function ToolCallGroup({
tools,
isLoading = false,
+ isCompact = false,
}: {
tools: InAppAgentToolCallContent[];
isLoading?: boolean;
+ isCompact?: boolean;
}) {
const label = `${isLoading ? "Calling" : "Called"} ${tools.length} ${tools.length === 1 ? "tool" : "tools"}`;
+ const paddingX = cn(isCompact ? "px-2.5" : "px-3");
+ const iconSize = isCompact ? "size-3" : "size-4";
+
return (
<details className="group/tool-group min-w-0">
- <summary className="flex cursor-pointer list-none items-center gap-2 px-3.5 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden">
+ <summary
+ className={cn(
+ "flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden",
+ paddingX,
+ )}
+ >
{isLoading ? (
- <Loader2 className="text-muted-foreground h-3.5 w-3.5 shrink-0 animate-spin" />
+ <Loader2
+ className={cn(
+ "text-muted-foreground shrink-0 animate-spin",
+ iconSize,
+ )}
+ />
) : (
- <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
+ <Wrench className={cn("text-muted-foreground shrink-0", iconSize)} />
)}
<span className="min-w-0 flex-1 truncate">{label}</span>
<span className="text-muted-foreground text-xs group-open/tool-group:hidden">
@@ -83,7 +117,9 @@ function ToolCallGroup({
Hide
</span>
</summary>
- <div className="border-border mt-2 space-y-2 border-t px-3.5 pt-2">
+ <div
+ className={cn("border-border mt-2 space-y-2 border-t pt-2", paddingX)}
+ >
{tools.map((tool, index) => (
<div key={`${tool.name}-${index}`} className="rounded-lg">
<ToolCallDetails tool={tool} />
@@ -164,16 +200,34 @@ function ToolPayload({
function MessageText({
role,
text,
+ isCompact,
}: {
role: InAppAgentMessageRole;
text: string;
+ isCompact: boolean;
}) {
if (role === "user") {
- return <p className="leading-5.5 whitespace-pre-wrap">{text}</p>;
+ return (
+ <p
+ className={cn(
+ "whitespace-pre-wrap",
+ isCompact ? "leading-4" : "leading-4.5",
+ )}
+ >
+ {text}
+ </p>
+ );
}
return (
- <div className="prose prose-sm text-foreground prose-headings:my-2.5 prose-p:my-1.5 prose-ul:my-1.5 prose-li:my-1 prose-ol:my-1.5 prose-strong:text-inherit prose-blockquote:my-2.5 prose-pre:my-2.5 prose-pre:bg-muted prose-pre:text-foreground prose-code:text-foreground prose-table:my-2.5 max-w-none leading-5.5">
+ <div
+ className={cn(
+ "prose prose-sm text-foreground prose-strong:text-inherit prose-pre:bg-muted prose-pre:text-foreground prose-code:text-foreground prose-table:m-0! prose-headings:text-inherit dark:prose-pre:bg-card prose-pre:leading-tight prose-table:border prose-td:p-2 prose-th:p-2 prose-table:bg-muted dark:prose-table:bg-card prose-table:overflow-hidden prose-table:rounded prose-tr:border-b prose-tr:border-border dark:prose-tr:border-border prose-headings:text-sm prose-hr:border-border max-w-none",
+ isCompact
+ ? "prose-headings:my-2 prose-p:my-1 prose-ul:my-1 prose-li:my-0.5 prose-ol:my-1 prose-blockquote:my-2 prose-pre:my-2 prose-table:my-2 prose-th:text-xs prose-hr:my-3 text-[0.775rem] leading-4"
+ : "prose-headings:my-2.5 prose-p:my-1.5 prose-ul:my-1.5 prose-li:my-1 prose-ol:my-1.5 prose-blockquote:my-2.5 prose-pre:my-2.5 prose-table:my-2.5 prose-th:text-sm prose-hr:my-5 leading-4.5",
+ )}
+ >
<Streamdown
// Remove all default classNames so that tailwind's prose styling can be applied without conflicts
components={{
@@ -183,12 +237,14 @@ function MessageText({
h4: ({ children }) => <h4>{children}</h4>,
h5: ({ children }) => <h5>{children}</h5>,
h6: ({ children }) => <h6>{children}</h6>,
+
p: ({ children }) => <p>{children}</p>,
a: ({ children, href }) => (
<a href={href} target="_blank" rel="noopener noreferrer">
{children}
</a>
),
+ hr: ({ children }) => <hr>{children}</hr>,
ul: ({ children }) => <ul>{children}</ul>,
ol: ({ children }) => <ol>{children}</ol>,
li: ({ children }) => <li>{children}</li>,
@@ -198,6 +254,12 @@ function MessageText({
em: ({ children }) => <em>{children}</em>,
code: ({ children }) => <code>{children}</code>,
pre: ({ children }) => <pre>{children}</pre>,
+ thead: ({ children }) => <thead>{children}</thead>,
+ tbody: ({ children }) => <tbody>{children}</tbody>,
+ tr: ({ children }) => <tr>{children}</tr>,
+ th: ({ children }) => <th>{children}</th>,
+ td: ({ children }) => <td>{children}</td>,
+ table: ({ children }) => <table>{children}</table>,
}}
>
{text}
@@ -209,13 +271,23 @@ function MessageText({
function ThinkingIndicator({
className,
label = "Thinking...",
+ isCompact = false,
}: {
className?: string;
label?: string;
+ isCompact?: boolean;
}) {
return (
- <div className={cn("flex items-center gap-2 text-sm", className)}>
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ <div
+ className={cn(
+ "flex items-center",
+ isCompact ? "gap-1.5 text-[0.775rem]" : "gap-2 text-sm",
+ className,
+ )}
+ >
+ <Loader2
+ className={cn("animate-spin", isCompact ? "h-3 w-3" : "h-3.5 w-3.5")}
+ />
<span>{label}</span>
</div>
);
diff --git a/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
similarity index 71%
rename from web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx
rename to web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
index 046dd64637..7376167ca5 100644
--- a/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
@@ -1,6 +1,24 @@
import preview from "../../../../.storybook/preview";
+import { useArgs } from "storybook/preview-api";
import { fn } from "storybook/test";
-import { InAppAgentDrawer } from "./InAppAgentDrawer";
+import {
+ InAppAgentWindow,
+ type InAppAgentWindowProps,
+} from "./InAppAgentWindow";
+
+function StatefulInAppAgentWindow(args: InAppAgentWindowProps) {
+ const [, updateArgs] = useArgs<InAppAgentWindowProps>();
+
+ return (
+ <InAppAgentWindow
+ {...args}
+ onExpandedChange={(isExpanded) => {
+ updateArgs({ isExpanded });
+ args.onExpandedChange(isExpanded);
+ }}
+ />
+ );
+}
const conversations = [
{
@@ -16,19 +34,20 @@ const conversations = [
];
const meta = preview.meta({
- component: InAppAgentDrawer,
+ component: InAppAgentWindow,
parameters: {
layout: "fullscreen",
},
decorators: [
(Story) => (
- <div className="h-screen w-full">
+ <div className="flex h-screen w-full items-center justify-center">
<Story />
</div>
),
],
args: {
error: null,
+ isExpanded: false,
isInputDisabled: false,
conversations,
hasMoreConversations: false,
@@ -38,9 +57,11 @@ const meta = preview.meta({
onNewConversation: fn(),
onSelectConversation: fn(),
onClose: fn(),
+ onExpandedChange: fn(),
onSubmit: fn(),
showCloseButton: true,
},
+ render: StatefulInAppAgentWindow,
});
export const Empty = meta.story({
@@ -113,6 +134,57 @@ export const Conversation = meta.story({
text: "Yes. Add score filters or group the traces by score name to see whether latency correlates with lower quality.",
},
},
+ {
+ id: "assistant-3",
+ role: "assistant",
+ content: {
+ type: "text",
+ text: [
+ "# Heading 1",
+ "## Heading 2",
+ "### Heading 3",
+ "#### Heading 4",
+ "##### Heading 5",
+ "###### Heading 6",
+ "",
+ "You can use **Langfuse** to inspect _production traces_ and compare `input`, `output`, and metadata across releases.",
+ "",
+ "- Inspect traces with nested observations",
+ "- Evaluate outputs with scores",
+ "- Monitor production quality over time",
+ "",
+ "1. Filter for `level = ERROR`.",
+ "2. Open the slowest trace.",
+ "3. Compare model settings and prompt versions.",
+ "",
+ "> Tip: add scores and metadata early so regressions are easier to segment later.",
+ "",
+ "| Signal | Where to look |",
+ "| --- | --- |",
+ "| Latency | Observation timings |",
+ "| Cost | Usage and model pricing |",
+ "| Quality | Scores and comments |",
+ "",
+ "```ts",
+ "const trace = {",
+ ' name: "checkout-agent",',
+ ' environment: "production",',
+ ' metadata: { region: "eu" },',
+ "};",
+ "```",
+ "",
+ "Streaming partial markdown:",
+ "",
+ "- The assistant can render a list item while it is still streaming",
+ "- It can also keep an unfinished **bold phrase",
+ "",
+ "```json",
+ "{",
+ ' "status": "streaming",',
+ ' "next": "content still arriving"',
+ ].join("\n"),
+ },
+ },
],
},
});
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
new file mode 100644
index 0000000000..e5fbc27296
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -0,0 +1,400 @@
+"use client";
+
+import { type KeyboardEvent, useEffect, useRef, useState } from "react";
+import {
+ BotMessageSquare,
+ History,
+ Maximize2,
+ Minimize2,
+ Plus,
+ SendHorizontal,
+ X,
+} from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { cn } from "@/src/utils/tailwind";
+import {
+ InAppAgentMessage,
+ type InAppAgentMessageContent,
+ type InAppAgentMessageRole,
+} from "./InAppAgentMessage";
+
+const AUTO_SCROLL_THRESHOLD_PX = 200;
+
+export type InAppAgentWindowMessage = {
+ id: string;
+ role: InAppAgentMessageRole;
+ content: InAppAgentMessageContent;
+};
+
+export type InAppAgentWindowConversation = {
+ id: string;
+ title: string | null;
+ updatedAt: Date;
+};
+
+type InAppAgentWindowCloseButtonProps =
+ | {
+ showCloseButton: false;
+ onClose?: () => void;
+ }
+ | {
+ showCloseButton?: true;
+ onClose: () => void;
+ };
+
+export type InAppAgentWindowProps = {
+ conversations: InAppAgentWindowConversation[];
+ error: string | null;
+ hasMoreConversations: boolean;
+ isExpanded: boolean;
+ isInputDisabled: boolean;
+ isLoadingMoreConversations: boolean;
+ messages: InAppAgentWindowMessage[];
+ onExpandedChange: (isExpanded: boolean) => void;
+ onLoadMoreConversations: () => void;
+ onNewConversation: () => void;
+ onSelectConversation: (conversationId: string) => void;
+ onSubmit: (input: string) => boolean | Promise<boolean>;
+ selectedConversationId: string | undefined;
+} & InAppAgentWindowCloseButtonProps;
+
+export function InAppAgentWindow(props: InAppAgentWindowProps) {
+ const {
+ conversations,
+ error,
+ hasMoreConversations,
+ isExpanded,
+ isInputDisabled,
+ isLoadingMoreConversations,
+ messages,
+ onExpandedChange,
+ onLoadMoreConversations,
+ onNewConversation,
+ onSelectConversation,
+ onSubmit,
+ selectedConversationId,
+ } = props;
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const scrollPositionRef = useRef<{
+ scrollHeight: number;
+ scrollTop: number;
+ clientHeight: number;
+ } | null>(null);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const [input, setInput] = useState("");
+
+ useEffect(() => {
+ const viewport = viewportRef.current;
+
+ if (!viewport) {
+ return;
+ }
+
+ const scrollPosition = scrollPositionRef.current;
+ const isNearBottom =
+ !scrollPosition ||
+ scrollPosition.scrollHeight -
+ scrollPosition.scrollTop -
+ scrollPosition.clientHeight <=
+ AUTO_SCROLL_THRESHOLD_PX;
+
+ if (!isNearBottom) {
+ return;
+ }
+
+ viewport.scrollTo({
+ top: viewport.scrollHeight,
+ behavior: "smooth",
+ });
+ }, [messages]);
+
+ useEffect(() => {
+ const input = inputRef.current;
+
+ if (!input) {
+ return;
+ }
+
+ input.style.height = "auto";
+ input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
+ }, [input]);
+
+ return (
+ <section
+ className={cn(
+ "bg-background flex min-w-0 flex-col overflow-hidden rounded-xl border shadow/5",
+ isExpanded
+ ? "h-full min-h-0 w-full"
+ : "h-[min(42rem,calc(100vh-var(--banner-offset)-2rem))] min-h-96 w-[min(28rem,calc(100vw-1rem))]",
+ )}
+ >
+ <header className="bg-header flex min-h-11.25 shrink-0 items-center justify-between gap-2 border-b px-3 py-1">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <p className="shrink-0 truncate text-sm font-semibold">
+ AI Assistant
+ </p>
+ <span className="text-muted-foreground rounded border px-1.5 py-1 text-xs leading-none font-medium">
+ Beta
+ </span>
+ </div>
+ <div className="flex shrink-0 items-center gap-0.5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-6 shrink-0"
+ onClick={onNewConversation}
+ disabled={isInputDisabled}
+ aria-label="Start new AI agent conversation"
+ >
+ <Plus className="size-3" />
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-6 shrink-0"
+ disabled={isInputDisabled}
+ aria-label="Conversation history"
+ >
+ <History className="size-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-64">
+ <DropdownMenuLabel>Recent conversations</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {conversations.length === 0 ? (
+ <DropdownMenuItem disabled>
+ No conversations yet
+ </DropdownMenuItem>
+ ) : (
+ conversations.map((conversation) => (
+ <DropdownMenuItem
+ key={conversation.id}
+ className={cn(
+ "truncate",
+ conversation.id === selectedConversationId &&
+ "bg-accent text-accent-foreground",
+ )}
+ onSelect={() => onSelectConversation(conversation.id)}
+ >
+ {conversation.title?.trim() || "Untitled conversation"}
+ </DropdownMenuItem>
+ ))
+ )}
+ {hasMoreConversations ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={isLoadingMoreConversations}
+ onSelect={onLoadMoreConversations}
+ >
+ {isLoadingMoreConversations ? "Loading..." : "Load more"}
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-6"
+ aria-label={isExpanded ? "Collapse window" : "Expand window"}
+ onClick={() => onExpandedChange(!isExpanded)}
+ >
+ {isExpanded ? (
+ <Minimize2 className="size-3" />
+ ) : (
+ <Maximize2 className="size-3" />
+ )}
+ </Button>
+ {props.showCloseButton !== false ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-6"
+ aria-label="Close assistant"
+ onClick={props.onClose}
+ >
+ <X className="size-3" />
+ </Button>
+ ) : null}
+ </div>
+ </header>
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div
+ ref={viewportRef}
+ className="min-h-0 flex-1 overflow-y-auto"
+ onScroll={(event) => {
+ const viewport = event.currentTarget;
+ scrollPositionRef.current = {
+ scrollHeight: viewport.scrollHeight,
+ scrollTop: viewport.scrollTop,
+ clientHeight: viewport.clientHeight,
+ };
+ }}
+ >
+ <div
+ className={cn(
+ "flex h-full w-full flex-col gap-4 py-4",
+ isExpanded && "mx-auto max-w-3xl",
+ isExpanded ? "px-0" : "px-3",
+ )}
+ >
+ {messages.length === 0 ? (
+ <div className="flex h-full w-full flex-1 flex-col items-center justify-center">
+ <div>
+ <BotMessageSquare className="text-muted-foreground mx-auto h-8 w-8" />
+ </div>
+ <p className="text-muted-foreground mt-4 text-sm">
+ Welcome to the Langfuse Assistant
+ </p>
+ <p className="text-muted-foreground/60 mt-2 max-w-xs text-center text-sm leading-relaxed">
+ I can help you with any questions you have about Langfuse or
+ assist you in exploring your event data.
+ <br />
+ Just ask me anything!
+ </p>
+ </div>
+ ) : null}
+
+ <ol className="flex w-full flex-col gap-3 pb-4">
+ {messages.map((message) => {
+ const hasToolContent = message.content.type === "toolGroup";
+
+ return (
+ <li
+ key={message.id}
+ className={cn(
+ "max-w-[92%]",
+ hasToolContent ? "w-full" : "w-fit",
+ message.role === "user" && "ml-auto",
+ )}
+ >
+ <InAppAgentMessage
+ role={message.role}
+ content={message.content}
+ isCompact={!isExpanded}
+ />
+ </li>
+ );
+ })}
+ </ol>
+
+ {error ? (
+ <div
+ role="alert"
+ className={cn(
+ "border-destructive/40 dark:bg-destructive dark:border-destructive-foreground/20 bg-destructive/10 dark:text-destructive-foreground text-destructive rounded-lg border px-2 py-1",
+ isExpanded ? "text-sm" : "text-xs",
+ )}
+ >
+ {error}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ <div
+ className={cn("p-1.5", isExpanded ? "pt-0" : "bg-header border-t")}
+ >
+ <form
+ className={cn(
+ "relative flex w-full items-end gap-2 rounded-md",
+ isExpanded &&
+ "mx-auto max-w-3xl cursor-text flex-col border focus-within:ring focus-within:ring-blue-500 focus-within:ring-offset-0",
+ )}
+ onClick={() => {
+ if (isExpanded) {
+ inputRef.current?.focus();
+ }
+ }}
+ onSubmit={(event) => {
+ event.preventDefault();
+
+ const content = input.trim();
+
+ if (!content || isInputDisabled) {
+ return;
+ }
+
+ Promise.resolve(onSubmit(content))
+ .then((submitted) => {
+ if (submitted) {
+ setInput((currentInput) =>
+ currentInput.trim() === content ? "" : currentInput,
+ );
+ }
+ })
+ .catch(() => undefined);
+ }}
+ >
+ <textarea
+ ref={inputRef}
+ value={input}
+ onChange={(event) => setInput(event.target.value)}
+ onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (
+ event.key === "Enter" &&
+ !event.shiftKey &&
+ !event.nativeEvent.isComposing
+ ) {
+ event.preventDefault();
+ event.currentTarget.form?.requestSubmit();
+ }
+ }}
+ disabled={isInputDisabled}
+ aria-label="Ask about Langfuse"
+ placeholder="Ask about Langfuse..."
+ rows={1}
+ className={cn(
+ "bg-background placeholder:text-muted-foreground w-full flex-1 resize-none overflow-y-auto rounded-md text-sm leading-5 disabled:cursor-not-allowed disabled:opacity-60",
+ isExpanded
+ ? "max-h-40 min-h-14 border-none ring-0"
+ : "border-input max-h-40 min-h-8 px-3 py-1",
+ )}
+ />
+ {!isExpanded && (
+ <Button
+ type="submit"
+ size="icon"
+ className="h-8 w-8 rounded-md border"
+ aria-label="Send message"
+ disabled={isInputDisabled || !input.trim()}
+ >
+ <SendHorizontal className="h-4 w-4" />
+ </Button>
+ )}
+
+ {isExpanded && (
+ <div className="flex w-full justify-end p-1">
+ <Button
+ type="submit"
+ className="h-8 w-fit rounded-md px-3"
+ aria-label="Send message"
+ disabled={isInputDisabled || !input.trim()}
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ >
+ Send <SendHorizontal className="ml-2 h-4 w-4" />
+ </Button>
+ </div>
+ )}
+ </form>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
index f207d1af7b..e485f15dea 100644
--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -44,6 +44,8 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
isAvailable: false,
open: false,
setOpen: () => undefined,
+ isExpanded: false,
+ setIsExpanded: () => undefined,
isRunning: false,
isSubmitting: false,
isSelectedConversationHydrating: false,
@@ -70,6 +72,8 @@ type InAppAiAgentContextType = {
isAvailable: boolean;
open: boolean;
setOpen: Dispatch<SetStateAction<boolean>>;
+ isExpanded: boolean;
+ setIsExpanded: Dispatch<SetStateAction<boolean>>;
isRunning: boolean;
isSubmitting: boolean;
isSelectedConversationHydrating: boolean;
@@ -153,6 +157,7 @@ function InAppAiAgentProviderInner({
>(`${SELECTED_CONVERSATION_STORAGE_KEY_PREFIX}:${projectId}`, null);
const [messages, setMessages] = useState<InAppAiAgentMessage[]>([]);
const [isRunning, setIsRunning] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const agentRef = useRef<HttpAgent | null>(null);
@@ -485,11 +490,19 @@ function InAppAiAgentProviderInner({
],
);
+ useEffect(() => {
+ if (!open) {
+ setIsExpanded(false);
+ }
+ }, [open]);
+
const value = useMemo<InAppAiAgentContextType>(
() => ({
isAvailable: true,
open,
setOpen,
+ isExpanded,
+ setIsExpanded,
isRunning,
isSubmitting,
isSelectedConversationHydrating,
@@ -504,6 +517,7 @@ function InAppAiAgentProviderInner({
submit,
}),
[
+ isExpanded,
conversations,
error,
hasMoreConversations,
diff --git a/web/src/features/in-app-agent/components/index.ts b/web/src/features/in-app-agent/components/index.ts
index 038952d550..529abf1d06 100644
--- a/web/src/features/in-app-agent/components/index.ts
+++ b/web/src/features/in-app-agent/components/index.ts
@@ -1,2 +1,2 @@
-export { ControlledInAppAgentDrawer } from "./ControlledInAppAgentDrawer";
+export { ControlledInAppAgentWindow } from "./ControlledInAppAgentWindow";
export { InAppAiAgentProvider, useInAppAiAgent } from "./InAppAiAgentProvider";
diff --git a/web/src/utils/outside-interaction.ts b/web/src/utils/outside-interaction.ts
new file mode 100644
index 0000000000..185ac58489
--- /dev/null
+++ b/web/src/utils/outside-interaction.ts
@@ -0,0 +1,11 @@
+export const IGNORE_OUTSIDE_INTERACTION_ATTRIBUTE =
+ "data-ignore-outside-interaction";
+
+export const IGNORE_OUTSIDE_INTERACTION_SELECTOR = `[${IGNORE_OUTSIDE_INTERACTION_ATTRIBUTE}]`;
+
+export function shouldIgnoreOutsideInteraction(target: EventTarget | null) {
+ return (
+ target instanceof Element &&
+ Boolean(target.closest(IGNORE_OUTSIDE_INTERACTION_SELECTOR))
+ );
+}