Skip to content

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

fix(agent): Resolve saved view filters (#15311)

Ben Bachem2316bd936e16
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
index 80be0ccdb4..1e42c80874 100644
--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
@@ -8,11 +8,12 @@ import type {
} from "@/src/ee/features/in-app-agent/schema";
import { replaceRunEvents } from "@/src/ee/features/in-app-agent/server/persistence";
import { env } from "@/src/env.mjs";
-import { prisma } from "@langfuse/shared/src/db";
+import { Prisma, prisma } from "@langfuse/shared/src/db";
import {
createAndAddApiKeysToDb,
createBasicAuthHeader,
createOrgProjectAndApiKey,
+ TableViewService,
} from "@langfuse/shared/src/server";
import type { Session } from "next-auth";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -1043,6 +1044,249 @@ describe("in-app agent public API route auth", () => {
}
});
+ it("resolves saved view filters only on a compatible table route", async () => {
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
+ const originalAiFeaturesPublicKey = env.LANGFUSE_AI_FEATURES_PUBLIC_KEY;
+ const originalAiFeaturesSecretKey = env.LANGFUSE_AI_FEATURES_SECRET_KEY;
+
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";
+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY = "pk-lf-test";
+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY = "sk-lf-test";
+
+ const { org, project } = await createOrgProjectAndApiKey();
+ const filters = [
+ {
+ column: "name",
+ type: "stringOptions" as const,
+ operator: "any of" as const,
+ value: ["handle-chatbot-message"],
+ },
+ ];
+ const savedView = await prisma.tableViewPreset.create({
+ data: {
+ projectId: project.id,
+ name: "Chatbot messages",
+ tableName: "traces",
+ createdBy: null,
+ updatedBy: null,
+ filters,
+ columnOrder: [],
+ columnVisibility: {},
+ searchQuery: null,
+ orderBy: Prisma.JsonNull,
+ },
+ });
+
+ try {
+ await prisma.organization.update({
+ where: { id: org.id },
+ data: { aiFeaturesEnabled: true },
+ });
+ authMocks.getServerSession.mockResolvedValue(
+ await createPersistedInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ }),
+ );
+
+ const { default: handler } =
+ await import("@/src/ee/features/in-app-agent/server/handler");
+ const response = await handler(
+ new Request("http://localhost/api/in-app-agent", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ threadId: "conversation-1",
+ runId: "client-run-1",
+ messages: [{ id: "message-1", role: "user", content: "hello" }],
+ tools: [],
+ context: [
+ {
+ description: "current_url",
+ value: `https://cloud.langfuse.com/project/${project.id}/traces?viewId=${savedView.id}&filter=name%3BstringOptions%3B%3Bany+of%3Bhandle-chatbot-message&orderBy=column-startTime_order-DESC`,
+ },
+ ],
+ state: {
+ type: "newConversation",
+ projectId: project.id,
+ },
+ forwardedProps: {},
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(agentMocks.createAgUiStream).toHaveBeenCalledOnce();
+ const streamInput = agentMocks.createAgUiStream.mock.calls[0][0].input;
+
+ expect(JSON.parse(streamInput.context[0].value)).toEqual({
+ pathname: `/project/${project.id}/traces`,
+ searchParams: [
+ { key: "viewId", value: savedView.id },
+ {
+ key: "filter",
+ value: "name;stringOptions;;any of;handle-chatbot-message",
+ },
+ { key: "orderBy", value: "column-startTime_order-DESC" },
+ ],
+ hash: "",
+ savedView: {
+ filters,
+ },
+ });
+
+ const mismatchedResponse = await handler(
+ new Request("http://localhost/api/in-app-agent", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ threadId: "conversation-2",
+ runId: "client-run-2",
+ messages: [{ id: "message-2", role: "user", content: "hello" }],
+ tools: [],
+ context: [
+ {
+ description: "current_url",
+ value: `https://cloud.langfuse.com/project/${project.id}/sessions?viewId=${savedView.id}`,
+ },
+ ],
+ state: {
+ type: "newConversation",
+ projectId: project.id,
+ },
+ forwardedProps: {},
+ }),
+ }),
+ );
+
+ expect(mismatchedResponse.status).toBe(200);
+ const mismatchedStreamInput =
+ agentMocks.createAgUiStream.mock.calls[1][0].input;
+ expect(JSON.parse(mismatchedStreamInput.context[0].value)).toEqual({
+ pathname: `/project/${project.id}/sessions`,
+ searchParams: [{ key: "viewId", value: savedView.id }],
+ hash: "",
+ });
+ } finally {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;
+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY =
+ originalAiFeaturesPublicKey;
+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY =
+ originalAiFeaturesSecretKey;
+ }
+ });
+
+ it("continues without resolved filters when saved view lookup fails", async () => {
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
+ const originalAiFeaturesPublicKey = env.LANGFUSE_AI_FEATURES_PUBLIC_KEY;
+ const originalAiFeaturesSecretKey = env.LANGFUSE_AI_FEATURES_SECRET_KEY;
+
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";
+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY = "pk-lf-test";
+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY = "sk-lf-test";
+
+ const { org, project } = await createOrgProjectAndApiKey();
+ const { project: otherProject } = await createOrgProjectAndApiKey();
+ const otherProjectView = await prisma.tableViewPreset.create({
+ data: {
+ projectId: otherProject.id,
+ name: "Private view",
+ tableName: "traces",
+ createdBy: null,
+ updatedBy: null,
+ filters: [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["private-trace"],
+ },
+ ],
+ columnOrder: [],
+ columnVisibility: {},
+ searchQuery: null,
+ orderBy: Prisma.JsonNull,
+ },
+ });
+ const lookupSpy = vi.spyOn(TableViewService, "getTableViewPresetsById");
+
+ try {
+ await prisma.organization.update({
+ where: { id: org.id },
+ data: { aiFeaturesEnabled: true },
+ });
+ authMocks.getServerSession.mockResolvedValue(
+ await createPersistedInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ }),
+ );
+
+ const { default: handler } =
+ await import("@/src/ee/features/in-app-agent/server/handler");
+
+ const lookupScenarios = [
+ { viewId: otherProjectView.id },
+ { viewId: randomUUID() },
+ { viewId: randomUUID(), error: new Error("database unavailable") },
+ ];
+
+ for (const [index, { viewId, error }] of lookupScenarios.entries()) {
+ if (error) {
+ lookupSpy.mockRejectedValueOnce(error);
+ }
+
+ const response = await handler(
+ new Request("http://localhost/api/in-app-agent", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ threadId: `conversation-${index}`,
+ runId: `client-run-${index}`,
+ messages: [
+ { id: `message-${index}`, role: "user", content: "hello" },
+ ],
+ tools: [],
+ context: [
+ {
+ description: "current_url",
+ value: `https://cloud.langfuse.com/project/${project.id}/traces?viewId=${viewId}`,
+ },
+ ],
+ state: {
+ type: "newConversation",
+ projectId: project.id,
+ },
+ forwardedProps: {},
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ const streamInput =
+ agentMocks.createAgUiStream.mock.calls[index][0].input;
+ expect(JSON.parse(streamInput.context[0].value)).toEqual({
+ pathname: `/project/${project.id}/traces`,
+ searchParams: [{ key: "viewId", value: viewId }],
+ hash: "",
+ });
+ }
+ } finally {
+ lookupSpy.mockRestore();
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;
+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY =
+ originalAiFeaturesPublicKey;
+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY =
+ originalAiFeaturesSecretKey;
+ }
+ });
+
it("drops screen context that is not the current project url", async () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
diff --git a/web/src/ee/features/in-app-agent/context.ts b/web/src/ee/features/in-app-agent/context.ts
index ae31af0611..835fa120bb 100644
--- a/web/src/ee/features/in-app-agent/context.ts
+++ b/web/src/ee/features/in-app-agent/context.ts
@@ -4,6 +4,7 @@ import {
type InAppAgentQuickActionAttribution,
} from "@/src/ee/features/in-app-agent/quickActions";
import { getInAppAgentProjectRoute } from "@/src/ee/features/in-app-agent/routeContext";
+import type { FilterState } from "@langfuse/shared";
type InAppAgentContext = AgUiRunAgentInput["context"];
@@ -167,6 +168,7 @@ export function createInAppAgentScreenContext(params: {
export function sanitizeInAppAgentContext(
context: InAppAgentContext,
projectId: string,
+ viewFilters?: FilterState,
): InAppAgentContext {
const sanitizedContext: InAppAgentContext = [];
const currentUrlContext = context.find(
@@ -181,14 +183,26 @@ export function sanitizeInAppAgentContext(
const serializedCurrentUrl = currentUrl
? JSON.stringify(currentUrl)
: undefined;
+ const serializedResolvedCurrentUrl =
+ currentUrl && viewFilters
+ ? JSON.stringify({
+ ...currentUrl,
+ savedView: { filters: viewFilters },
+ })
+ : undefined;
+ const boundedCurrentUrl =
+ serializedResolvedCurrentUrl &&
+ serializedResolvedCurrentUrl.length <= MAX_SCREEN_CONTEXT_JSON_LENGTH
+ ? serializedResolvedCurrentUrl
+ : serializedCurrentUrl;
if (
- serializedCurrentUrl &&
- serializedCurrentUrl.length <= MAX_SCREEN_CONTEXT_JSON_LENGTH
+ boundedCurrentUrl &&
+ boundedCurrentUrl.length <= MAX_SCREEN_CONTEXT_JSON_LENGTH
) {
sanitizedContext.push({
description: CURRENT_URL_CONTEXT_DESCRIPTION,
- value: serializedCurrentUrl,
+ value: boundedCurrentUrl,
});
}
}
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 512a67f618..9e81204ae3 100644
--- a/web/src/ee/features/in-app-agent/server/handler.ts
+++ b/web/src/ee/features/in-app-agent/server/handler.ts
@@ -64,12 +64,16 @@ import {
import { getLangfuseAITraceSinkParams } from "@/src/features/ai-features/server/bedrockCompletion";
import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
import { getProductBaseUrl } from "@/src/utils/base-url";
+import { parseSavedViewFromURL } from "@/src/utils/product-url";
import { assertUnreachable } from "@/src/utils/types";
import {
BaseError,
ForbiddenError,
+ type FilterState,
InvalidRequestError,
+ LangfuseNotFoundError,
type RateLimitResult,
+ TableViewPresetTableName,
UnauthorizedError,
CloudConfigSchema,
} from "@langfuse/shared";
@@ -77,6 +81,7 @@ import { prisma } from "@langfuse/shared/src/db";
import {
logger,
redis,
+ TableViewService,
type ApiAccessScope,
} from "@langfuse/shared/src/server";
import {
@@ -197,7 +202,11 @@ export default async function handler(request: Request) {
);
}
- const sanitizedInput = sanitizeAgentInput(input, projectId);
+ const sanitizedInput = await prepareAgentInput(
+ input,
+ projectId,
+ user.v4BetaEnabled ?? false,
+ );
const awsProfile = env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE;
const bedrockModelId = env.LANGFUSE_AWS_BEDROCK_MODEL;
const langfuseAiFeaturesPublicKey = env.LANGFUSE_AI_FEATURES_PUBLIC_KEY;
@@ -856,10 +865,11 @@ function isResumeAgentInput(
return "command" in input.forwardedProps;
}
-function sanitizeAgentInput(
+async function prepareAgentInput(
input: AgUiRunAgentInput,
projectId: string,
-): SanitizedAgentInput {
+ isV4Enabled: boolean,
+): Promise<SanitizedAgentInput> {
const forwardedProps: unknown = input.forwardedProps;
if (
@@ -871,6 +881,48 @@ function sanitizeAgentInput(
throw new InvalidRequestError("Invalid forwarded props");
}
+ const currentUrlContext = input.context.find(
+ (item) => item.description === "current_url",
+ );
+ const selectedSavedView = currentUrlContext
+ ? parseSavedViewFromURL(currentUrlContext.value, isV4Enabled)
+ : undefined;
+ let viewFilters: FilterState | undefined;
+
+ if (selectedSavedView) {
+ try {
+ const { filters, tableName } =
+ await TableViewService.getTableViewPresetsById(
+ selectedSavedView.viewId,
+ projectId,
+ );
+
+ if (
+ tableName === selectedSavedView.tableName ||
+ (selectedSavedView.tableName ===
+ TableViewPresetTableName.ObservationsEvents &&
+ tableName === TableViewPresetTableName.Observations)
+ ) {
+ viewFilters = filters;
+ }
+ } catch (error) {
+ // Saved views can be deleted while their URLs remain open or shared.
+ if (!(error instanceof LangfuseNotFoundError)) {
+ logger.warn("Failed to resolve saved view for in-app agent context", {
+ error,
+ projectId,
+ savedViewId: selectedSavedView.viewId,
+ });
+ }
+ }
+ }
+
+ const context = sanitizeInAppAgentContext(
+ input.context,
+ projectId,
+ viewFilters,
+ );
+
if (forwardedProps && "command" in forwardedProps) {
const resumeForwardedProps =
ResumeForwardedPropsSchema.safeParse(forwardedProps);
@@ -886,7 +938,7 @@ function sanitizeAgentInput(
state: null,
messages: [],
tools: [],
- context: sanitizeInAppAgentContext(input.context, projectId),
+ context,
forwardedProps: resumeForwardedProps.data,
};
}
@@ -904,7 +956,7 @@ function sanitizeAgentInput(
state: null,
messages: [{ ...lastUserMessage, id: createInAppAgentMessageId() }],
tools: [],
- context: sanitizeInAppAgentContext(input.context, projectId),
+ context,
forwardedProps: {},
};
}
diff --git a/web/src/utils/product-url.ts b/web/src/utils/product-url.ts
index 5a408391cb..94dfdc5870 100644
--- a/web/src/utils/product-url.ts
+++ b/web/src/utils/product-url.ts
@@ -1,4 +1,8 @@
-import type { APIScoreV3, FilterState } from "@langfuse/shared";
+import {
+ TableViewPresetTableName,
+ type APIScoreV3,
+ type FilterState,
+} from "@langfuse/shared";
import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";
import { getProductBaseUrl } from "@/src/utils/base-url";
import {
@@ -8,6 +12,74 @@ import {
type ProductPathQuery = Record<string, string | string[] | null | undefined>;
+export function parseSavedViewFromURL(
+ currentUrl: string,
+ isV4Enabled: boolean,
+) {
+ let parsedUrl: URL;
+
+ try {
+ parsedUrl = new URL(currentUrl, "https://langfuse.local");
+ } catch {
+ return undefined;
+ }
+
+ const pathSegments = parsedUrl.pathname.split("/").filter(Boolean);
+ const projectSegmentIndex = pathSegments.indexOf("project");
+ const section = pathSegments[projectSegmentIndex + 2];
+ const detailId = pathSegments[projectSegmentIndex + 3];
+ const viewId = parsedUrl.searchParams.get("viewId");
+
+ if (projectSegmentIndex === -1 || !section || !viewId) {
+ return undefined;
+ }
+
+ if (section === "traces" && !detailId) {
+ return {
+ viewId,
+ tableName: isV4Enabled
+ ? TableViewPresetTableName.ObservationsEvents
+ : TableViewPresetTableName.Traces,
+ };
+ }
+
+ if (section === "observations" && !detailId) {
+ return {
+ viewId,
+ tableName: isV4Enabled
+ ? TableViewPresetTableName.ObservationsEvents
+ : TableViewPresetTableName.Observations,
+ };
+ }
+
+ if (section === "sessions") {
+ return {
+ viewId,
+ tableName: detailId
+ ? TableViewPresetTableName.SessionDetail
+ : TableViewPresetTableName.Sessions,
+ };
+ }
+
+ if (section === "datasets" && !detailId) {
+ return { viewId, tableName: TableViewPresetTableName.Datasets };
+ }
+
+ if (section === "scores" && !detailId) {
+ return { viewId, tableName: TableViewPresetTableName.Scores };
+ }
+
+ if (section === "experiments" && detailId === "results") {
+ return { viewId, tableName: TableViewPresetTableName.ExperimentItems };
+ }
+
+ if (section === "experiments" && !detailId) {
+ return { viewId, tableName: TableViewPresetTableName.Experiments };
+ }
+
+ return undefined;
+}
+
type TracesPathTimeRange =
| { preset: (typeof TABLE_AGGREGATION_OPTIONS)[number] }
| { from: string; to: string };