Skip to content

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

fix(agent): Make user aware of screen context (#15079)

Ben Bachemc0d66e9cc717
diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index 82ddd7f186..137e01c081 100644
--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -1,10 +1,12 @@
"use client";
import { useMemo } from "react";
+import { useRouter } from "next/router";
import { InAppAgentWindow } from "./InAppAgentWindow";
import type { InAppAgentWindowConversation } from "./InAppAgentWindow";
import { useInAppAiAgent } from "./InAppAiAgentProvider";
import { getDrawerMessages } from "./utils/utils";
+import { getInAppAgentScreenContextDescription } from "@/src/ee/features/in-app-agent/context";
type ControlledInAppAgentWindowBaseProps = {
isHeaderDragHandleEnabled?: boolean;
@@ -28,6 +30,7 @@ type ControlledInAppAgentWindowProps = ControlledInAppAgentWindowBaseProps &
export function ControlledInAppAgentWindow(
props: ControlledInAppAgentWindowProps,
) {
+ const router = useRouter();
const {
conversations,
error,
@@ -52,6 +55,10 @@ export function ControlledInAppAgentWindow(
isSubmitting ||
isSelectedConversationHydrating ||
pendingToolApprovals.length > 0;
+ const screenContextDescription = useMemo(
+ () => getInAppAgentScreenContextDescription(router.asPath),
+ [router.asPath],
+ );
const drawerMessages = useMemo(
() =>
@@ -77,6 +84,7 @@ export function ControlledInAppAgentWindow(
isExpanded={props.isExpanded}
isInputDisabled={isInputDisabled}
messages={drawerMessages}
+ screenContextDescription={screenContextDescription}
conversations={conversations}
hasMoreConversations={hasMoreConversations}
isLoadingMoreConversations={isLoadingMoreConversations}
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.tsx
index dcd263372c..cecd4e435c 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
@@ -521,6 +521,7 @@ const meta = preview.meta({
onExpandedChange: fn(),
onSubmit: fn(),
onSubmitFeedback: fn(),
+ screenContextDescription: { type: "page" as const },
showCloseButton: true,
},
render: (args) => <StatefulInAppAgentWindow {...args} />,
@@ -528,6 +529,7 @@ const meta = preview.meta({
export const ToolApprovalRequired = meta.story({
args: {
+ isAssistantTurnInProgress: true,
isInputDisabled: true,
selectedConversationId: "conversation-1",
messages: [
@@ -573,6 +575,7 @@ export const Empty = meta.story({
export const Conversation = meta.story({
args: {
selectedConversationId: "conversation-1",
+ screenContextDescription: { type: "experimentRun" as const },
messages: [
{
id: "user-1",
@@ -742,7 +745,6 @@ export const Conversation = meta.story({
export const Streaming = meta.story({
args: {
isAssistantTurnInProgress: true,
- isInputDisabled: true,
selectedConversationId: "conversation-1",
messages: streamingSeedMessages,
},
@@ -752,7 +754,6 @@ export const Streaming = meta.story({
export const LoadingResponse = meta.story({
args: {
isAssistantTurnInProgress: true,
- isInputDisabled: true,
messages: [
{
id: "user-1",
@@ -987,7 +988,28 @@ export const RateLimited = meta.story({
name: "(Test) Rate Limited",
args: {
error: null,
- messages: [],
+ isAssistantTurnInProgress: true,
+ isInputDisabled: true,
+ messages: [
+ {
+ id: "approval-1",
+ role: "assistant",
+ content: {
+ type: "toolGroup",
+ tools: [
+ {
+ type: "tool",
+ name: "langfuse_upsertDataset",
+ args: JSON.stringify({ name: "regression-examples" }),
+ approval: {
+ id: "approval-1",
+ status: "pending",
+ },
+ },
+ ],
+ },
+ },
+ ],
},
render: function Render(args) {
const [retryAt] = useState(() => Date.now() + 12_000);
@@ -1015,14 +1037,15 @@ export const RateLimited = meta.story({
canvas.getByRole("textbox", { name: "Ask the assistant a question" }),
).toBeDisabled();
await expect(
- canvas.getByRole("button", { name: "Get started with Langfuse" }),
+ canvas.getByRole("button", { name: "Confirm" }),
).toBeDisabled();
+ await expect(canvas.getByRole("button", { name: "Reject" })).toBeDisabled();
await expect(
canvas.getByRole("button", { name: "Start new conversation" }),
- ).toBeEnabled();
+ ).toBeDisabled();
await expect(
canvas.getByRole("button", { name: "Conversation history" }),
- ).toBeEnabled();
+ ).toBeDisabled();
},
});
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
index 2da5e12ea6..452f5ae681 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -10,6 +10,7 @@ import {
import {
BotMessageSquare,
History,
+ Info,
Maximize2,
Minimize2,
Minus,
@@ -39,12 +40,14 @@ import {
type InAppAgentMessageRole,
} from "./InAppAgentMessage";
import type { InAppAgentMessageFeedbackValue } from "@/src/ee/features/in-app-agent/schema";
+import type { InAppAgentScreenContextDescription } from "@/src/ee/features/in-app-agent/context";
import { InAppAgentToolCallCard } from "@/src/ee/features/in-app-agent/components/InAppAgentToolCallCard";
import {
type InAppAgentError,
isInAppAgentRateLimited,
} from "@/src/ee/features/in-app-agent/components/utils/utils";
import styles from "./InAppAgentWindow.module.css";
+import { assertUnreachable } from "@/src/utils/types";
const AUTO_SCROLL_THRESHOLD_PX = 50;
const SCROLL_DIRECTION_TOLERANCE_PX = 1;
@@ -75,6 +78,64 @@ function scrollViewportToBottom(viewport: HTMLDivElement | null) {
});
}
+function formatScreenContextNotice(
+ description: InAppAgentScreenContextDescription,
+) {
+ if (description.type === "page") {
+ return "The assistant is aware of your current page.";
+ }
+
+ if (description.type === "observation") {
+ return "The assistant is aware that you're viewing this observation.";
+ }
+
+ if (description.type === "trace") {
+ return "The assistant is aware that you're viewing this trace.";
+ }
+
+ if (description.type === "prompt") {
+ return "The assistant is aware that you're viewing this prompt.";
+ }
+
+ if (description.type === "session") {
+ return "The assistant is aware that you're viewing this session.";
+ }
+
+ if (description.type === "dataset") {
+ return "The assistant is aware that you're viewing this dataset.";
+ }
+
+ if (description.type === "datasetItem") {
+ return "The assistant is aware that you're viewing this dataset item.";
+ }
+
+ if (description.type === "experimentRun") {
+ return "The assistant is aware that you're viewing this experiment run.";
+ }
+
+ if (
+ description.type === "trace-list" ||
+ description.type === "observations-list" ||
+ description.type === "sessions-list" ||
+ description.type === "prompts-list" ||
+ description.type === "datasets-list"
+ ) {
+ const listLabel = {
+ "trace-list": "trace",
+ "observations-list": "observation",
+ "sessions-list": "session",
+ "prompts-list": "prompt",
+ "datasets-list": "dataset",
+ }[description.type];
+
+ return description.hasAppliedFilters
+ ? `The assistant is aware of this ${listLabel} view and its filters.`
+ : `The assistant is aware of this ${listLabel} view.`;
+ }
+
+ return assertUnreachable(description);
+}
+
export type InAppAgentWindowMessage = {
id: string;
runId?: string;
@@ -123,6 +184,7 @@ export type InAppAgentWindowProps = {
value: InAppAgentMessageFeedbackValue | null;
comment?: string | null;
}) => Promise<void>;
+ screenContextDescription: InAppAgentScreenContextDescription;
selectedConversationId: string | undefined;
} & InAppAgentWindowCloseButtonProps;
@@ -156,7 +218,7 @@ function InAppAgentRateLimitError({
<div
role="alert"
className={cn(
- "border-border bg-muted/60 text-foreground rounded-lg border px-2 py-1",
+ "border-border bg-muted/60 text-foreground w-full rounded-lg border px-2 py-1",
isExpanded ? "text-sm" : "text-xs",
)}
>
@@ -211,8 +273,12 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
onSelectConversation,
onSubmit,
onSubmitFeedback,
+ screenContextDescription,
selectedConversationId,
} = props;
+ const screenContextNotice = formatScreenContextNotice(
+ screenContextDescription,
+ );
const isRateLimited = isInAppAgentRateLimited(error);
const isInputDisabled = baseIsInputDisabled || isRateLimited;
const viewportRef = useRef<HTMLDivElement>(null);
@@ -659,9 +725,46 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
</div>
</div>
) : null}
- {error?.type === "rate_limit" && (
+ <div
+ aria-hidden={isAssistantTurnInProgress}
+ className={cn(
+ "flex shrink-0 flex-col overflow-hidden transition-[max-height,opacity] duration-200 ease-out motion-reduce:transition-none",
+ isAssistantTurnInProgress
+ ? "max-h-0 opacity-0"
+ : "max-h-40 opacity-100",
+ )}
+ >
<div className="p-2">
- <InAppAgentRateLimitError error={error} isExpanded={isExpanded} />
+ <div
+ className={cn(
+ "flex w-full flex-col gap-1.5",
+ isExpanded && "mx-auto max-w-3xl",
+ )}
+ >
+ <p
+ className={cn(
+ "border-border bg-muted/60 text-foreground flex w-full items-center gap-1 rounded-lg border px-2 py-1",
+ isExpanded ? "text-sm" : "text-xs",
+ )}
+ >
+ <Info aria-hidden="true" className="size-3 shrink-0" />
+ <span className="min-w-0 truncate" title={screenContextNotice}>
+ {screenContextNotice}
+ </span>
+ </p>
+ </div>
+ </div>
+ </div>
+ {error?.type === "rate_limit" && (
+ <div
+ className={cn(
+ "shrink-0 px-2 pb-2",
+ isAssistantTurnInProgress && "pt-2",
+ )}
+ >
+ <div className={cn(isExpanded && "mx-auto max-w-3xl")}>
+ <InAppAgentRateLimitError error={error} isExpanded={isExpanded} />
+ </div>
</div>
)}
{isAssistantTurnInProgress && pendingToolCalls.length === 0 ? (
diff --git a/web/src/ee/features/in-app-agent/context.clienttest.ts b/web/src/ee/features/in-app-agent/context.clienttest.ts
new file mode 100644
index 0000000000..74a9b432c2
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/context.clienttest.ts
@@ -0,0 +1,131 @@
+import { getInAppAgentScreenContextDescription } from "./context";
+
+describe("getInAppAgentScreenContextDescription", () => {
+ it.each([
+ {
+ name: "trace detail",
+ url: "/project/project-1/traces/trace-1",
+ expected: { type: "trace" },
+ },
+ {
+ name: "selected observation in a trace",
+ url: "/project/project-1/traces/trace-1?observation=observation-1",
+ expected: { type: "observation" },
+ },
+ {
+ name: "empty observation selection",
+ url: "/project/project-1/traces/trace-1?observation=",
+ expected: { type: "trace" },
+ },
+ {
+ name: "observation peek",
+ url: "/project/project-1/observations?peek=observation-1&traceId=trace-1",
+ expected: { type: "observation" },
+ },
+ {
+ name: "observation peek in V4 events table",
+ url: "/project/project-1/traces?peek=trace-1&observation=observation-1",
+ expected: { type: "observation" },
+ },
+ {
+ name: "trace peek",
+ url: "/project/project-1/traces?peek=trace-1",
+ expected: { type: "trace" },
+ },
+ {
+ name: "trace list without filters",
+ url: "/project/project-1/traces",
+ expected: { type: "trace-list", hasAppliedFilters: false },
+ },
+ {
+ name: "trace list with structured filters",
+ url: "/project/project-1/traces?filter=level%3BstringOptions%3B%3Bany+of%3BERROR",
+ expected: { type: "trace-list", hasAppliedFilters: true },
+ },
+ {
+ name: "observations list with full-text search",
+ url: "/project/project-1/observations?search=checkout&searchType=id",
+ expected: { type: "observations-list", hasAppliedFilters: true },
+ },
+ {
+ name: "trace setup page",
+ url: "/project/project-1/traces/setup",
+ expected: { type: "page" },
+ },
+ {
+ name: "prompt version",
+ url: "/project/project-1/prompts/folder%2Fcheckout?version=12",
+ expected: {
+ type: "prompt",
+ name: "folder/checkout",
+ selector: { type: "version", value: "12" },
+ },
+ },
+ {
+ name: "prompt label",
+ url: "/project/project-1/prompts/checkout?label=production",
+ expected: {
+ type: "prompt",
+ name: "checkout",
+ selector: { type: "label", value: "production" },
+ },
+ },
+ {
+ name: "prompt metrics",
+ url: "/project/project-1/prompts/folder/checkout/metrics",
+ expected: { type: "prompt", name: "folder/checkout" },
+ },
+ {
+ name: "legacy prompt detail",
+ url: "/project/project-1/prompts/prompt-detail?promptName=checkout",
+ expected: { type: "prompt", name: "checkout" },
+ },
+ {
+ name: "session detail",
+ url: "/project/project-1/sessions/support%2F123",
+ expected: { type: "session", id: "support/123" },
+ },
+ {
+ name: "sessions list",
+ url: "/project/project-1/sessions",
+ expected: { type: "sessions-list", hasAppliedFilters: false },
+ },
+ {
+ name: "prompts list",
+ url: "/project/project-1/prompts?filter=type%3BstringOptions%3B%3D%3Bchat",
+ expected: { type: "prompts-list", hasAppliedFilters: true },
+ },
+ {
+ name: "dataset detail",
+ url: "/project/project-1/datasets/dataset-1/items",
+ expected: { type: "dataset" },
+ },
+ {
+ name: "dataset item detail",
+ url: "/project/project-1/datasets/dataset-1/items/item-1",
+ expected: { type: "datasetItem" },
+ },
+ {
+ name: "experiment run detail",
+ url: "/project/project-1/datasets/dataset-1/runs/run-1",
+ expected: { type: "experimentRun" },
+ },
+ {
+ name: "datasets list",
+ url: "/project/project-1/datasets",
+ expected: { type: "datasets-list", hasAppliedFilters: false },
+ },
+ {
+ name: "unknown project page",
+ url: "/project/project-1/scores",
+ expected: { type: "page" },
+ },
+ {
+ name: "malformed encoded path",
+ url: "/project/project-1/prompts/%E0%A4%A",
+ expected: { type: "page" },
+ },
+ ])("describes $name", ({ url, expected }) => {
+ expect(getInAppAgentScreenContextDescription(url)).toEqual(expected);
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/context.ts b/web/src/ee/features/in-app-agent/context.ts
index 6856efcf43..8c87caa7f9 100644
--- a/web/src/ee/features/in-app-agent/context.ts
+++ b/web/src/ee/features/in-app-agent/context.ts
@@ -2,6 +2,27 @@ import type { AgUiRunAgentInput } from "@/src/ee/features/in-app-agent/schema";
type InAppAgentContext = AgUiRunAgentInput["context"];
+export type InAppAgentScreenContextDescription =
+ | { type: "page" }
+ | { type: "observation" }
+ | { type: "trace" }
+ | {
+ type: "prompt";
+ name: string;
+ selector?:
+ | { type: "version"; value: string }
+ | { type: "label"; value: string };
+ }
+ | { type: "session"; id: string }
+ | { type: "dataset" }
+ | { type: "datasetItem" }
+ | { type: "experimentRun" }
+ | { type: "trace-list"; hasAppliedFilters: boolean }
+ | { type: "observations-list"; hasAppliedFilters: boolean }
+ | { type: "sessions-list"; hasAppliedFilters: boolean }
+ | { type: "prompts-list"; hasAppliedFilters: boolean }
+ | { type: "datasets-list"; hasAppliedFilters: boolean };
+
const CURRENT_URL_CONTEXT_DESCRIPTION = "current_url";
const MAX_SCREEN_CONTEXT_SEARCH_PARAMS = 30;
const MAX_CONTEXT_KEY_LENGTH = 80;
@@ -15,6 +36,130 @@ const USER_CONTEXT_DESCRIPTIONS = new Set([
"browser_languages",
]);
+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");
+
+ if (
+ projectSegmentIndex === -1 ||
+ rawPathSegments.length <= projectSegmentIndex + 2
+ ) {
+ return { type: "page" };
+ }
+
+ let routeSegments: string[];
+
+ try {
+ routeSegments = rawPathSegments
+ .slice(projectSegmentIndex + 2)
+ .map((segment) => decodeURIComponent(segment));
+ } catch {
+ return { type: "page" };
+ }
+
+ const section = routeSegments[0];
+ const detailId = routeSegments[1];
+ const peekId = parsedUrl.searchParams.get("peek");
+ const observationId = parsedUrl.searchParams.get("observation");
+ const hasAppliedFilters = ["filter", "search"].some((parameter) =>
+ Boolean(parsedUrl.searchParams.get(parameter)?.trim()),
+ );
+
+ if (
+ (section === "traces" && observationId && (detailId || peekId)) ||
+ (section === "observations" && peekId)
+ ) {
+ return { type: "observation" };
+ }
+
+ if (section === "traces" && ((detailId && detailId !== "setup") || peekId)) {
+ return { type: "trace" };
+ }
+
+ if (section === "traces" && !detailId) {
+ return { type: "trace-list", hasAppliedFilters };
+ }
+
+ if (section === "observations" && !detailId) {
+ return { type: "observations-list", hasAppliedFilters };
+ }
+
+ if (section === "prompts") {
+ const promptPathSegments = routeSegments.slice(1);
+ const isMetricsPage =
+ promptPathSegments[promptPathSegments.length - 1] === "metrics";
+ const promptName = (
+ isMetricsPage ? promptPathSegments.slice(0, -1) : promptPathSegments
+ ).join("/");
+ const legacyPromptName = parsedUrl.searchParams.get("promptName");
+ const resolvedPromptName =
+ promptName === "prompt-detail" ? legacyPromptName : promptName;
+
+ if (resolvedPromptName && resolvedPromptName !== "new") {
+ const version = parsedUrl.searchParams.get("version");
+ const label = parsedUrl.searchParams.get("label");
+
+ if (version && /^\d+$/.test(version)) {
+ return {
+ type: "prompt",
+ name: resolvedPromptName,
+ selector: { type: "version", value: version },
+ };
+ }
+
+ if (label) {
+ return {
+ type: "prompt",
+ name: resolvedPromptName,
+ selector: { type: "label", value: label },
+ };
+ }
+
+ return { type: "prompt", name: resolvedPromptName };
+ }
+
+ if (promptPathSegments.length === 0) {
+ return { type: "prompts-list", hasAppliedFilters };
+ }
+ }
+
+ if (section === "sessions" && detailId) {
+ return { type: "session", id: detailId };
+ }
+
+ if (section === "sessions" && !detailId) {
+ return { type: "sessions-list", hasAppliedFilters };
+ }
+
+ if (section === "datasets" && detailId) {
+ if (routeSegments[2] === "runs" && routeSegments[3]) {
+ return { type: "experimentRun" };
+ }
+
+ if (routeSegments[2] === "items" && routeSegments[3]) {
+ return { type: "datasetItem" };
+ }
+
+ return { type: "dataset" };
+ }
+
+ if (section === "datasets" && !detailId) {
+ return { type: "datasets-list", hasAppliedFilters };
+ }
+
+ return { type: "page" };
+}
+
export function createInAppAgentScreenContext(params: {
currentUrl: string;
}): InAppAgentContext {