🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(in-app-agent): internal session menu next to the assistant title (#18253)
Nimar860f5aaf3b09
diff --git a/web/src/__tests__/server/in-app-agent-router.servertest.ts b/web/src/__tests__/server/in-app-agent-router.servertest.tsindex 302d1eeef2..f1b12f7263 100644--- a/web/src/__tests__/server/in-app-agent-router.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-router.servertest.ts@@ -4,6 +4,7 @@ import type { Session } from "next-auth";import { describe, expect, it } from "vitest";import { prisma } from "@langfuse/shared/src/db";+import { env } from "@/src/env.mjs";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -92,6 +93,36 @@ describe("in-app agent router", () => {conversationId: conversation.id,});});++ it("exposes the telemetry project to internal users only", async () => {+ const fixture = await createProjectFixture();+ const userCaller = createCallerForFixture(fixture, fixture.ownerUserId);+ const adminCaller = createCallerForFixture(fixture, fixture.ownerUserId, {+ admin: true,+ });+ const originalAiFeaturesProjectId = env.LANGFUSE_AI_FEATURES_PROJECT_ID;++ try {+ (+ env as { LANGFUSE_AI_FEATURES_PROJECT_ID?: string }+ ).LANGFUSE_AI_FEATURES_PROJECT_ID = "ai-features-project";++ await expect(+ userCaller.inAppAgent.telemetryProject({+ projectId: fixture.projectId,+ }),+ ).rejects.toThrow("internal surface");+ await expect(+ adminCaller.inAppAgent.telemetryProject({+ projectId: fixture.projectId,+ }),+ ).resolves.toEqual({ projectId: "ai-features-project" });+ } finally {+ (+ env as { LANGFUSE_AI_FEATURES_PROJECT_ID?: string }+ ).LANGFUSE_AI_FEATURES_PROJECT_ID = originalAiFeaturesProjectId;+ }+ });});async function createCaller() {@@ -154,6 +185,7 @@ async function createProjectFixture() {function createCallerForFixture(fixture: Awaited<ReturnType<typeof createProjectFixture>>,userId: string,+ { admin = false }: { admin?: boolean } = {},) {const session: Session = {expires: "1",@@ -187,7 +219,7 @@ function createCallerForFixture(},],featureFlags: testFeatureFlags(),- admin: false,+ admin,},environment: {enableExperimentalFeatures: false,diff --git a/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx b/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsxindex f075225100..738f97e80b 100644--- a/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx+++ b/web/src/components/design-system/DropdownMenu/DropdownMenu.stories.tsx@@ -39,6 +39,14 @@ const meta = preview.meta({export const Default = meta.story({});+export const Internal = meta.story({+ args: {+ title: undefined,+ ariaLabel: "Session actions",+ internal: true,+ },+});+export const ManyItems = meta.story({args: {items: Array.from({ length: 20 }, (_, index) => ({diff --git a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsxindex 765a1dc6c1..59e4d5fc06 100644--- a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx+++ b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx@@ -31,6 +31,7 @@ import * as React from "react";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";import { useScrollGradients } from "@/src/hooks/useScrollGradients";+import { Badge } from "@/src/components/design-system/Badge/Badge";import { Checkbox } from "@/src/components/design-system/Checkbox/Checkbox";const menuVariants = cva(@@ -193,6 +194,8 @@ type DropdownMenuProps = {placement?: Placement;search?: { placeholder: string };title?: string;+ /** Marks an internal-only menu with the Internal badge in the header. */+ internal?: boolean;description?: string;};@@ -216,12 +219,14 @@ function DropdownMenuNode({children,description,disabled = false,+ internal = false,items,maxHeight = "15rem",placement = "bottom-start",search,title,}: DropdownMenuProps) {+ const hasHeader = Boolean(title) || internal;const [isOpen, setIsOpen] = React.useState(false);const [activeIndex, setActiveIndex] = React.useState<number | null>(null);const [searchQuery, setSearchQuery] = React.useState("");@@ -350,9 +355,16 @@ function DropdownMenuNode({}: {})}>- {title ? (+ {hasHeader ? (<div className="border-border bg-popover sticky top-0 z-1 border-b px-3 py-2.5 text-sm font-bold">- {title}+ {internal ? (+ <div className="flex items-center gap-2">+ {title}+ <Badge text="Internal" color="yellow" size="sm" />+ </div>+ ) : (+ title+ )}{description && (<p className="text-muted-foreground mt-1 text-xs font-normal">{description}@@ -399,7 +411,7 @@ function DropdownMenuNode({) : null}<divclassName={menuBodyVariants({- hasTitle: Boolean(title || search),+ hasTitle: hasHeader || Boolean(search),showBottomGradient: bottom,showTopGradient: top,})}diff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsxindex c186f2a819..4a3939a9dc 100644--- a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx@@ -8,6 +8,8 @@ import {type InAppAgentWindowExecutionUi,} from "./InAppAgentWindow";import { useInAppAiAgent } from "./InAppAiAgentProvider";+import { InAppAgentInternalSessionMenu } from "./InAppAgentInternalSessionMenu";+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";import { useSmoothStreamingMessages } from "./useSmoothStreamingMessages";import { getDrawerMessages } from "./utils/utils";import { getInAppAgentScreenContextDescription } from "@/src/features/in-app-agent/context";@@ -48,6 +50,7 @@ export function ControlledInAppAgentWindow(props: ControlledInAppAgentWindowProps,) {const router = useRouter();+ const internalFeaturesEnabled = useInternalFeaturesEnabled();const {activityByConversationId,conversations,@@ -56,6 +59,7 @@ export function ControlledInAppAgentWindow(isLoadingMoreConversations,isRunning,isSelectedConversationHydrating,+ isSelectedConversationPersisted,execution,isSubmitting,invalidateConversations,@@ -164,6 +168,21 @@ export function ControlledInAppAgentWindow(],);+ const projectId =+ typeof router.query.projectId === "string"+ ? router.query.projectId+ : undefined;+ const titleActions =+ internalFeaturesEnabled &&+ projectId &&+ selectedConversationId &&+ isSelectedConversationPersisted ? (+ <InAppAgentInternalSessionMenu+ projectId={projectId}+ conversationId={selectedConversationId}+ />+ ) : null;+const closeButtonProps =props.showCloseButton === false? ({ showCloseButton: false } as const)@@ -190,6 +209,7 @@ export function ControlledInAppAgentWindow(isLoadingMoreConversations={isLoadingMoreConversations}selectedConversationId={selectedConversationId}selectedConversationTitle={selectedConversationTitle}+ titleActions={titleActions}onLoadMoreConversations={loadMoreConversations}onOpenConversationHistory={invalidateConversations}onDeleteConversation={props.onDeleteConversation}diff --git a/web/src/features/in-app-agent/components/InAppAgentInternalSessionMenu.tsx b/web/src/features/in-app-agent/components/InAppAgentInternalSessionMenu.tsxnew file mode 100644index 0000000000..d8fbd9c1d3--- /dev/null+++ b/web/src/features/in-app-agent/components/InAppAgentInternalSessionMenu.tsx@@ -0,0 +1,120 @@+"use client";++import { Copy, ExternalLink, MoreHorizontal } from "lucide-react";++import {+ DropdownMenu,+ type DropdownMenuItemDefinition,+} from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { Button } from "@/src/components/ui/button";+import { showSuccessToast } from "@/src/features/notifications";+import { api } from "@/src/utils/api";+import { copyTextToClipboard } from "@/src/utils/clipboard";++function getOpenSessionItem({+ conversationId,+ isError,+ isPending,+ telemetryProjectId,+}: {+ conversationId: string;+ isError: boolean;+ isPending: boolean;+ telemetryProjectId: string | null;+}): DropdownMenuItemDefinition {+ const item = {+ type: "item",+ id: "open-session",+ title: "Open session in Langfuse",+ icon: ExternalLink,+ } as const;+ // A disabled button, not a placeholder link, so middle-click cannot open a tab.+ const unavailable = (reason: string): DropdownMenuItemDefinition => ({+ ...item,+ disabled: { reason },+ onClick: () => undefined,+ });++ if (isPending) {+ return unavailable("Loading the telemetry project.");+ }+ if (isError) {+ return unavailable("Could not load the telemetry project.");+ }+ if (!telemetryProjectId) {+ return unavailable(+ "Assistant telemetry is not recorded for this organization or instance.",+ );+ }+ return {+ ...item,+ href: `/project/${encodeURIComponent(telemetryProjectId)}/sessions/${encodeURIComponent(conversationId)}`,+ linkTarget: "_blank",+ };+}++/**+ * Debug shortcuts for the Langfuse team: assistant turns are traced into the+ * instance's AI-features project with the conversation id as session id.+ */+export function InAppAgentInternalSessionMenu({+ projectId,+ conversationId,+}: {+ projectId: string;+ conversationId: string;+}) {+ const telemetryProject = api.inAppAgent.telemetryProject.useQuery(+ { projectId },+ { meta: { silentAllErrors: true } },+ );++ const items: DropdownMenuItemDefinition[] = [+ {+ type: "item",+ id: "copy-session-id",+ title: "Copy session ID",+ icon: Copy,+ onClick: () => {+ copyTextToClipboard(conversationId)+ .then(() => {+ showSuccessToast({+ operation: "in_app_agent_session_id.copy",+ title: "Session ID copied",+ description: conversationId,+ duration: 2000,+ });+ })+ .catch(() => undefined);+ },+ },+ getOpenSessionItem({+ conversationId,+ isError: telemetryProject.isError,+ isPending: telemetryProject.isPending,+ telemetryProjectId: telemetryProject.data?.projectId ?? null,+ }),+ ];++ return (+ <DropdownMenu+ ariaLabel="Internal session actions"+ internal+ items={items}+ placement="bottom-start"+ >+ {({ getTriggerProps }) => (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-6 shrink-0"+ aria-label="Internal session actions"+ {...getTriggerProps()}+ >+ <MoreHorizontal className="icon-base text-icon-foreground" />+ </Button>+ )}+ </DropdownMenu>+ );+}diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsxindex d3305f5597..3d818ab117 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx@@ -9,6 +9,7 @@ import {import { ScanSearch } from "lucide-react";import { InAppAgentRunStatus } from "@langfuse/shared/in-app-agent";import { TooltipProvider } from "@/src/components/ui/tooltip";+import { LayerProvider } from "@/src/context/LayerContext/LayerContext";import {InAppAgentWindow,type InAppAgentWindowProps,@@ -27,6 +28,7 @@ const controlledAgent = vi.hoisted(() => ({isLoadingMoreConversations: false,isRunning: true,isSelectedConversationHydrating: false,+ isSelectedConversationPersisted: false,isSubmitting: false,execution: {run: null as {@@ -45,20 +47,49 @@ const controlledAgent = vi.hoisted(() => ({pendingToolApprovals: [] as Array<{ id: string }>,approveToolCall: vi.fn(),rejectToolCall: vi.fn(),- selectedConversationId: undefined,+ selectedConversationId: undefined as string | undefined,selectedConversationTitle: null,selectConversation: vi.fn(),submit: vi.fn(),submitFeedback: vi.fn(),},}));+const sessionUser = vi.hoisted(() => ({ admin: false }));+const telemetryProjectQuery = vi.hoisted(() => ({+ value: {+ data: { projectId: "ai-features-project" } as+ | { projectId: string | null }+ | undefined,+ isPending: false,+ isError: false,+ },+}));++vi.mock("next-auth/react", () => ({+ useSession: () => ({+ data: {+ user: { ...sessionUser, featureFlags: {}, organizations: [] },+ environment: { enableExperimentalFeatures: false },+ },+ }),+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ inAppAgent: {+ telemetryProject: {+ useQuery: () => telemetryProjectQuery.value,+ },+ },+ },+}));vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({usePostHogClientCapture: () => capture,}));vi.mock("next/router", () => ({- useRouter: () => ({ asPath: "/" }),+ useRouter: () => ({ asPath: "/", query: { projectId: "project-1" } }),}));vi.mock("./InAppAiAgentProvider", () => ({@@ -399,6 +430,113 @@ describe("ControlledInAppAgentWindow stop", () => {});});+describe("ControlledInAppAgentWindow internal session menu", () => {+ beforeAll(() => {+ // jsdom has no ResizeObserver; the menu's scroll gradients observe it.+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ });++ afterAll(() => {+ vi.unstubAllGlobals();+ });++ afterEach(() => {+ sessionUser.admin = false;+ controlledAgent.value.selectedConversationId = undefined;+ controlledAgent.value.isSelectedConversationPersisted = false;+ telemetryProjectQuery.value = {+ data: { projectId: "ai-features-project" },+ isPending: false,+ isError: false,+ };+ });++ function renderControlledWindow() {+ return render(+ <LayerProvider>+ <TooltipProvider>+ <ControlledInAppAgentWindow+ isExpanded={false}+ onClose={vi.fn()}+ onDeleteConversation={vi.fn()}+ onExpandedChange={vi.fn()}+ />+ </TooltipProvider>+ </LayerProvider>,+ );+ }++ it("offers session actions in the internal view once the conversation is persisted", async () => {+ controlledAgent.value.selectedConversationId = "aconv_1";+ controlledAgent.value.isSelectedConversationPersisted = true;+ const external = renderControlledWindow();++ expect(+ screen.queryByRole("button", { name: "Internal session actions" }),+ ).not.toBeInTheDocument();+ external.unmount();++ sessionUser.admin = true;+ controlledAgent.value.isSelectedConversationPersisted = false;+ const unpersisted = renderControlledWindow();++ expect(+ screen.queryByRole("button", { name: "Internal session actions" }),+ ).not.toBeInTheDocument();+ unpersisted.unmount();++ controlledAgent.value.isSelectedConversationPersisted = true;+ renderControlledWindow();+ fireEvent.click(+ screen.getByRole("button", { name: "Internal session actions" }),+ );++ const menu = await screen.findByRole("menu", {+ name: "Internal session actions",+ });+ expect(within(menu).getByText("Internal")).toBeInTheDocument();+ expect(within(menu).getByText("Copy session ID")).toBeInTheDocument();+ const openSession = within(menu).getByRole("link", {+ name: "Open session in Langfuse",+ });+ expect(openSession).toHaveAttribute(+ "href",+ "/project/ai-features-project/sessions/aconv_1",+ );+ expect(openSession).toHaveAttribute("target", "_blank");+ });++ it("keeps the open-session action inert when the telemetry lookup fails", async () => {+ sessionUser.admin = true;+ controlledAgent.value.selectedConversationId = "aconv_1";+ controlledAgent.value.isSelectedConversationPersisted = true;+ telemetryProjectQuery.value = {+ data: undefined,+ isPending: false,+ isError: true,+ };+ renderControlledWindow();+ fireEvent.click(+ screen.getByRole("button", { name: "Internal session actions" }),+ );++ const menu = await screen.findByRole("menu", {+ name: "Internal session actions",+ });+ expect(within(menu).queryByRole("link")).not.toBeInTheDocument();+ expect(+ within(menu).getByRole("menuitem", { name: "Open session in Langfuse" }),+ ).toHaveAttribute("title", "Could not load the telemetry project.");+ });+});+describe("InAppAgentWindow activity", () => {it("shows a waiting drawer, then Working once the first activity arrives", () => {const userMessage = {diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsxindex 344a9865f8..54a555ff62 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx@@ -907,6 +907,8 @@ export type InAppAgentWindowProps = {/** Titles the window. Null until the server has named the conversation,* which is when the product name shows instead. */selectedConversationTitle: string | null;+ /** Rendered right after the title. */+ titleActions?: ReactNode;} & InAppAgentWindowCloseButtonProps;function InAppAgentRateLimitError({@@ -999,6 +1001,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {screenContextDescription,selectedConversationId,selectedConversationTitle,+ titleActions,} = props;const screenContextNotice = formatScreenContextNotice(screenContextDescription,@@ -1181,6 +1184,14 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {Assistant</p>)}+ {titleActions ? (+ <div+ className="flex shrink-0 items-center"+ data-movable-resizable-panel-ignore-drag="true"+ >+ {titleActions}+ </div>+ ) : null}</div><divclassName="flex shrink-0 items-center gap-0.5"diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 3984caed88..b15cd0c02b 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -126,6 +126,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {isSubmitting: false,pendingToolApprovals: [],isSelectedConversationHydrating: false,+ isSelectedConversationPersisted: false,execution: { run: null, isCancelling: false, cancel: () => undefined },error: null,messages: [],@@ -184,6 +185,8 @@ type InAppAiAgentContextType = {isSubmitting: boolean;pendingToolApprovals: InAppAgentPendingToolApproval[];isSelectedConversationHydrating: boolean;+ /** False until the server acknowledges the selected conversation's first run. */+ isSelectedConversationPersisted: boolean;execution: InAppAiAgentExecution;error: InAppAgentError | null;messages: InAppAiAgentMessage[];@@ -1468,6 +1471,9 @@ function InAppAiAgentProviderInner({? []: effectivePendingToolApprovals,isSelectedConversationHydrating,+ isSelectedConversationPersisted:+ Boolean(selectedConversationId) &&+ !unpersistedConversationIds.has(selectedConversationId ?? ""),execution,error: effectiveError,messages: messagesWithUiState,@@ -1519,6 +1525,7 @@ function InAppAiAgentProviderInner({selectedConversationId,submit,submitFeedback,+ unpersistedConversationIds,],);diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.tsindex 77e477c6fe..883bfe4151 100644--- a/web/src/features/in-app-agent/server/router.ts+++ b/web/src/features/in-app-agent/server/router.ts@@ -1,6 +1,7 @@import { z } from "zod";import {+ ForbiddenError,InvalidRequestError,resolveInAppAgentRootRunId,ScoreDataTypeEnum,@@ -38,6 +39,7 @@ import {getInAppAgentApiAccessScope,} from "@/src/features/in-app-agent/server/rateLimit";import { assertInAppAgentRunCapacity } from "@/src/features/in-app-agent/server/runCapacity";+import { hasInternalAccess } from "@/src/features/feature-flags/server";import {cancelBackgroundRun,decideBackgroundApproval,@@ -449,4 +451,37 @@ export const inAppAgentRouter = createTRPCRouter({return { feedback: { value: input.value, comment } };}),++ /**+ * The project this instance traces assistant turns into, where each+ * conversation is a session. Internal surface only: null when the+ * organization opted out of AI telemetry or tracing is not configured.+ */+ telemetryProject: protectedProjectProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => {+ if (+ !hasInternalAccess({+ isAdmin: ctx.session.user.admin === true,+ isExperimentalFeaturesEnabled:+ env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",+ })+ ) {+ throw new ForbiddenError(+ "The assistant telemetry project is an internal surface.",+ );+ }++ const projectAvailability = await assertInAppAgentAvailable({+ prisma: ctx.prisma,+ projectId: input.projectId,+ user: ctx.session.user,+ });++ return {+ projectId: projectAvailability.aiTelemetryEnabled+ ? (env.LANGFUSE_AI_FEATURES_PROJECT_ID ?? null)+ : null,+ };+ }),});diff --git a/web/src/features/notifications/toastOperations.ts b/web/src/features/notifications/toastOperations.tsindex 47ff21464d..c3cdff16b1 100644--- a/web/src/features/notifications/toastOperations.ts+++ b/web/src/features/notifications/toastOperations.ts@@ -84,6 +84,7 @@ export const applicationToastOperations = ["in_app_agent_conversations.load","in_app_agent_feedback.save","in_app_agent_run.stop",+ "in_app_agent_session_id.copy","json_schema.prettify","media.resolveExternalMedia","model.create",diff --git a/web/src/features/organizations/components/AIFeatureSwitch.tsx b/web/src/features/organizations/components/AIFeatureSwitch.tsxindex 70a2d589a3..9ca9b9aa49 100644--- a/web/src/features/organizations/components/AIFeatureSwitch.tsx+++ b/web/src/features/organizations/components/AIFeatureSwitch.tsx@@ -60,6 +60,7 @@ export default function AIFeatureSwitch() {await updateSession();// Admins resolve org context from this query, not the sessionutils.organizations.byId.invalidate();+ utils.inAppAgent.telemetryProject.invalidate();},onError: () => {setIsAITelemetrySwitchEnabled(aiTelemetryEnabled ?? true);