🪢 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(assistant): Make assistant quick actions context-aware and extend coverage (#15146)
Lysander Kiesel3f6d480564ec
diff --git a/web/src/__tests__/server/unit/in-app-agent-quick-action-context.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-quick-action-context.servertest.tsnew file mode 100644index 0000000000..b0b5091e39--- /dev/null+++ b/web/src/__tests__/server/unit/in-app-agent-quick-action-context.servertest.ts@@ -0,0 +1,54 @@+import {+ getInAppAgentQuickActionTraceMetadata,+ sanitizeInAppAgentContext,+} from "@/src/ee/features/in-app-agent/context";++describe("in-app agent quick-action attribution", () => {+ it("exposes trace metadata for well-formed attribution and keeps it out of the model-visible context", () => {+ const context = [+ {+ description: "quick_action_key",+ value: "analyze-failure-patterns",+ },+ {+ description: "quick_action_category",+ value: "observability",+ },+ ];++ expect(getInAppAgentQuickActionTraceMetadata(context)).toEqual({+ quick_action_key: "analyze-failure-patterns",+ quick_action_category: "observability",+ });+ expect(sanitizeInAppAgentContext(context, "project-1")).toEqual([]);+ });++ it("rejects malformed attribution", () => {+ const invalidPairs = [+ ["INVALID!", "observability"],+ ["a".repeat(81), "observability"],+ ["analyze-failure-patterns", "unknown-context"],+ ] as const;++ for (const [quickActionKey, quickActionCategory] of invalidPairs) {+ expect(+ getInAppAgentQuickActionTraceMetadata([+ { description: "quick_action_key", value: quickActionKey },+ {+ description: "quick_action_category",+ value: quickActionCategory,+ },+ ]),+ ).toEqual({});+ }++ expect(+ getInAppAgentQuickActionTraceMetadata([+ {+ description: "quick_action_key",+ value: "analyze-failure-patterns",+ },+ ]),+ ).toEqual({});+ });+});diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsxindex 85eeb76ea3..e72a9d1a75 100644--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx@@ -7,6 +7,10 @@ import type { InAppAgentWindowConversation } from "./InAppAgentWindow";import { useInAppAiAgent } from "./InAppAiAgentProvider";import { getDrawerMessages } from "./utils/utils";import { getInAppAgentScreenContextDescription } from "@/src/ee/features/in-app-agent/context";+import {+ getInAppAgentFocusedQuickActions,+ getInAppAgentQuickActionContext,+} from "@/src/ee/features/in-app-agent/quickActions";const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE ="Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";@@ -70,6 +74,13 @@ export function ControlledInAppAgentWindow(() => getInAppAgentScreenContextDescription(router.asPath),[router.asPath],);+ const quickActionContext = getInAppAgentQuickActionContext(router.asPath);+ const focusedQuickActions = getInAppAgentFocusedQuickActions(+ screenContextDescription.type,+ );+ // Strip query and hash so peek views and filter changes on the same page do+ // not reset the quick-action picker.+ const quickActionResetKey = router.asPath.replace(/[?#].*$/, "");const drawerMessages = useMemo(() =>@@ -96,6 +107,9 @@ export function ControlledInAppAgentWindow(isInputDisabled={isInputDisabled}disablePendingToolApprovalActions={selectedConversationIsWriteLocked}messages={drawerMessages}+ quickActionContext={quickActionContext}+ focusedQuickActions={focusedQuickActions}+ quickActionResetKey={quickActionResetKey}screenContextDescription={screenContextDescription}conversations={conversations}hasMoreConversations={hasMoreConversations}diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.clienttest.tsxnew file mode 100644index 0000000000..3ae9815476--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx@@ -0,0 +1,145 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { ScanSearch } from "lucide-react";+import { TooltipProvider } from "@/src/components/ui/tooltip";+import {+ InAppAgentWindow,+ type InAppAgentWindowProps,+} from "./InAppAgentWindow";++const capture = vi.fn();++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => capture,+}));++// jsdom does not implement Element scrolling.+Element.prototype.scrollTo = vi.fn();++function windowElement(+ overrides: Partial<+ Omit<InAppAgentWindowProps, "showCloseButton" | "onClose">+ > = {},+) {+ const props: InAppAgentWindowProps = {+ conversations: [],+ error: null,+ hasMoreConversations: false,+ isAssistantTurnInProgress: false,+ isExpanded: false,+ isInputDisabled: false,+ isLoadingMoreConversations: false,+ messages: [],+ onApproveToolCall: vi.fn(),+ onDeleteConversation: vi.fn(),+ onExpandedChange: vi.fn(),+ onLoadMoreConversations: vi.fn(),+ onNewConversation: vi.fn(),+ onOpenConversationHistory: vi.fn(),+ onRejectToolCall: vi.fn(),+ onSelectConversation: vi.fn(),+ onSubmit: vi.fn().mockResolvedValue(true),+ onSubmitFeedback: vi.fn(),+ quickActionContext: "observability",+ quickActionResetKey: "/project/project-1/traces",+ screenContextDescription: { type: "trace-list", hasAppliedFilters: true },+ selectedConversationId: undefined,+ ...overrides,+ showCloseButton: false,+ };++ return (+ <TooltipProvider>+ <InAppAgentWindow {...props} />+ </TooltipProvider>+ );+}++function selectTab(name: string) {+ fireEvent.mouseDown(screen.getByRole("tab", { name }), {+ button: 0,+ ctrlKey: false,+ });+}++describe("InAppAgentWindow quick actions", () => {+ it("switches tabs, resets on route change, and submits the action prompt with attribution", async () => {+ const onSubmit = vi.fn().mockResolvedValue(true);+ const { rerender } = render(windowElement({ onSubmit }));++ expect(screen.getAllByRole("tab").map((tab) => tab.textContent)).toEqual([+ "Observability",+ "Prompts",+ "Evaluation",+ "Dashboard",+ ]);+ expect(screen.getByRole("tab", { name: "Observability" })).toHaveAttribute(+ "aria-selected",+ "true",+ );++ selectTab("Prompts");+ expect(screen.getByRole("tab", { name: "Prompts" })).toHaveAttribute(+ "aria-selected",+ "true",+ );++ rerender(+ windowElement({+ onSubmit,+ quickActionResetKey: "/project/project-1/observations",+ }),+ );+ expect(screen.getByRole("tab", { name: "Observability" })).toHaveAttribute(+ "aria-selected",+ "true",+ );++ selectTab("Prompts");+ fireEvent.click(screen.getByRole("button", { name: /^Create a prompt/ }));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ "Help me create a new prompt in Langfuse prompt management, including choosing between a text and chat prompt, defining its variables, and setting a label.",+ {+ quickAction: {+ key: "create-prompt",+ category: "prompts",+ },+ },+ );+ });+ expect(capture).toHaveBeenCalledWith("in_app_agent:quick_action_started", {+ quickActionKey: "create-prompt",+ quickActionCategory: "prompts",+ position: 0,+ });+ expect(capture).toHaveBeenCalledTimes(1);+ });++ it("shows focused actions on the initial tab and coarse actions elsewhere", () => {+ render(+ windowElement({+ focusedQuickActions: [+ {+ id: "analyze-this-trace",+ label: "Analyze this trace",+ description: "Run structured error analysis on this trace",+ icon: ScanSearch,+ prompt: "Analyze this trace.",+ },+ ],+ quickActionResetKey: "/project/project-1/traces/trace-1",+ screenContextDescription: { type: "trace" },+ }),+ );++ expect(+ screen.getByRole("button", { name: /^Analyze this trace/ }),+ ).toBeInTheDocument();++ selectTab("Prompts");+ expect(+ screen.getByRole("button", { name: /^Create a prompt/ }),+ ).toBeInTheDocument();+ });+});diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsxindex ef58fc5abc..d41f537978 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx@@ -6,6 +6,7 @@ import {type InAppAgentWindowMessage,type InAppAgentWindowProps,} from "./InAppAgentWindow";+import { getInAppAgentQuickActionContext } from "@/src/ee/features/in-app-agent/quickActions";import {InAppAgentWindowShell,useInAppAgentWindowShellPanelControl,@@ -605,6 +606,8 @@ const meta = preview.meta({onExpandedChange: fn(),onSubmit: fn(),onSubmitFeedback: fn(),+ quickActionContext: getInAppAgentQuickActionContext("/"),+ quickActionResetKey: "/",screenContextDescription: { type: "page" as const },showCloseButton: true,},@@ -1124,7 +1127,7 @@ export const RateLimited = meta.story({timeout: 2_000,});await expect(- canvas.getByRole("textbox", { name: "Ask the assistant a question" }),+ canvas.getByRole("textbox", { name: "Message the assistant" }),).toBeDisabled();await expect(canvas.getByRole("button", { name: "Confirm" }),@@ -1139,9 +1142,12 @@ export const RateLimited = meta.story({},});-export const RefocusAfterSubmit = {+export const RefocusAfterSubmit = meta.story({name: "(Test) Refocus After Submit",- render: function Render(args: InAppAgentWindowProps) {+ args: {+ messages: [],+ },+ render: function Render(args) {const [isExpanded, setIsExpanded] = useState(args.isExpanded);const [isInputDisabled, setIsInputDisabled] = useState(false);const [messages, setMessages] = useState<InAppAgentWindowMessage[]>([@@ -1195,7 +1201,7 @@ export const RefocusAfterSubmit = {},play: async ({ canvasElement }: { canvasElement: HTMLElement }) => {const canvas = within(canvasElement);- const textarea = canvas.getByLabelText("Ask the assistant a question");+ const textarea = canvas.getByLabelText("Message the assistant");await userEvent.type(textarea, "Check the latest latency regression");await userEvent.click(canvas.getByRole("button", { name: "Send message" }));@@ -1210,4 +1216,4 @@ export const RefocusAfterSubmit = {expect(textarea).toHaveFocus();});},-};+});diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsxindex d5e05f5e33..ac4ec289f3 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx@@ -8,6 +8,7 @@ import {useState,} from "react";import {+ ArrowRight,BotMessageSquare,History,Info,@@ -48,25 +49,21 @@ import {} from "@/src/ee/features/in-app-agent/components/utils/utils";import styles from "./InAppAgentWindow.module.css";import { assertUnreachable } from "@/src/utils/types";+import {+ IN_APP_AGENT_QUICK_ACTION_CONTEXTS,+ IN_APP_AGENT_QUICK_ACTION_CONTEXT_ICONS,+ IN_APP_AGENT_QUICK_ACTION_CONTEXT_LABELS,+ getInAppAgentQuickActions,+ isInAppAgentQuickActionContext,+ type InAppAgentQuickAction,+ type InAppAgentQuickActionContext,+ type InAppAgentSubmitOptions,+} from "@/src/ee/features/in-app-agent/quickActions";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";const AUTO_SCROLL_THRESHOLD_PX = 50;const SCROLL_DIRECTION_TOLERANCE_PX = 1;-const CONVERSATION_STARTERS = [- [- "Get started with Langfuse",- "Where should I start with setting up Langfuse?",- ],- ["Optimize my setup", "What should I improve in my Langfuse setup?"],- [- "Find problematic traces",- "Show me patterns in failed or low-scoring traces.",- ],- [- "Investigate unusual patterns",- "Are there unusual latency or cost patterns recently?",- ],-] as const;-function scrollViewportToBottom(viewport: HTMLDivElement | null) {if (!viewport) {return;@@ -78,6 +75,103 @@ function scrollViewportToBottom(viewport: HTMLDivElement | null) {});}+function InAppAgentQuickActionPicker({+ focusedActions,+ initialContext,+ isDisabled,+ onSelectAction,+}: {+ focusedActions?: readonly InAppAgentQuickAction[];+ initialContext: InAppAgentQuickActionContext;+ isDisabled: boolean;+ onSelectAction: (+ action: InAppAgentQuickAction,+ context: InAppAgentQuickActionContext,+ position: number,+ ) => void;+}) {+ const [selectedContext, setSelectedContext] = useState(initialContext);+ const selectedActions =+ selectedContext === initialContext && focusedActions?.length+ ? focusedActions+ : getInAppAgentQuickActions(selectedContext);+ const contextFallbackIcon =+ IN_APP_AGENT_QUICK_ACTION_CONTEXT_ICONS[selectedContext];++ return (+ <>+ <p className="text-foreground mt-4 text-base font-medium">+ Welcome to the Langfuse Assistant+ </p>+ <p className="text-muted-foreground mt-2 max-w-xs text-center text-sm leading-relaxed">+ What do you want to do?+ </p>+ <Tabs+ value={selectedContext}+ className="mt-5 w-full max-w-md"+ onValueChange={(value) => {+ if (isInAppAgentQuickActionContext(value)) {+ setSelectedContext(value);+ }+ }}+ >+ <TabsList+ aria-label="Quick action category"+ className="h-auto w-full justify-between rounded-none border-b bg-transparent p-0"+ >+ {IN_APP_AGENT_QUICK_ACTION_CONTEXTS.map((context) => (+ <TabsTrigger+ key={context}+ value={context}+ disabled={isDisabled}+ className="text-muted-foreground data-[state=active]:border-primary-accent data-[state=active]:text-foreground h-8 shrink-0 rounded-none border-b-2 border-transparent bg-transparent px-0 text-sm tracking-[-0.04em] shadow-none data-[state=active]:bg-transparent data-[state=active]:shadow-none"+ >+ {IN_APP_AGENT_QUICK_ACTION_CONTEXT_LABELS[context]}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ <div className="mt-4 flex w-full max-w-sm flex-col gap-2.5">+ {selectedActions.map((action, position) => {+ const ActionIcon = action.icon ?? contextFallbackIcon;++ return (+ <Button+ key={action.id}+ type="button"+ variant="outline"+ className="bg-card hover:bg-muted/60 group h-auto min-h-16 w-full justify-start gap-2.5 rounded-lg px-3 py-2 text-left whitespace-normal shadow-xs"+ disabled={isDisabled}+ onClick={() => {+ onSelectAction(action, selectedContext, position);+ }}+ >+ <span className="bg-muted text-primary-accent flex size-8 shrink-0 items-center justify-center rounded-md">+ <ActionIcon aria-hidden="true" className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="text-foreground block text-sm leading-snug font-semibold">+ {action.label}+ </span>+ <span+ className="text-muted-foreground mt-0.5 block truncate text-sm leading-snug font-normal"+ title={action.description}+ >+ {action.description}+ </span>+ </span>+ <ArrowRight+ aria-hidden="true"+ className="text-muted-foreground size-4 shrink-0 transition-transform group-hover:translate-x-0.5"+ />+ </Button>+ );+ })}+ </div>+ </>+ );+}+function formatScreenContextNotice(description: InAppAgentScreenContextDescription,) {@@ -178,7 +272,10 @@ export type InAppAgentWindowProps = {onRejectToolCall: (approvalId: string) => Promise<void>;onOpenConversationHistory: () => void;onSelectConversation: (conversationId: string) => void;- onSubmit: (input: string) => boolean | Promise<boolean>;+ onSubmit: (+ input: string,+ options?: InAppAgentSubmitOptions,+ ) => boolean | Promise<boolean>;onSubmitFeedback: (params: {messageId: string;runId: string;@@ -186,6 +283,9 @@ export type InAppAgentWindowProps = {comment?: string | null;}) => Promise<void>;screenContextDescription: InAppAgentScreenContextDescription;+ quickActionContext: InAppAgentQuickActionContext;+ focusedQuickActions?: readonly InAppAgentQuickAction[];+ quickActionResetKey: string;selectedConversationId: string | undefined;} & InAppAgentWindowCloseButtonProps;@@ -275,12 +375,16 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {onSelectConversation,onSubmit,onSubmitFeedback,+ focusedQuickActions,+ quickActionContext,+ quickActionResetKey,screenContextDescription,selectedConversationId,} = props;const screenContextNotice = formatScreenContextNotice(screenContextDescription,);+ const capture = usePostHogClientCapture();const isRateLimited = isInAppAgentRateLimited(error);const isInputDisabled = baseIsInputDisabled || isRateLimited;const viewportRef = useRef<HTMLDivElement>(null);@@ -321,14 +425,14 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {}).filter((message): message is InAppAgentWindowMessage => message !== null);- const submitInput = (content: string) => {+ const submitInput = (content: string, options?: InAppAgentSubmitOptions) => {const trimmedContent = content.trim();if (!trimmedContent || isInputDisabled) {return;}- Promise.resolve(onSubmit(trimmedContent))+ Promise.resolve(onSubmit(trimmedContent, options)).then((submitted) => {if (submitted) {isAutoScrollAttachedRef.current = true;@@ -606,35 +710,25 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {<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 data.- <br />- What do you want to do?- </p>- <div className="mt-6 flex max-w-sm flex-wrap items-center justify-center gap-2">- {CONVERSATION_STARTERS.map(([label, message]) => (- <button- key={label}- type="button"- className={cn(- "bg-card text-foreground border-border hover:bg-muted/60 border text-[0.775rem] leading-none shadow-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60",- isExpanded- ? "rounded-2xl px-3 py-2"- : "rounded-xl px-2 py-1.5",- )}- disabled={isInputDisabled}- onClick={() => {- submitInput(message);- }}- >- {label}- </button>- ))}- </div>+ <InAppAgentQuickActionPicker+ key={`${selectedConversationId ?? "new"}:${quickActionResetKey}`}+ focusedActions={focusedQuickActions}+ initialContext={quickActionContext}+ isDisabled={isInputDisabled}+ onSelectAction={(action, context, position) => {+ capture("in_app_agent:quick_action_started", {+ quickActionKey: action.id,+ quickActionCategory: context,+ position,+ });+ submitInput(action.prompt, {+ quickAction: {+ key: action.id,+ category: context,+ },+ });+ }}+ /></div>) : null}@@ -838,8 +932,8 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {}}}disabled={isInputDisabled}- aria-label="Ask the assistant a question"- placeholder="Ask the assistant a question..."+ aria-label="Message the assistant"+ placeholder="Let me know what I can do for you..."rows={1}className={cn("bg-background placeholder:text-foreground-tertiary w-full flex-1 resize-none overflow-y-auto rounded-md text-sm leading-5 disabled:cursor-not-allowed disabled:opacity-60",diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 9164738a07..bb4a2de467 100644--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -36,9 +36,14 @@ import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { api } from "@/src/utils/api";import {+ createInAppAgentQuickActionAttributionContext,createInAppAgentScreenContext,createInAppAgentUserContext,} from "@/src/ee/features/in-app-agent/context";+import type {+ InAppAgentQuickActionAttribution,+ InAppAgentSubmitOptions,+} from "@/src/ee/features/in-app-agent/quickActions";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import {getInAppAgentError,@@ -138,7 +143,10 @@ type InAppAiAgentContextType = {invalidateConversations: () => void;selectConversation: (conversationId: string | null) => void;deleteConversation: (conversationId: string) => Promise<void>;- submit: (content: string) => Promise<boolean>;+ submit: (+ content: string,+ options?: InAppAgentSubmitOptions,+ ) => Promise<boolean>;approveToolCall: (approvalId: string) => Promise<void>;rejectToolCall: (approvalId: string) => Promise<void>;submitFeedback: (params: {@@ -625,6 +633,7 @@ function InAppAiAgentProviderInner({agent: HttpAgent,conversationId: string,runParameters?: Parameters<HttpAgent["runAgent"]>[0],+ quickActionAttribution?: InAppAgentQuickActionAttribution,) => {clearLoadingEvents();setIsRunning(true);@@ -634,7 +643,7 @@ function InAppAiAgentProviderInner({context: createInAppAgentScreenContext({currentUrl: window.location.href,}).concat(- ...createInAppAgentUserContext({+ createInAppAgentUserContext({userName: session.data?.user?.name,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,languages:@@ -642,6 +651,11 @@ function InAppAiAgentProviderInner({? Array.from(navigator.languages): [navigator.language],}),+ quickActionAttribution+ ? createInAppAgentQuickActionAttributionContext(+ quickActionAttribution,+ )+ : [],),}).then(() => true)@@ -760,7 +774,7 @@ function InAppAiAgentProviderInner({);const submit = useCallback(- async (content: string) => {+ async (content: string, options?: InAppAgentSubmitOptions) => {if (!content ||isRunning ||@@ -827,7 +841,7 @@ function InAppAiAgentProviderInner({}capture("in_app_agent:new_chat_turn");startedRun = true;- runAgent(agent, conversationId);+ runAgent(agent, conversationId, undefined, options?.quickAction);return true;} catch (error) {setError(getInAppAgentError(error));diff --git a/web/src/ee/features/in-app-agent/context.ts b/web/src/ee/features/in-app-agent/context.tsindex 8c87caa7f9..f980045827 100644--- a/web/src/ee/features/in-app-agent/context.ts+++ b/web/src/ee/features/in-app-agent/context.ts@@ -1,4 +1,9 @@import type { AgUiRunAgentInput } from "@/src/ee/features/in-app-agent/schema";+import {+ isInAppAgentQuickActionContext,+ type InAppAgentQuickActionAttribution,+} from "@/src/ee/features/in-app-agent/quickActions";+import { getInAppAgentProjectRoute } from "@/src/ee/features/in-app-agent/routeContext";type InAppAgentContext = AgUiRunAgentInput["context"];@@ -24,48 +29,35 @@ export type InAppAgentScreenContextDescription =| { type: "datasets-list"; hasAppliedFilters: boolean };const CURRENT_URL_CONTEXT_DESCRIPTION = "current_url";+const QUICK_ACTION_KEY_CONTEXT_DESCRIPTION = "quick_action_key";+const QUICK_ACTION_CATEGORY_CONTEXT_DESCRIPTION = "quick_action_category";const MAX_SCREEN_CONTEXT_SEARCH_PARAMS = 30;const MAX_CONTEXT_KEY_LENGTH = 80;const MAX_CONTEXT_VALUE_LENGTH = 500;const MAX_SCREEN_CONTEXT_PATH_LENGTH = 500;const MAX_SCREEN_CONTEXT_HASH_LENGTH = 200;const MAX_SCREEN_CONTEXT_JSON_LENGTH = 4_000;+const MAX_QUICK_ACTION_KEY_LENGTH = 80;+const QUICK_ACTION_KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;const USER_CONTEXT_DESCRIPTIONS = new Set(["user_name","current_timezone","browser_languages",]);+// Entity-granular classifier of a project URL, used for the screen-context+// banner and focused quick actions. getInAppAgentQuickActionContext() in+// quickActions.ts classifies the same URL coarsely by section for the picker.export function getInAppAgentScreenContextDescription(currentUrl: string,): InAppAgentScreenContextDescription {- let parsedUrl: URL;-- try {- parsedUrl = new URL(currentUrl, "https://langfuse.local");- } catch {- return { type: "page" };- }-- const rawPathSegments = parsedUrl.pathname.split("/").filter(Boolean);- const projectSegmentIndex = rawPathSegments.indexOf("project");+ const projectRoute = getInAppAgentProjectRoute(currentUrl);- if (- projectSegmentIndex === -1 ||- rawPathSegments.length <= projectSegmentIndex + 2- ) {+ if (!projectRoute) {return { type: "page" };}- let routeSegments: string[];-- try {- routeSegments = rawPathSegments- .slice(projectSegmentIndex + 2)- .map((segment) => decodeURIComponent(segment));- } catch {- return { type: "page" };- }+ const { parsedUrl, routeSegments } = projectRoute;const section = routeSegments[0];const detailId = routeSegments[1];@@ -205,6 +197,61 @@ export function sanitizeInAppAgentContext(return sanitizedContext;}+export function createInAppAgentQuickActionAttributionContext(+ attribution: InAppAgentQuickActionAttribution,+): InAppAgentContext {+ return [+ {+ description: QUICK_ACTION_KEY_CONTEXT_DESCRIPTION,+ value: attribution.key,+ },+ {+ description: QUICK_ACTION_CATEGORY_CONTEXT_DESCRIPTION,+ value: attribution.category,+ },+ ];+}++// Attribution is telemetry only: it is validated by shape here and read for+// trace metadata, but never forwarded into the model-visible sanitized context.+export function getInAppAgentQuickActionAttribution(+ context: InAppAgentContext,+): InAppAgentQuickActionAttribution | undefined {+ const quickActionKey = context+ .find((item) => item.description === QUICK_ACTION_KEY_CONTEXT_DESCRIPTION)+ ?.value.trim();+ const quickActionCategory = context+ .find(+ (item) => item.description === QUICK_ACTION_CATEGORY_CONTEXT_DESCRIPTION,+ )+ ?.value.trim();++ if (+ !quickActionKey ||+ quickActionKey.length > MAX_QUICK_ACTION_KEY_LENGTH ||+ !QUICK_ACTION_KEY_PATTERN.test(quickActionKey) ||+ !quickActionCategory ||+ !isInAppAgentQuickActionContext(quickActionCategory)+ ) {+ return undefined;+ }++ return { key: quickActionKey, category: quickActionCategory };+}++export function getInAppAgentQuickActionTraceMetadata(+ context: InAppAgentContext,+): Record<string, string> {+ const attribution = getInAppAgentQuickActionAttribution(context);++ return attribution+ ? {+ quick_action_key: attribution.key,+ quick_action_category: attribution.category,+ }+ : {};+}+function sanitizeUserContext(context: InAppAgentContext): InAppAgentContext {return context.flatMap((item) => {if (!USER_CONTEXT_DESCRIPTIONS.has(item.description)) {diff --git a/web/src/ee/features/in-app-agent/quickActions.clienttest.ts b/web/src/ee/features/in-app-agent/quickActions.clienttest.tsnew file mode 100644index 0000000000..bfc527f0ff--- /dev/null+++ b/web/src/ee/features/in-app-agent/quickActions.clienttest.ts@@ -0,0 +1,24 @@+import {+ getInAppAgentFocusedQuickActions,+ getInAppAgentQuickActionContext,+} from "./quickActions";++describe("contextual assistant quick actions", () => {+ it("classifies project sections and falls back to observability", () => {+ expect(getInAppAgentQuickActionContext("/project/p-1/datasets/d-1")).toBe(+ "evaluation",+ );+ expect(+ getInAppAgentQuickActionContext("/project/p-1/unsupported-feature"),+ ).toBe("observability");+ expect(getInAppAgentQuickActionContext("/organization/o-1/settings")).toBe(+ "observability",+ );+ });++ it("returns focused actions only for entity screen context types", () => {+ expect(getInAppAgentFocusedQuickActions("trace")).toBeDefined();+ expect(getInAppAgentFocusedQuickActions("trace-list")).toBeUndefined();+ expect(getInAppAgentFocusedQuickActions("page")).toBeUndefined();+ });+});diff --git a/web/src/ee/features/in-app-agent/quickActions.ts b/web/src/ee/features/in-app-agent/quickActions.tsnew file mode 100644index 0000000000..68103ba87c--- /dev/null+++ b/web/src/ee/features/in-app-agent/quickActions.ts@@ -0,0 +1,405 @@+import { getInAppAgentProjectRoute } from "@/src/ee/features/in-app-agent/routeContext";+import {+ Activity,+ BarChart3,+ Beaker,+ ClipboardCheck,+ Clock,+ Coins,+ Database,+ FileJson,+ FilePlus,+ FlaskConical,+ GitCompareArrows,+ LayoutDashboard,+ Lightbulb,+ ListChecks,+ ListTree,+ MessageSquareText,+ Radar,+ ScanSearch,+ ScrollText,+ Sparkles,+ SquarePercent,+ TrendingDown,+ WandSparkles,+ type LucideIcon,+} from "lucide-react";++export const IN_APP_AGENT_QUICK_ACTION_CONTEXTS = [+ "observability",+ "prompts",+ "evaluation",+ "dashboards",+] as const;++export type InAppAgentQuickActionContext =+ (typeof IN_APP_AGENT_QUICK_ACTION_CONTEXTS)[number];++export const IN_APP_AGENT_QUICK_ACTION_CONTEXT_LABELS: Record<+ InAppAgentQuickActionContext,+ string+> = {+ observability: "Observability",+ prompts: "Prompts",+ evaluation: "Evaluation",+ dashboards: "Dashboard",+};++export type InAppAgentQuickAction = {+ id: string;+ label: string;+ description: string;+ prompt: string;+ icon: LucideIcon;+};++export const IN_APP_AGENT_QUICK_ACTION_CONTEXT_ICONS: Record<+ InAppAgentQuickActionContext,+ LucideIcon+> = {+ observability: ListTree,+ dashboards: LayoutDashboard,+ prompts: FileJson,+ evaluation: Lightbulb,+};++export type InAppAgentQuickActionAttribution = {+ key: string;+ category: InAppAgentQuickActionContext;+};++export type InAppAgentSubmitOptions = {+ quickAction?: InAppAgentQuickActionAttribution;+};++// Version 1 starter sets. Idea is that periodic curation replaces sets when usage+// supports a stronger ranking. Prompts are somewhat product-generic and act on the+// current page context without copying customer data.+export const IN_APP_AGENT_QUICK_ACTIONS_BY_CONTEXT = {+ observability: [+ {+ id: "analyze-failure-patterns",+ label: "Analyze failure patterns",+ description: "Run structured error analysis on failed traces",+ icon: ScanSearch,+ prompt:+ "Run a structured error analysis on failed traces in the current view (taking active filters into account): sample representative traces (as many as needed), open-code and cluster recurring failure modes into a taxonomy, recommend what to fix first, and offer to set up an evaluator or annotation queue to track the top failure modes.",+ },+ {+ id: "review-recent-activity",+ label: "Review recent activity",+ description: "Get a digest of volume, cost, and latency",+ icon: Activity,+ prompt:+ "Give me a digest of recent activity in the current view (taking active filters into account): trace volume, error rates, latency, and cost over the last seven days (and compare it with the previous week), and highlight anything that changed significantly.",+ },+ {+ id: "investigate-unusual-patterns",+ label: "Investigate unusual patterns",+ description: "Spot unusual cost, latency, or quality patterns",+ icon: Radar,+ prompt:+ "Review the current filtered view for unusual latency, cost, or quality patterns, explain likely causes, and suggest what to investigate next.",+ },+ ],+ dashboards: [+ {+ id: "monitor-production-health",+ label: "Monitor production health",+ description: "Widget for error rate, latency, throughput",+ icon: Activity,+ prompt:+ "Help me build widgets that keep an eye on production health — error rate, P95/P99 latency, throughput. First ask whether to scope this to a specific model, feature, trace name or keep it project-wide, and fit the widgets to whatever is already on my current dashboard.",+ },+ {+ id: "track-cost-and-usage",+ label: "Track cost and usage",+ description: "Widget for spend by model and feature",+ icon: Coins,+ prompt:+ "Help me build widgets to track token usage and cost — how spend is trending, which users drive it (if available), and how models compare. First check whether to focus on a particular model, feature, or user segment or look across the whole project, and fit them to whatever is already on my current dashboard.",+ },+ {+ id: "track-quality-and-feedback",+ label: "Track quality and feedback",+ description: "Widget for score trends and feedback",+ icon: SquarePercent,+ prompt:+ "Help me build widgets to track quality — score trends over time, score distribution, and user feedback like thumbs up/down. First ask which score or use case matters most or whether I want an overall view, take my current dashboard into account.",+ },+ ],+ prompts: [+ {+ id: "create-prompt",+ label: "Create a prompt",+ description: "Add a new prompt to prompt management",+ icon: FilePlus,+ prompt:+ "Help me create a new prompt in Langfuse prompt management, including choosing between a text and chat prompt, defining its variables, and setting a label.",+ },+ {+ id: "find-prompts-to-improve",+ label: "Find prompts to improve",+ description: "Spot prompts with weak performance",+ icon: TrendingDown,+ prompt:+ "Across my prompts, identify which ones have declining scores, high latency, or high cost in production based on their linked generations, and suggest which to improve first. If no generations are linked to prompts, explain how to link prompts to traces instead.",+ },+ {+ id: "review-prompt-usage",+ label: "Review prompt usage",+ description: "See which prompts drive production traffic",+ icon: BarChart3,+ prompt:+ "Summarize which prompts are used most in production, which versions are live, and their latency, cost, and score performance. If no generations are linked to prompts, explain how to link prompts to traces instead.",+ },+ ],+ evaluation: [+ {+ id: "set-up-llm-judge-evaluator",+ label: "Set up LLM-as-a-judge evaluator",+ description: "Score outputs with a model judge",+ icon: WandSparkles,+ prompt:+ "Help me set up an LLM-as-a-judge evaluator. First ask what I want to score — a quality like hallucination, helpfulness, or toxicity, or something tied to a specific use case — then help me pick a managed template or write a custom rubric, map its variables, and choose whether it runs on live observations or an experiment and which data it targets. If it helps, look at a few recent traces first to ground your understanding.",+ },+ {+ id: "set-up-annotation-queue",+ label: "Set up an annotation queue",+ description: "Queue traces for human review and scoring",+ icon: ListChecks,+ prompt:+ "Help me set up an annotation queue so a human can review and score traces. First ask which traces or use case I want reviewed and which dimensions to score, then create the score configs and the queue, add a starter set of items.",+ },+ {+ id: "create-dataset-from-traces",+ label: "Create a dataset",+ description: "Build a dataset from representative traces",+ icon: Database,+ prompt:+ "Help me build a dataset (up to 10 items) from representative traces so I can evaluate and run experiments. First ask which use case or slice of traffic it should cover and what to name it, then pull a small set of up to ten traces as items with inputs and expected outputs. When it's ready, I can run an experiment on it from the UI, or you can give me a coding-agent prompt to run it via the SDK.",+ },+ ],+} satisfies Record<+ InAppAgentQuickActionContext,+ readonly InAppAgentQuickAction[]+>;++export const IN_APP_AGENT_FOCUSED_QUICK_ACTIONS = {+ trace: [+ {+ id: "analyze-this-trace",+ label: "Analyze this trace",+ description: "Run structured error analysis on this trace",+ icon: ScanSearch,+ prompt:+ "Run a structured error analysis on this trace: review its observations and generations, identify failure modes, explain what went wrong, and recommend what to fix first.",+ },+ {+ id: "summarize-this-trace",+ label: "Summarize this trace",+ description: "Get a plain-language recap of this execution",+ icon: ScrollText,+ prompt:+ "Summarize this trace, including its execution sequence, generations, tool calls, errors, scores, and outcome.",+ },+ {+ id: "break-down-this-trace-cost",+ label: "Break down this trace's cost",+ description: "See where latency and tokens add up",+ icon: Coins,+ prompt:+ "Break down this trace's latency, token usage, and cost across its generation observations, and identify the largest drivers.",+ },+ ],+ observation: [+ {+ id: "analyze-this-observation",+ label: "Analyze this observation",+ description: "Inspect this observation for issues",+ icon: ScanSearch,+ prompt:+ "Analyze this observation, including its input, output, errors, scores, and linked prompt version, and explain what went wrong or could be improved.",+ },+ {+ id: "explain-this-generation",+ label: "Explain this observation",+ description: "Understand what this observation did",+ icon: MessageSquareText,+ prompt:+ "Explain what this observation did, how it fits into the surrounding trace, and whether its output looks correct.",+ },+ {+ id: "optimize-this-generation-cost",+ label: "Optimize this observation's cost",+ description: "Reduce tokens and latency for this step",+ icon: Coins,+ prompt:+ "Review this observation's token usage, latency, and model choice, then suggest concrete ways to reduce cost or latency without hurting quality.",+ },+ ],+ session: [+ {+ id: "summarize-this-session",+ label: "Summarize this session",+ description: "Get a plain-language recap of this session",+ icon: Clock,+ prompt:+ "Summarize this session, including its traces, execution flow, errors, scores, and overall outcome.",+ },+ {+ id: "analyze-this-session",+ label: "Analyze this session",+ description: "Find issues across this session's traces",+ icon: ScanSearch,+ prompt:+ "Analyze this session's traces for recurring failure patterns, quality issues, and unusual latency or cost, then recommend what to investigate next.",+ },+ {+ id: "break-down-this-session-cost",+ label: "Break down this session's cost",+ description: "See where this session spends tokens",+ icon: Coins,+ prompt:+ "Break down this session's token usage and cost across its traces and generations, and highlight the largest drivers.",+ },+ ],+ prompt: [+ {+ id: "review-prompt-best-practices",+ label: "Review with best practices",+ description: "Check this prompt against Langfuse guidance",+ icon: Sparkles,+ prompt:+ "Review this prompt against prompt engineering best practices and suggest concrete improvements to its structure, instructions, and variables while preserving its intent.",+ },+ {+ id: "compare-prompt-versions",+ label: "Compare prompt versions",+ description: "Review how versions changed",+ icon: GitCompareArrows,+ prompt:+ "Compare recent versions of this prompt, summarize what changed between them, and how each version performs in production based on its linked generations. If no generations are linked to this prompt, explain how to link prompts to traces instead.",+ },+ {+ id: "check-prompt-performance",+ label: "Check prompt performance",+ description: "Connect this prompt to latency, cost, and scores",+ icon: SquarePercent,+ prompt:+ "Find the generations that use this prompt and summarize its latency, cost, and score performance, pointing me to this prompt's Metrics tab for the full per-version breakdown. If no generations are linked to this prompt, explain how to link prompts to traces instead.",+ },+ ],+ dataset: [+ {+ id: "add-items-to-this-dataset",+ label: "Add items from traces",+ description: "Populate this dataset from production traces",+ icon: Database,+ prompt:+ "Help me add a small set of up to ten representative production traces as items to this dataset so I can use it for experiments and evaluation.",+ },+ {+ id: "set-up-experiment-on-this-dataset",+ label: "Prep an experiment",+ description: "Attach evaluators and get ready to run",+ icon: Beaker,+ prompt:+ "Help me get an experiment ready on this dataset: check that its item keys match my prompt variables, confirm an LLM connection is configured, and attach an evaluator to score the results. Langfuse runs the experiment itself, so point me to the experiments UI to start it, or give me a ready-to-use prompt I can hand a coding agent to run it via the SDK.",+ },+ {+ id: "review-this-dataset",+ label: "Review this dataset",+ description: "Assess coverage and quality of items",+ icon: ClipboardCheck,+ prompt:+ "Review this dataset's items for coverage, diversity, and quality, and recommend improvements before I run experiments or evaluations on it.",+ },+ ],+ experimentRun: [+ {+ id: "summarize-this-experiment-run",+ label: "Summarize this experiment run",+ description: "Understand how this run performed",+ icon: FlaskConical,+ prompt:+ "Summarize this experiment run, including its configuration, scores, and how it compares to the dataset baseline.",+ },+ {+ id: "compare-this-experiment-run",+ label: "Compare to other runs",+ description: "See how this run stacks up",+ icon: GitCompareArrows,+ prompt:+ "Compare this experiment run to other recent runs on the same dataset and summarize which configuration performed best.",+ },+ {+ id: "investigate-this-experiment-run",+ label: "Investigate this run's results",+ description: "Find where this run succeeded or failed",+ icon: ScanSearch,+ prompt:+ "Investigate this experiment run's results, highlight the best and worst-performing items, and explain likely causes.",+ },+ ],+} satisfies Record<string, readonly InAppAgentQuickAction[]>;++// Coarse section -> tab classifier for the quick-action picker.+// getInAppAgentScreenContextDescription() in context.ts classifies the same+// URL at entity granularity (for the banner and focused action sets).+const QUICK_ACTION_CONTEXT_BY_PROJECT_SECTION: Record<+ string,+ InAppAgentQuickActionContext+> = {+ traces: "observability",+ observations: "observability",+ sessions: "observability",+ users: "observability",+ monitors: "observability",+ dashboards: "dashboards",+ widgets: "dashboards",+ prompts: "prompts",+ playground: "prompts",+ scores: "evaluation",+ evals: "evaluation",+ "annotation-queues": "evaluation",+ datasets: "evaluation",+ experiments: "evaluation",+};++export function getInAppAgentQuickActionContext(+ currentUrl: string,+): InAppAgentQuickActionContext {+ const section = getInAppAgentProjectRoute(currentUrl)?.routeSegments[0];++ return section+ ? (QUICK_ACTION_CONTEXT_BY_PROJECT_SECTION[section] ?? "observability")+ : "observability";+}++export function getInAppAgentQuickActions(+ context: InAppAgentQuickActionContext,+): readonly InAppAgentQuickAction[] {+ return IN_APP_AGENT_QUICK_ACTIONS_BY_CONTEXT[context];+}++export function getInAppAgentFocusedQuickActions(+ screenContextType: string,+): readonly InAppAgentQuickAction[] | undefined {+ if (!(screenContextType in IN_APP_AGENT_FOCUSED_QUICK_ACTIONS)) {+ return undefined;+ }++ return IN_APP_AGENT_FOCUSED_QUICK_ACTIONS[+ screenContextType as keyof typeof IN_APP_AGENT_FOCUSED_QUICK_ACTIONS+ ];+}++export function isInAppAgentQuickActionContext(+ value: string,+): value is InAppAgentQuickActionContext {+ return IN_APP_AGENT_QUICK_ACTION_CONTEXTS.some(+ (context) => context === value,+ );+}diff --git a/web/src/ee/features/in-app-agent/routeContext.ts b/web/src/ee/features/in-app-agent/routeContext.tsnew file mode 100644index 0000000000..a7a924a0f5--- /dev/null+++ b/web/src/ee/features/in-app-agent/routeContext.ts@@ -0,0 +1,35 @@+export function getInAppAgentProjectRoute(currentUrl: string):+ | {+ parsedUrl: URL;+ routeSegments: string[];+ }+ | undefined {+ let parsedUrl: URL;++ try {+ parsedUrl = new URL(currentUrl, "https://langfuse.local");+ } catch {+ return undefined;+ }++ const rawPathSegments = parsedUrl.pathname.split("/").filter(Boolean);+ const projectSegmentIndex = rawPathSegments.indexOf("project");++ if (+ projectSegmentIndex === -1 ||+ rawPathSegments.length <= projectSegmentIndex + 2+ ) {+ return undefined;+ }++ try {+ return {+ parsedUrl,+ routeSegments: rawPathSegments+ .slice(projectSegmentIndex + 2)+ .map((segment) => decodeURIComponent(segment)),+ };+ } catch {+ return undefined;+ }+}diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex 4985895e37..408a243e15 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -7,7 +7,10 @@ import {createInAppAgentMessageId,createInAppAgentRunId,} from "@/src/ee/features/in-app-agent/ids";-import { sanitizeInAppAgentContext } from "@/src/ee/features/in-app-agent/context";+import {+ getInAppAgentQuickActionTraceMetadata,+ sanitizeInAppAgentContext,+} from "@/src/ee/features/in-app-agent/context";import { getInAppAgentInstrumentationTraceId } from "@/src/ee/features/in-app-agent/constants";import {AgUiRunAgentInputSchema,@@ -547,6 +550,7 @@ export default async function handler(request: Request) {parsedState.data.type === "existingConversation"? "existing": "new",+ ...getInAppAgentQuickActionTraceMetadata(input.context),},});diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 2358381b47..c5f406d2f3 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -279,7 +279,7 @@ export const events = {"message_sent","community_hours_click",], // also used on landing page for consistency- in_app_agent: ["new_chat_started", "new_chat_turn"],+ in_app_agent: ["new_chat_started", "new_chat_turn", "quick_action_started"],cmd_k_menu: ["opened", "search_entered", "navigated"],spend_alert: ["created", "updated", "deleted"],sidebar: ["book_a_call_clicked", "v4_beta_toggled"],