Skip to content

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

feat(agent): Direct entrypoint in 'add widget' modal to use assistant to create dashboard widgets (#15162)

Lysander Kieself20845b6a4e0
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.ts
index b0b5091e39..7fb96458a5 100644
--- 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.ts
@@ -1,4 +1,5 @@
import {
+ getInAppAgentMessageEntryPointTraceMetadata,
getInAppAgentQuickActionTraceMetadata,
sanitizeInAppAgentContext,
} from "@/src/ee/features/in-app-agent/context";
@@ -52,3 +53,22 @@ describe("in-app agent quick-action attribution", () => {
).toEqual({});
});
});
+
+describe("in-app agent message entry point", () => {
+ it("exposes allowlisted entry points as trace metadata and keeps them out of the model-visible context", () => {
+ const context = [
+ { description: "message_entry_point", value: "add-widget-modal" },
+ ];
+
+ expect(getInAppAgentMessageEntryPointTraceMetadata(context)).toEqual({
+ message_entry_point: "add-widget-modal",
+ });
+ expect(sanitizeInAppAgentContext(context, "project-1")).toEqual([]);
+
+ expect(
+ getInAppAgentMessageEntryPointTraceMetadata([
+ { description: "message_entry_point", value: "not-a-real-source" },
+ ]),
+ ).toEqual({});
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.clienttest.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.clienttest.tsx
new file mode 100644
index 0000000000..9043072b2d
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.clienttest.tsx
@@ -0,0 +1,74 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { InAppAgentWidgetComposer } from "./InAppAgentWidgetComposer";
+
+const openAssistant = vi.fn().mockReturnValue(true);
+const submit = vi.fn().mockResolvedValue(true);
+
+vi.mock("./InAppAiAgentProvider", () => ({
+ useInAppAiAgent: () => ({
+ isAvailable: true,
+ isRunning: false,
+ isSubmitting: false,
+ openAssistant,
+ submit,
+ }),
+}));
+
+describe("InAppAgentWidgetComposer", () => {
+ beforeEach(() => {
+ openAssistant.mockClear().mockReturnValue(true);
+ submit.mockClear().mockResolvedValue(true);
+ });
+
+ it("starts a fresh Assistant conversation with the widget request", async () => {
+ const onSubmitted = vi.fn();
+ render(<InAppAgentWidgetComposer onSubmitted={onSubmitted} />);
+
+ fireEvent.change(screen.getByLabelText("Describe the widget you want"), {
+ target: { value: " Show p95 latency by model " },
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Add with Langfuse Assistant" }),
+ );
+
+ await waitFor(() => {
+ expect(submit).toHaveBeenCalledWith(
+ "Create a dashboard widget for this request and add it to the current dashboard:\n\nShow p95 latency by model\n\nChoose an appropriate data view, metrics, dimensions, filters, and chart type. Briefly explain the plan, then create the widget.",
+ { newConversation: true, entryPoint: "add-widget-modal" },
+ );
+ });
+ expect(openAssistant).toHaveBeenCalledWith("dashboard_widget");
+ expect(onSubmitted).toHaveBeenCalledOnce();
+ });
+
+ it("disables submit for whitespace-only input", () => {
+ render(<InAppAgentWidgetComposer onSubmitted={vi.fn()} />);
+
+ fireEvent.change(screen.getByLabelText("Describe the widget you want"), {
+ target: { value: " " },
+ });
+
+ expect(
+ screen.getByRole("button", { name: "Add with Langfuse Assistant" }),
+ ).toBeDisabled();
+ });
+
+ it("keeps the picker open and preserves the request when submit does not start", async () => {
+ submit.mockResolvedValue(false);
+ const onSubmitted = vi.fn();
+ render(<InAppAgentWidgetComposer onSubmitted={onSubmitted} />);
+
+ const input = screen.getByLabelText("Describe the widget you want");
+ fireEvent.change(input, { target: { value: "Show error rate" } });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Add with Langfuse Assistant" }),
+ );
+
+ await waitFor(() => {
+ expect(submit).toHaveBeenCalledOnce();
+ });
+ expect(onSubmitted).not.toHaveBeenCalled();
+ expect(input).toHaveValue("Show error rate");
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.tsx
new file mode 100644
index 0000000000..f2e05eab43
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer.tsx
@@ -0,0 +1,112 @@
+import { type KeyboardEvent, type SyntheticEvent, useState } from "react";
+import { SendHorizontal, Sparkles } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { Textarea } from "@/src/components/ui/textarea";
+import { useInAppAiAgent } from "@/src/ee/features/in-app-agent/components/InAppAiAgentProvider";
+
+const MAX_TEXTAREA_HEIGHT_PX = 160;
+
+// Grow the textarea to fit its content up to a cap, then scroll. Driven from the
+// change/submit events (no effect): the initiating event owns the DOM sync.
+function resizeTextarea(textarea: HTMLTextAreaElement | null) {
+ if (!textarea) {
+ return;
+ }
+
+ textarea.style.height = "auto";
+ textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT_PX)}px`;
+}
+
+const getWidgetCreationPrompt = (request: string) =>
+ `Create a dashboard widget for this request and add it to the current dashboard:\n\n${request}\n\nChoose an appropriate data view, metrics, dimensions, filters, and chart type. Briefly explain the plan, then create the widget.`;
+
+export function InAppAgentWidgetComposer({
+ onSubmitted,
+}: {
+ onSubmitted: () => void;
+}) {
+ const { isAvailable, isRunning, isSubmitting, openAssistant, submit } =
+ useInAppAiAgent();
+ const [request, setRequest] = useState("");
+
+ if (!isAvailable) {
+ return null;
+ }
+
+ const handleSubmit = async (event: SyntheticEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ const trimmedRequest = request.trim();
+
+ if (!trimmedRequest || isRunning || isSubmitting) {
+ return;
+ }
+
+ if (!openAssistant("dashboard_widget")) {
+ return;
+ }
+
+ const started = await submit(getWidgetCreationPrompt(trimmedRequest), {
+ newConversation: true,
+ entryPoint: "add-widget-modal",
+ });
+
+ if (started) {
+ setRequest("");
+ onSubmitted();
+ }
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (
+ event.key === "Enter" &&
+ !event.shiftKey &&
+ !event.nativeEvent.isComposing
+ ) {
+ event.preventDefault();
+ event.currentTarget.form?.requestSubmit();
+ }
+ };
+
+ return (
+ <form
+ onSubmit={handleSubmit}
+ className="bg-muted/30 flex flex-col gap-2 rounded-lg border p-3"
+ >
+ <div className="flex items-center gap-2 font-medium">
+ <Sparkles className="h-4 w-4" />
+ Add with Langfuse Assistant
+ </div>
+ <p className="text-muted-foreground text-xs">
+ Describe the chart you need. The Assistant will create it as a widget
+ and add it to this dashboard.
+ </p>
+ <div className="flex items-end gap-2">
+ <Textarea
+ aria-label="Describe the widget you want"
+ autoComplete="off"
+ maxLength={2000}
+ rows={1}
+ placeholder="e.g. Show p95 latency by model over the last 7 days"
+ value={request}
+ onChange={(event) => {
+ setRequest(event.target.value);
+ resizeTextarea(event.currentTarget);
+ }}
+ onKeyDown={handleKeyDown}
+ className="max-h-40 min-h-8 resize-none px-2 py-1 leading-5"
+ />
+ <Button
+ type="submit"
+ size="icon"
+ className="h-8 w-8 shrink-0 rounded-md border"
+ variant="outline"
+ aria-label="Add with Langfuse Assistant"
+ disabled={!request.trim() || isRunning || isSubmitting}
+ >
+ <SendHorizontal className="h-4 w-4" />
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
index e9cfc52d20..63afe63a69 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -38,9 +38,11 @@ import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { api } from "@/src/utils/api";
import {
+ createInAppAgentMessageEntryPointContext,
createInAppAgentQuickActionAttributionContext,
createInAppAgentScreenContext,
createInAppAgentUserContext,
+ type InAppAgentMessageEntryPoint,
} from "@/src/ee/features/in-app-agent/context";
import type {
InAppAgentQuickActionAttribution,
@@ -63,7 +65,10 @@ const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
"Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
const EMPTY_MESSAGES: AgUiMessage[] = [];
-export type InAppAgentEntryPoint = "top_nav" | "keyboard_shortcut";
+export type InAppAgentEntryPoint =
+ | "top_nav"
+ | "keyboard_shortcut"
+ | "dashboard_widget";
const MastraSuspendEventSchema = z.object({
type: z.literal("mastra_suspend"),
@@ -646,6 +651,7 @@ function InAppAiAgentProviderInner({
conversationId: string,
runParameters?: Parameters<HttpAgent["runAgent"]>[0],
quickActionAttribution?: InAppAgentQuickActionAttribution,
+ messageEntryPoint?: InAppAgentMessageEntryPoint,
) => {
clearLoadingEvents();
setIsRunning(true);
@@ -668,6 +674,9 @@ function InAppAiAgentProviderInner({
quickActionAttribution,
)
: [],
+ messageEntryPoint
+ ? createInAppAgentMessageEntryPointContext(messageEntryPoint)
+ : [],
),
})
.then(() => true)
@@ -791,7 +800,8 @@ function InAppAiAgentProviderInner({
!content ||
isRunning ||
isInAppAgentRateLimited(error) ||
- isSelectedConversationHydrating ||
+ (options?.newConversation !== true &&
+ isSelectedConversationHydrating) ||
submitInFlightRef.current
) {
return false;
@@ -803,7 +813,10 @@ function InAppAiAgentProviderInner({
let startedRun = false;
try {
- if (selectedConversationIsWriteLocked) {
+ const isNewConversation =
+ options?.newConversation === true || !selectedConversationId;
+
+ if (!isNewConversation && selectedConversationIsWriteLocked) {
setError({
type: "generic",
message: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
@@ -811,9 +824,13 @@ function InAppAiAgentProviderInner({
return false;
}
- const isNewConversation = !selectedConversationId;
- const conversationId =
- selectedConversationId ?? createInAppAgentConversationId();
+ const conversationId = isNewConversation
+ ? createInAppAgentConversationId()
+ : selectedConversationId;
+
+ if (!conversationId) {
+ return false;
+ }
if (isNewConversation) {
setSelectedConversationId(conversationId);
@@ -848,12 +865,19 @@ function InAppAiAgentProviderInner({
agent.addMessage(userMessage);
setMessages(agent.messages.filter(isAgentConversationMessage));
+ const entryPoint = options?.entryPoint ?? "chat";
if (isNewConversation) {
- capture("in_app_agent:new_chat_started");
+ capture("in_app_agent:new_chat_started", { entryPoint });
}
- capture("in_app_agent:new_chat_turn");
+ capture("in_app_agent:new_chat_turn", { entryPoint });
startedRun = true;
- runAgent(agent, conversationId, undefined, options?.quickAction);
+ runAgent(
+ agent,
+ conversationId,
+ undefined,
+ options?.quickAction,
+ entryPoint,
+ );
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.ts
index f980045827..ae31af0611 100644
--- a/web/src/ee/features/in-app-agent/context.ts
+++ b/web/src/ee/features/in-app-agent/context.ts
@@ -31,6 +31,7 @@ export type InAppAgentScreenContextDescription =
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 MESSAGE_ENTRY_POINT_CONTEXT_DESCRIPTION = "message_entry_point";
const MAX_SCREEN_CONTEXT_SEARCH_PARAMS = 30;
const MAX_CONTEXT_KEY_LENGTH = 80;
const MAX_CONTEXT_VALUE_LENGTH = 500;
@@ -252,6 +253,44 @@ export function getInAppAgentQuickActionTraceMetadata(
: {};
}
+export const IN_APP_AGENT_MESSAGE_ENTRY_POINTS = [
+ "chat",
+ "add-widget-modal",
+] as const;
+
+export type InAppAgentMessageEntryPoint =
+ (typeof IN_APP_AGENT_MESSAGE_ENTRY_POINTS)[number];
+
+export function createInAppAgentMessageEntryPointContext(
+ entryPoint: InAppAgentMessageEntryPoint,
+): InAppAgentContext {
+ return [
+ {
+ description: MESSAGE_ENTRY_POINT_CONTEXT_DESCRIPTION,
+ value: entryPoint,
+ },
+ ];
+}
+
+// Telemetry only, like quick-action attribution: read for trace metadata but
+// never forwarded into the model-visible sanitized context.
+export function getInAppAgentMessageEntryPointTraceMetadata(
+ context: InAppAgentContext,
+): Record<string, string> {
+ const entryPoint = context
+ .find(
+ (item) => item.description === MESSAGE_ENTRY_POINT_CONTEXT_DESCRIPTION,
+ )
+ ?.value.trim();
+
+ return entryPoint &&
+ (IN_APP_AGENT_MESSAGE_ENTRY_POINTS as readonly string[]).includes(
+ entryPoint,
+ )
+ ? { message_entry_point: entryPoint }
+ : {};
+}
+
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.ts b/web/src/ee/features/in-app-agent/quickActions.ts
index 68103ba87c..c609f2b6e9 100644
--- a/web/src/ee/features/in-app-agent/quickActions.ts
+++ b/web/src/ee/features/in-app-agent/quickActions.ts
@@ -1,3 +1,4 @@
+import type { InAppAgentMessageEntryPoint } from "@/src/ee/features/in-app-agent/context";
import { getInAppAgentProjectRoute } from "@/src/ee/features/in-app-agent/routeContext";
import {
Activity,
@@ -71,6 +72,11 @@ export type InAppAgentQuickActionAttribution = {
export type InAppAgentSubmitOptions = {
quickAction?: InAppAgentQuickActionAttribution;
+ /** Force a fresh conversation instead of appending to the selected one. */
+ newConversation?: boolean;
+ /** Which surface sent the message; telemetry only (PostHog + trace
+ * metadata), never shown to the agent. Defaults to "chat". */
+ entryPoint?: InAppAgentMessageEntryPoint;
};
// Version 1 starter sets. Idea is that periodic curation replaces sets when usage
diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.ts
index 408a243e15..512a67f618 100644
--- a/web/src/ee/features/in-app-agent/server/handler.ts
+++ b/web/src/ee/features/in-app-agent/server/handler.ts
@@ -8,6 +8,7 @@ import {
createInAppAgentRunId,
} from "@/src/ee/features/in-app-agent/ids";
import {
+ getInAppAgentMessageEntryPointTraceMetadata,
getInAppAgentQuickActionTraceMetadata,
sanitizeInAppAgentContext,
} from "@/src/ee/features/in-app-agent/context";
@@ -551,6 +552,9 @@ export default async function handler(request: Request) {
? "existing"
: "new",
...getInAppAgentQuickActionTraceMetadata(input.context),
+ ...getInAppAgentMessageEntryPointTraceMetadata(
+ input.context,
+ ),
},
});
diff --git a/web/src/features/widgets/components/SelectWidgetDialog.tsx b/web/src/features/widgets/components/SelectWidgetDialog.tsx
index a34b953953..0e6e30ace1 100644
--- a/web/src/features/widgets/components/SelectWidgetDialog.tsx
+++ b/web/src/features/widgets/components/SelectWidgetDialog.tsx
@@ -26,6 +26,7 @@ import {
} from "@langfuse/shared";
import { HOME_PRESET_METADATA } from "@/src/features/dashboard/components/home-preset-registry";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import { InAppAgentWidgetComposer } from "@/src/ee/features/in-app-agent/components/InAppAgentWidgetComposer";
export type WidgetItem = {
id: string;
@@ -159,6 +160,9 @@ export function SelectWidgetDialog({
</div>
) : (
<div className="flex flex-col gap-3 p-1">
+ <InAppAgentWidgetComposer
+ onSubmitted={() => onOpenChange(false)}
+ />
<button
type="button"
onClick={() => {