🪢 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(agent): Add redirect tool (#14180)
Ben Bachem22fa28d6ee9e
diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex fc9bb6f29f..1e830ca2d8 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -10,7 +10,7 @@ import {createInAppAgentConversationId,createInAppAgentRunId,} from "@/src/ee/features/in-app-agent/ids";-import type { AgUiEvent } from "@/src/ee/features/in-app-agent/schema";+import { type AgUiEvent } from "@/src/ee/features/in-app-agent/schema";import { inAppAgentRouter } from "@/src/ee/features/in-app-agent/server/router";import {createRun,@@ -22,6 +22,7 @@ import {toPersistableAgentEvent,} from "@/src/ee/features/in-app-agent/server/persistence";import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";describe("in-app agent persistence", () => {const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;@@ -987,6 +988,69 @@ describe("in-app agent persistence", () => {]);});+ it("drops failed redirect tool results before replay", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ const events = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ messageId: "user-1",+ content: "open a trace",+ });+ const process = (event: AgUiEvent) =>+ processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event,+ });++ await process({+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-1",+ role: "assistant",+ });+ await process({+ type: EventType.TOOL_CALL_START,+ toolCallId: "redirect-tool-call",+ toolCallName: IN_APP_AGENT_REDIRECT_TOOL_NAME,+ parentMessageId: "assistant-1",+ });+ await process({+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "redirect-tool-call",+ delta: '{"destination":"trace"}',+ });+ await process({+ type: EventType.TOOL_CALL_END,+ toolCallId: "redirect-tool-call",+ });+ await process({+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-result-1",+ toolCallId: "redirect-tool-call",+ content: "Tool validation failed: trace params are required",+ role: "tool",+ });++ await expect(+ getConversationMessagesForReplay({+ prisma,+ projectId,+ conversationId: conversation.id,+ }),+ ).resolves.toEqual([+ { id: "user-1", role: "user", content: "open a trace" },+ ]);+ });+it("drops empty assistant messages after removing orphan tool calls before replay", async () => {const { projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex ecbaf45ddf..6f3f11c60e 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -4,6 +4,8 @@ import { Agent } from "@mastra/core/agent";import { describe, expect, it, vi } from "vitest";import type { AgUiEvent } from "@/src/ee/features/in-app-agent/schema";+import { decodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";const adapterEvents = vi.hoisted(() => ({items: [] as AgUiEvent[],@@ -200,6 +202,10 @@ describe("createAgUiStream", () => {publicKey: "pk",secretKey: "sk",},+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },langfuseTracing: {environment: "langfuse-in-app-agent",metadata: { langfuse_project_id: "project-1" },@@ -223,6 +229,9 @@ describe("createAgUiStream", () => {server: "langfuseDocs",execute: expect.any(Function),}),+ langfuse_proposeRedirect: expect.objectContaining({+ id: "langfuse_proposeRedirect",+ }),},}),);@@ -233,6 +242,26 @@ describe("createAgUiStream", () => {choices: expect.any(Array),}),});++ const redirectTool = vi.mocked(Agent).mock.calls[0]?.[0]?.tools?.[+ IN_APP_AGENT_REDIRECT_TOOL_NAME+ ] as+ | {+ execute?: (input: unknown) => Promise<unknown>;+ }+ | undefined;++ await expect(+ redirectTool?.execute?.({+ label: "Open trace",+ destination: "trace",+ params: { traceId: "trace-1" },+ }),+ ).resolves.toEqual({+ type: "redirectAction",+ label: "Open trace",+ href: "/project/project-1/traces/trace-1",+ });expect(persistedEvents.map((event) => event.type)).toEqual([EventType.RUN_STARTED,EventType.MESSAGES_SNAPSHOT,@@ -284,6 +313,83 @@ describe("createAgUiStream", () => {expect(instrumentationMocks.instrumentation.flush).toHaveBeenCalled();});+ it("uses V4-compatible filters for traces redirect actions", async () => {+ const { createAgUiStream } =+ await import("@/src/ee/features/in-app-agent/server/agent");+ const input = {+ threadId: "conversation-1",+ runId: "run-1",+ messages: [+ {+ id: "user-message-1",+ role: "user" as const,+ content: "open checkout traces",+ },+ ],+ tools: [],+ context: [],+ state: null,+ forwardedProps: {},+ };+ adapterEvents.items = [];++ const stream = createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ awsBedrock: { modelId: "test-model" },+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ },+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: true,+ },+ },+ });+ await readStream(stream);++ const redirectTool = vi.mocked(Agent).mock.calls[0]?.[0]?.tools?.[+ IN_APP_AGENT_REDIRECT_TOOL_NAME+ ] as+ | {+ execute?: (input: unknown) => Promise<unknown>;+ }+ | undefined;++ const result = await redirectTool?.execute?.({+ label: "Open traces tagged checkout",+ destination: "traces",+ params: {+ filters: {+ tags: ["checkout"],+ sessionId: ["session-1"],+ bookmarked: true,+ },+ },+ });++ expect(result).toMatchObject({+ type: "redirectAction",+ label: "Open traces tagged checkout",+ });+ const href = (result as { href: string }).href;+ const filter = new URL(`https://langfuse.local${href}`).searchParams.get(+ "filter",+ );++ expect(decodeFiltersGeneric(filter ?? "")).toEqual([+ {+ column: "tags",+ operator: "any of",+ type: "arrayOptions",+ value: ["checkout"],+ },+ ]);+ });+it("lets HttpAgent subscribers observe streamed run errors", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");@@ -328,6 +434,10 @@ describe("createAgUiStream", () => {publicKey: "pk",secretKey: "sk",},+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },},});const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsxindex d8f19ce30a..3bbef37725 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx@@ -92,6 +92,21 @@ export const AssistantTextWithLongFeedbackComment = meta.story({},});+export const AssistantTextWithRedirectAction = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "text",+ text: "I found the members settings page for this project.",+ redirectAction: {+ type: "redirectAction",+ label: "Open members",+ href: "/project/project-1/settings/members",+ },+ },+ },+});+export const AssistantMarkdown = meta.story({args: {role: "assistant",@@ -213,6 +228,28 @@ export const SingleToolCallGroup = meta.story({},});+export const RedirectAction = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "redirectAction",+ label: "Open members",+ href: "/project/project-1/settings/members",+ },+ },+});++export const RedirectActionWithParams = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "redirectAction",+ label: "Open error traces",+ href: "/project/project-1/traces?dateRange=1d&search=checkout&searchType=content&filter=level%3BstringOptions%3B%3Bany+of%3BERROR",+ },+ },+});+export const LoadingToolCallGroup = meta.story({args: {role: "assistant",diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsxindex 3e8f7c5b11..626ebb664c 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx@@ -1,6 +1,7 @@"use client";import {+ ArrowRight,Check,Copy,BookOpenText,@@ -10,7 +11,9 @@ import {Wrench,} from "lucide-react";import Link from "next/link";+import { useRouter } from "next/router";import { Streamdown } from "streamdown";+import { Button } from "@/src/components/ui/button";import { getSafeLinkUrl } from "@/src/components/ui/safe-url";import { stripBasePath } from "@/src/utils/redirect";import { cn } from "@/src/utils/tailwind";@@ -41,14 +44,22 @@ import styles from "./InAppAgentMessage.module.css";export type InAppAgentMessageRole = "assistant" | "user";+type InAppAgentRedirectActionContent = {+ type: "redirectAction";+ label: string;+ href: string;+};+export type InAppAgentMessageContent =| { type: "loading"; label?: string }| {type: "text";text: string;feedback?: InAppAgentMessageFeedback;+ redirectAction?: InAppAgentRedirectActionContent;sources?: InAppAgentMessageSource[];}+ | InAppAgentRedirectActionContent| {type: "toolGroup";tools: InAppAgentToolCallContent[];@@ -151,6 +162,10 @@ export function InAppAgentMessage({windowZIndex,onSubmitFeedback,}: InAppAgentMessageProps) {+ if (content.type === "redirectAction") {+ return <RedirectActionButton content={content} isCompact={isCompact} />;+ }+if (content.type === "toolGroup") {return (<div@@ -189,7 +204,10 @@ const MessageCard = forwardRef<HTMLDivElement,{role: InAppAgentMessageRole;- content: Exclude<InAppAgentMessageContent, { type: "toolGroup" }>;+ content: Exclude<+ InAppAgentMessageContent,+ { type: "toolGroup" | "redirectAction" }+ >;isCompact: boolean;}>(function MessageCard({ role, content, isCompact }, ref) {@@ -211,7 +229,17 @@ const MessageCard = forwardRef<{content.type === "loading" ? (<ThinkingIndicator label={content.label} isCompact={isCompact} />) : (- <MessageText role={role} text={content.text} isCompact={isCompact} />+ <>+ <MessageText role={role} text={content.text} isCompact={isCompact} />+ {content.redirectAction ? (+ <div className={cn(isCompact ? "mt-3 mb-1" : "mt-2.5 mb-0.5")}>+ <RedirectActionButton+ content={content.redirectAction}+ isCompact={isCompact}+ />+ </div>+ ) : null}+ </>)}</div>);@@ -561,6 +589,31 @@ function FeedbackButton({);}+function RedirectActionButton({+ content,+ isCompact,+}: {+ content: InAppAgentRedirectActionContent;+ isCompact: boolean;+}) {+ const router = useRouter();++ return (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className={cn("shrink-0", isCompact ? "h-6 px-2 text-xs" : "h-7")}+ onClick={() => {+ router.push(content.href).catch(() => undefined);+ }}+ >+ {content.label}+ <ArrowRight className="ml-1 size-3" />+ </Button>+ );+}+function ToolCallGroup({tools,isLoading = false,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 c8232cd83d..ce676026c0 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@@ -497,6 +497,15 @@ export const Conversation = meta.story({text: "Start by filtering traces by timestamp, then sort by latency. Open the slowest traces to inspect long-running observations.",},},+ {+ id: "assistant-redirect-1",+ role: "assistant",+ content: {+ type: "redirectAction",+ label: "Open slow traces",+ href: "/project/project-1/traces?dateRange=1d&orderBy=column-latency_order-DESC",+ },+ },{id: "user-2",role: "user",diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsxindex 7eb62f2444..8162d38d1f 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx@@ -391,7 +391,10 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {<ol className="flex w-full flex-col gap-3 pb-4">{messages.map((message, index) => {- const hasToolContent = message.content.type === "toolGroup";+ const hasFullWidthContent =+ message.content.type === "toolGroup" ||+ message.content.type === "redirectAction";+const nextUserMessageIndex = messages.findIndex((nextMessage, nextIndex) =>nextIndex > index && nextMessage.role === "user",@@ -415,7 +418,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {key={message.id}className={cn("max-w-[92%]",- hasToolContent ? "w-full" : "w-fit",+ hasFullWidthContent ? "w-full" : "w-fit",message.role === "user" && "ml-auto",)}>diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsxindex ce8b29e70b..5bd3f28e2a 100644--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -140,7 +140,9 @@ function InAppAiAgentProjectProvider({children,projectId,defaultOpen,-}: InAppAiAgentProviderProps & { projectId: string }) {+}: InAppAiAgentProviderProps & {+ projectId: string;+}) {const [open, setOpen] = useSessionStorage<boolean>(`${OPEN_STORAGE_KEY_PREFIX}:${projectId}`,defaultOpen ?? false,@@ -391,7 +393,7 @@ function InAppAiAgentProviderInner({resetAgent();const agent = new HttpAgent({- url: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`,+ url: getInAppAgentUrl(),threadId: conversationId,initialMessages,initialState: getConversationAgentState(@@ -722,6 +724,10 @@ function attachActiveRunIdToAssistantMessages(});}+function getInAppAgentUrl() {+ return `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`;+}+function getAgentErrorMessage(error: unknown): string {if (error && typeof error === "object") {const payload = "payload" in error ? error.payload : undefined;diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.tsindex 475ad2d3b8..9836fc8a12 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts@@ -1,13 +1,18 @@import { z } from "zod";import type { InAppAgentWindowMessage } from "../InAppAgentWindow";-import type { InAppAgentToolCallContent } from "../InAppAgentMessage";+import type {+ InAppAgentMessageContent,+ InAppAgentToolCallContent,+} from "../InAppAgentMessage";import { deduplicateBy } from "@/src/utils/arrays";import {AgUiMessageSchema,type AgUiMessage,type InAppAgentMessageSource,+ InAppAgentRedirectActionToolResultSchema,InAppAgentMessageSourceSchema,} from "@/src/ee/features/in-app-agent/schema";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";const LangfuseDocsDocumentSchema = z.object({type: z.literal("document"),@@ -91,10 +96,44 @@ export function getDrawerMessages({};parsedMessages.forEach((message, index) => {+ if (message.role === "tool") {+ const redirectAction = getRedirectActionFromToolResult(message);++ // Merge redirect actions into the preceding text message when possible for a smoother UI.+ if (redirectAction) {+ const previousRawMessage = parsedMessages[index - 1];+ const previousMessage = mappedMessages[mappedMessages.length - 1];++ if (+ pendingTools.length === 0 &&+ previousRawMessage?.role === "assistant" &&+ previousMessage?.role === "assistant" &&+ previousMessage.id === previousRawMessage.id &&+ previousMessage.content.type === "text"+ ) {+ mappedMessages[mappedMessages.length - 1] = {+ ...previousMessage,+ content: {+ ...previousMessage.content,+ redirectAction,+ },+ };+ } else {+ flushPendingTools();+ mappedMessages.push({+ id: `${message.id}-redirect`,+ role: "assistant",+ content: redirectAction,+ });+ }+ }++ return;+ }+if (message.role === "system" ||message.role === "developer" ||- message.role === "tool" ||message.role === "activity") {return;@@ -134,19 +173,29 @@ export function getDrawerMessages({const toolContent =message.role === "assistant"- ? (message.toolCalls?.map((toolCall): InAppAgentToolCallContent => {- const result = toolResults.get(toolCall.id);-- return {- type: "tool",- name: toolCall.function.name,- args: toolCall.function.arguments,- ...(result?.content !== undefined- ? { result: result.content }- : {}),- ...(result?.error !== undefined ? { error: result.error } : {}),- };- }) ?? [])+ ? (message.toolCalls?.flatMap(+ (toolCall): InAppAgentToolCallContent[] => {+ if (toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME) {+ return [];+ }++ const result = toolResults.get(toolCall.id);++ return [+ {+ type: "tool",+ name: toolCall.function.name,+ args: toolCall.function.arguments,+ ...(result?.content !== undefined+ ? { result: result.content }+ : {}),+ ...(result?.error !== undefined+ ? { error: result.error }+ : {}),+ },+ ];+ },+ ) ?? []): [];const docsSources = extractLangfuseDocsSources(toolContent);@@ -224,7 +273,8 @@ export function getDrawerMessages({!error &&latestUserMessageIndex >= 0 &&latestAssistantMessage?.content.type !== "text" &&- latestAssistantMessage?.content.type !== "loading"+ latestAssistantMessage?.content.type !== "loading" &&+ latestAssistantMessage?.content.type !== "redirectAction") {if (latestAssistantMessage?.content.type === "toolGroup") {return mappedMessages.map((message, index) =>@@ -269,6 +319,18 @@ function getToolResultsByToolCallId(messages: readonly AgUiMessage[]) {return results;}+function getRedirectActionFromToolResult(+ message: Extract<AgUiMessage, { role: "tool" }>,+): Extract<InAppAgentMessageContent, { type: "redirectAction" }> | null {+ try {+ return InAppAgentRedirectActionToolResultSchema.parse(+ JSON.parse(message.content),+ );+ } catch {+ return null;+ }+}+export function extractLangfuseDocsSources(tools: readonly InAppAgentToolCallContent[],): InAppAgentMessageSource[] {diff --git a/web/src/ee/features/in-app-agent/constants.ts b/web/src/ee/features/in-app-agent/constants.tsnew file mode 100644index 0000000000..03bc3be9d7--- /dev/null+++ b/web/src/ee/features/in-app-agent/constants.ts@@ -0,0 +1,2 @@+// Avoid renaming this as the FE is aware of this when rendering, renaming it would cause history issues+export const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";diff --git a/web/src/ee/features/in-app-agent/schema.ts b/web/src/ee/features/in-app-agent/schema.tsindex 4f851f043e..5b4ebd1a05 100644--- a/web/src/ee/features/in-app-agent/schema.ts+++ b/web/src/ee/features/in-app-agent/schema.ts@@ -47,6 +47,13 @@ export type InAppAgentMessageFeedback = z.infer<typeof InAppAgentMessageFeedbackSchema>;+// Changes to this schema need to be backwards-compatible as messages with this are already persisted.+export const InAppAgentRedirectActionToolResultSchema = z.object({+ type: z.literal("redirectAction"),+ label: z.string().min(1).max(80),+ href: z.string().min(1),+});+const AgUiInputContentSourceSchema = z.discriminatedUnion("type", [z.object({type: z.literal("data"),diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.tsindex 5b932ed6c6..1fdbf17c9b 100644--- a/web/src/ee/features/in-app-agent/server/agent.ts+++ b/web/src/ee/features/in-app-agent/server/agent.ts@@ -5,13 +5,15 @@ import { fromNodeProviderChain } from "@aws-sdk/credential-providers";import { Agent } from "@mastra/core/agent";import { MCPClient } from "@mastra/mcp";-import type {- AgUiEvent,- AgUiRunAgentInput,+import {+ type AgUiEvent,+ type AgUiRunAgentInput,} from "@/src/ee/features/in-app-agent/schema";import type { InAppAgentTracingConfig } from "@/src/ee/features/in-app-agent/server/instrumentation";import { createInAppAgentInstrumentation } from "@/src/ee/features/in-app-agent/server/instrumentation";+import { createRedirectActionTool } from "@/src/ee/features/in-app-agent/server/tools";import { logger } from "@langfuse/shared/src/server";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";const ASSISTANT_TITLE = "Langfuse Assistant";const getAssistantSystemPrompt = (@@ -53,6 +55,14 @@ If the user asks you to perform an action, you have two options:- If the action is available via the CLI, suggest that the user can ask their own agent (Claude, Codex or similar) to perform the action for them using the CLI, for that they should use the Langfuse skill: https://github.com/langfuse/skills. When suggesting this, provide a prompt the user can use as a code block.</permissions>+<user_navigation>+When a relevant Langfuse page would help the user, answer the question normally and call ${IN_APP_AGENT_REDIRECT_TOOL_NAME} to propose opening that page.+The tool call should be the last thing in your response before ending your turn, and should not be mentioned in the text of your response.+Use the redirect proposal only for known in-app destinations from the tool schema. Never invent URLs or ask the user to paste links.+When the user asks for a trace view with specific state, use the typed trace params for time ranges, search, filters, and ordering instead of describing URL query parameters.+Use a short action label, for example "Open members" or "Open traces".+</user_navigation>+<world_knowledge>The current time is ${new Date().toDateString()}.</world_knowledge>@@ -94,6 +104,10 @@ type CreateAgUiStreamOptions = {publicKey: string;secretKey: string;};+ redirectAction: {+ projectId: string;+ isV4Enabled: boolean;+ };langfuseTracing?: InAppAgentTracingConfig;};@@ -545,6 +559,10 @@ async function createMastraAdapter(params: {const tools = {...prefixToolsetTools("langfuse", toolsets.langfuse),...prefixToolsetTools("langfuseDocs", toolsets.langfuseDocs),+ [IN_APP_AGENT_REDIRECT_TOOL_NAME]: createRedirectActionTool({+ projectId: params.options.redirectAction.projectId,+ isV4Enabled: params.options.redirectAction.isV4Enabled,+ }),};const agent = new Agent({diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex 75b021e659..5ac40fc5ad 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -320,6 +320,10 @@ export default async function handler(request: Request) {publicKey: mcpApiKey.publicKey,secretKey: mcpApiKey.secretKey,},+ redirectAction: {+ projectId,+ isV4Enabled: session.user?.v4BetaEnabled ?? false,+ },langfuseTracing:project.organization.aiTelemetryEnabled && targetProjectId? {diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.tsindex e162792df6..02ea6b663a 100644--- a/web/src/ee/features/in-app-agent/server/persistence.ts+++ b/web/src/ee/features/in-app-agent/server/persistence.ts@@ -11,10 +11,12 @@ import type {import {AgUiMessageSchema,+ InAppAgentRedirectActionToolResultSchema,type AgUiEvent,type AgUiMessage,} from "@/src/ee/features/in-app-agent/schema";import { compactTextMessageChunks } from "@/src/ee/features/in-app-agent/server/eventCompaction";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";// Keep this close to the route maxDuration (120s) so a killed foreground stream// does not block the conversation long after the route can no longer respond.@@ -326,8 +328,11 @@ function getMessagesFromPersistedEvents(function sanitizeConversationMessagesForReplay(messages: readonly AgUiMessage[],): readonly AgUiMessage[] {- const messagesWithoutOrphanToolCalls =- dropUnpairedAssistantToolCalls(messages);+ const messagesWithoutRedirectActions =+ dropRedirectActionToolResults(messages);+ const messagesWithoutOrphanToolCalls = dropUnpairedAssistantToolCalls(+ messagesWithoutRedirectActions,+ );return stripAssistantRunIds(dropEmptyAssistantMessages(messagesWithoutOrphanToolCalls),);@@ -740,7 +745,56 @@ function mergeMessages(existing: AgUiMessage, next: AgUiMessage): AgUiMessage {}function compactPersistedEvents(events: readonly AgUiEvent[]): AgUiEvent[] {- return compactEvents(compactTextMessageChunks(events)) as AgUiEvent[];+ return dropRedirectToolCallEvents(+ compactEvents(compactTextMessageChunks(events)) as AgUiEvent[],+ );+}++// Redirect actions are rendered from the server-generated href payload. Drop the+// redirect tool call scaffolding and args so persisted history does not depend+// on the redirect input schema, which may evolve over time.+function dropRedirectToolCallEvents(events: readonly AgUiEvent[]): AgUiEvent[] {+ const redirectToolCallIds = new Set<string>();++ for (const event of events) {+ if (+ event.type === EventType.TOOL_CALL_START &&+ getString(event, "toolCallName") === IN_APP_AGENT_REDIRECT_TOOL_NAME+ ) {+ const toolCallId = getString(event, "toolCallId");+ if (toolCallId) {+ redirectToolCallIds.add(toolCallId);+ }+ }++ if (event.type === EventType.TOOL_CALL_RESULT) {+ const toolCallId = getString(event, "toolCallId");+ if (+ toolCallId &&+ isRedirectActionToolResult(getString(event, "content"))+ ) {+ redirectToolCallIds.add(toolCallId);+ }+ }+ }++ if (redirectToolCallIds.size === 0) {+ return [...events];+ }++ return events.filter((event) => {+ if (+ event.type !== EventType.TOOL_CALL_START &&+ event.type !== EventType.TOOL_CALL_ARGS &&+ event.type !== EventType.TOOL_CALL_END &&+ event.type !== EventType.TOOL_CALL_RESULT+ ) {+ return true;+ }++ const toolCallId = getString(event, "toolCallId");+ return !toolCallId || !redirectToolCallIds.has(toolCallId);+ });}function dropUnpairedAssistantToolCalls(messages: readonly AgUiMessage[]) {@@ -778,6 +832,19 @@ function dropUnpairedAssistantToolCalls(messages: readonly AgUiMessage[]) {return changed ? sanitizedMessages : messages;}+function dropRedirectActionToolResults(messages: readonly AgUiMessage[]) {+ let changed = false;+ const sanitizedMessages = messages.filter((message) => {+ const keep =+ message.role !== "tool" || !isRedirectActionToolResult(message.content);++ changed = changed || !keep;+ return keep;+ });++ return changed ? sanitizedMessages : messages;+}+function dropEmptyAssistantMessages(messages: readonly AgUiMessage[]) {let changed = false;const sanitizedMessages = messages.filter((message) => {@@ -838,6 +905,20 @@ function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);}+function isRedirectActionToolResult(content: string | undefined) {+ if (!content) {+ return false;+ }++ try {+ return InAppAgentRedirectActionToolResultSchema.safeParse(+ JSON.parse(content),+ ).success;+ } catch {+ return false;+ }+}+function compactObject<T extends Record<string, unknown>>(value: T): T {return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined),diff --git a/web/src/ee/features/in-app-agent/server/tools.ts b/web/src/ee/features/in-app-agent/server/tools.tsnew file mode 100644index 0000000000..ce5262f2a1--- /dev/null+++ b/web/src/ee/features/in-app-agent/server/tools.ts@@ -0,0 +1,340 @@+import { createTool } from "@mastra/core/tools";+import { assertUnreachable } from "@/src/utils/types";+import {+ buildDashboardsPath,+ buildDatasetsPath,+ buildEvalsPath,+ buildExperimentsPath,+ buildModelsPath,+ buildMonitorsPath,+ buildPlaygroundPath,+ buildProjectMembersPath,+ buildProjectSettingsPath,+ buildPromptsPath,+ buildScoresPath,+ buildSessionPath,+ buildSessionsPath,+ buildTracePath,+ buildTracesPath,+} from "@/src/utils/product-url";+import z from "zod";+import { TABLE_AGGREGATION_OPTIONS } from "@/src/utils/date-range-utils";+import { ObservationLevelDomain, TracingSearchType } from "@langfuse/shared";+import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";++const InAppAgentRedirectDestinationSchema = z.enum([+ "dashboards",+ "datasets",+ "evals",+ "experiments",+ "models",+ "monitors",+ "playground",+ "projectMembers",+ "projectSettings",+ "prompts",+ "scores",+ "session",+ "sessions",+ "trace",+ "traces",+]);++const InAppAgentRedirectBaseSchema = z.object({+ label: z.string().min(1).max(80),+});++const InAppAgentTableTimeRangePresetSchema = z.enum(TABLE_AGGREGATION_OPTIONS);++const InAppAgentTableTimeRangeStrictSchema = z.union([+ z.object({+ preset: InAppAgentTableTimeRangePresetSchema,+ }),+ z.object({+ from: z.iso.datetime(),+ to: z.iso.datetime(),+ }),+]);++const InAppAgentTableTimeRangeSchema = z+ .object({+ preset: InAppAgentTableTimeRangePresetSchema.optional(),+ from: z.iso.datetime().optional(),+ to: z.iso.datetime().optional(),+ })+ .superRefine((value, ctx) => {+ if (!InAppAgentTableTimeRangeStrictSchema.safeParse(value).success) {+ ctx.addIssue({+ code: "custom",+ message: "Provide either a preset or both from and to.",+ });+ }+ }) as z.ZodType<z.infer<typeof InAppAgentTableTimeRangeStrictSchema>>;++const InAppAgentTracingFiltersSchema = z.object({+ bookmarked: z.boolean().optional(),+ environment: z.array(z.string().min(1).max(100)).max(10).optional(),+ level: z.array(ObservationLevelDomain).max(4).optional(),+ metadata: z+ .array(+ z.object({+ key: z.string().min(1).max(100),+ value: z.string().max(200),+ }),+ )+ .max(5)+ .optional(),+ sessionId: z.array(z.string().min(1).max(200)).max(10).optional(),+ tags: z.array(z.string().min(1).max(100)).max(10).optional(),+ traceId: z.string().min(1).max(200).optional(),+ traceName: z.array(z.string().min(1).max(200)).max(10).optional(),+ userId: z.array(z.string().min(1).max(200)).max(10).optional(),+ version: z.string().min(1).max(200).optional(),+});++const InAppAgentTracesParamsSchema = z.object({+ filters: InAppAgentTracingFiltersSchema.optional(),+ orderBy: z+ .object({+ column: z.enum(["timestamp", "startTime", "traceName", "latency"]),+ order: z.enum(["ASC", "DESC"]),+ })+ .optional(),+ search: z+ .object({+ query: z.string().min(1).max(300),+ type: z.array(TracingSearchType).max(4).optional(),+ })+ .optional(),+ timeRange: InAppAgentTableTimeRangeSchema.optional(),+});++const InAppAgentProjectSettingsPageSchema = z.enum([+ "index",+ "api-keys",+ "developer-tools",+ "llm-connections",+ "models",+ "scores",+ "members",+ "integrations",+ "exports",+ "batch-actions",+ "audit-logs",+ "notifications",+]);++const InAppAgentRedirectToolInputStrictSchema = z.discriminatedUnion(+ "destination",+ [+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("dashboards"),+ }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("datasets"),+ params: z+ .object({ folder: z.string().min(1).max(200).optional() })+ .optional(),+ }),+ InAppAgentRedirectBaseSchema.extend({ destination: z.literal("evals") }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("experiments"),+ }),+ InAppAgentRedirectBaseSchema.extend({ destination: z.literal("models") }),+ InAppAgentRedirectBaseSchema.extend({ destination: z.literal("monitors") }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("playground"),+ }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("projectMembers"),+ }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("projectSettings"),+ params: z+ .object({ page: InAppAgentProjectSettingsPageSchema.optional() })+ .optional(),+ }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("prompts"),+ params: z+ .object({ folder: z.string().min(1).max(200).optional() })+ .optional(),+ }),+ InAppAgentRedirectBaseSchema.extend({ destination: z.literal("scores") }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("session"),+ params: z.object({ sessionId: z.string().min(1).max(200) }),+ }),+ InAppAgentRedirectBaseSchema.extend({ destination: z.literal("sessions") }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("trace"),+ params: z.object({+ timestamp: z.iso.datetime().optional(),+ traceId: z.string().min(1).max(200),+ }),+ }),+ InAppAgentRedirectBaseSchema.extend({+ destination: z.literal("traces"),+ params: InAppAgentTracesParamsSchema.optional(),+ }),+ ],+);++const InAppAgentRedirectParamsSchema = z.object({+ folder: z.string().min(1).max(200).optional(),+ page: InAppAgentProjectSettingsPageSchema.optional(),+ sessionId: z.string().min(1).max(200).optional(),+ timestamp: z.iso.datetime().optional(),+ traceId: z.string().min(1).max(200).optional(),+ filters: InAppAgentTracingFiltersSchema.optional(),+ orderBy: InAppAgentTracesParamsSchema.shape.orderBy,+ search: InAppAgentTracesParamsSchema.shape.search,+ timeRange: InAppAgentTableTimeRangeSchema.optional(),+});++const InAppAgentRedirectToolInputSchema = InAppAgentRedirectBaseSchema.extend({+ destination: InAppAgentRedirectDestinationSchema,+ params: InAppAgentRedirectParamsSchema.optional(),+}).superRefine((value, ctx) => {+ const result = InAppAgentRedirectToolInputStrictSchema.safeParse(value);++ if (!result.success) {+ ctx.addIssue({+ code: "custom",+ message: "Invalid redirect destination parameters.",+ });+ }+}) as z.ZodType<z.infer<typeof InAppAgentRedirectToolInputStrictSchema>>;++type InAppAgentRedirectToolInput = z.infer<+ typeof InAppAgentRedirectToolInputStrictSchema+>;++export function createRedirectActionTool({+ projectId,+ isV4Enabled,+}: {+ projectId: string;+ isV4Enabled: boolean;+}) {+ return createTool({+ id: IN_APP_AGENT_REDIRECT_TOOL_NAME,+ description:+ "Propose a user-confirmed navigation action to a known Langfuse page. This does not navigate automatically.",+ inputSchema: InAppAgentRedirectToolInputSchema,+ execute: async (input) => {+ return getRedirectActionToolResult({+ input,+ projectId,+ isV4Enabled,+ });+ },+ });+}++function getRedirectActionToolResult({+ input,+ projectId,+ isV4Enabled,+}: {+ input: unknown;+ projectId: string;+ isV4Enabled: boolean;+}) {+ const parsedInput = InAppAgentRedirectToolInputSchema.parse(input);+ const href = getRedirectHref(parsedInput, projectId, isV4Enabled);++ return {+ type: "redirectAction" as const,+ label: parsedInput.label,+ href,+ };+}++function getRedirectHref(+ input: InAppAgentRedirectToolInput,+ projectId: string,+ isV4Enabled: boolean,+): string {+ if (input.destination === "dashboards") {+ return buildDashboardsPath({ projectId });+ }++ if (input.destination === "datasets") {+ return buildDatasetsPath({+ projectId,+ folder: input.params?.folder,+ });+ }++ if (input.destination === "evals") {+ return buildEvalsPath({ projectId });+ }++ if (input.destination === "experiments") {+ return buildExperimentsPath({ projectId });+ }++ if (input.destination === "models") {+ return buildModelsPath({ projectId });+ }++ if (input.destination === "monitors") {+ return buildMonitorsPath({ projectId });+ }++ if (input.destination === "playground") {+ return buildPlaygroundPath({ projectId });+ }++ if (input.destination === "projectMembers") {+ return buildProjectMembersPath({ projectId });+ }++ if (input.destination === "projectSettings") {+ return buildProjectSettingsPath({+ projectId,+ page: input.params?.page,+ });+ }++ if (input.destination === "prompts") {+ return buildPromptsPath({+ projectId,+ folder: input.params?.folder,+ });+ }++ if (input.destination === "scores") {+ return buildScoresPath({ projectId });+ }++ if (input.destination === "session") {+ return buildSessionPath({+ projectId,+ sessionId: input.params.sessionId,+ });+ }++ if (input.destination === "sessions") {+ return buildSessionsPath({ projectId });+ }++ if (input.destination === "trace") {+ return buildTracePath({+ projectId,+ traceId: input.params.traceId,+ timestamp: input.params.timestamp,+ });+ }++ if (input.destination === "traces") {+ return buildTracesPath({+ projectId,+ isV4Enabled,+ params: input.params,+ });+ }++ return assertUnreachable(input);+}diff --git a/web/src/features/filters/lib/filter-query-encoding.ts b/web/src/features/filters/lib/filter-query-encoding.tsindex 35deafc7bd..2d81f9ed37 100644--- a/web/src/features/filters/lib/filter-query-encoding.ts+++ b/web/src/features/filters/lib/filter-query-encoding.ts@@ -3,9 +3,22 @@ import {singleFilter,type SingleValueOption,} from "@langfuse/shared";-import { encodeDelimitedArray, decodeDelimitedArray } from "use-query-params";import { normalizeLegacySessionPositionInTraceKey } from "@/src/components/session/session-position-in-trace";+const encodeDelimitedArray = (values: string[], delimiter: string): string =>+ values.join(delimiter);++const decodeDelimitedArray = (+ value: string,+ delimiter: string,+): string[] | undefined => {+ if (value === "") {+ return [];+ }++ return value.split(delimiter);+};+// Escape pipe characters in values to avoid conflicts with the delimiter// Uses backslash escaping: | → \|, and \ → \\export function escapePipeInValue(value: string): string {diff --git a/web/src/utils/product-url.ts b/web/src/utils/product-url.tsindex 7736655aea..fe899f14fa 100644--- a/web/src/utils/product-url.ts+++ b/web/src/utils/product-url.ts@@ -1,7 +1,47 @@+import type { FilterState } from "@langfuse/shared";import { env } from "@/src/env.mjs";+import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";+import {+ rangeToString,+ type TABLE_AGGREGATION_OPTIONS,+} from "@/src/utils/date-range-utils";const LOCALHOST_HOST_PATTERN = /^(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i;+type ProductPathQuery = Record<string, string | string[] | null | undefined>;++type TracesPathTimeRange =+ | { preset: (typeof TABLE_AGGREGATION_OPTIONS)[number] }+ | { from: string; to: string };++type TracesPathFilters = {+ bookmarked?: boolean;+ environment?: string[];+ level?: string[];+ metadata?: Array<{ key: string; value: string }>;+ sessionId?: string[];+ tags?: string[];+ traceId?: string;+ traceName?: string[];+ userId?: string[];+ version?: string;+};++type TracesPathOrderBy = {+ column: "timestamp" | "startTime" | "traceName" | "latency";+ order: "ASC" | "DESC";+};++type TracesPathParams = {+ filters?: TracesPathFilters;+ orderBy?: TracesPathOrderBy;+ search?: {+ query: string;+ type?: string[];+ };+ timeRange?: TracesPathTimeRange;+};+const getProductBaseUrl = () => {const rawBaseUrl = env.NEXTAUTH_URL;const baseUrl = new URL(@@ -17,40 +57,304 @@ const getProductBaseUrl = () => {return baseUrl;};-const buildProductUrl = (path: string, query?: Record<string, string>) => {+export const appendProductPathQuery = (+ path: string,+ query: ProductPathQuery,+): string => {+ const searchParams = new URLSearchParams();++ Object.entries(query).forEach(([key, value]) => {+ if (!value) {+ return;+ }++ if (Array.isArray(value)) {+ value.forEach((item) => {+ if (item) {+ searchParams.append(key, item);+ }+ });+ } else {+ searchParams.set(key, value);+ }+ });++ const queryString = searchParams.toString();++ return queryString ? `${path}?${queryString}` : path;+};++const buildProductUrl = (path: string, query?: ProductPathQuery) => {const baseUrl = getProductBaseUrl();const basePath = baseUrl.pathname.replace(/\/$/, "");const url = new URL(`${basePath}${path}`, baseUrl);for (const [key, value] of Object.entries(query ?? {})) {- url.searchParams.set(key, value);+ if (!value) {+ continue;+ }++ if (Array.isArray(value)) {+ value.forEach((item) => {+ if (item) {+ url.searchParams.append(key, item);+ }+ });+ } else {+ url.searchParams.set(key, value);+ }}return url.toString();};-export const buildTraceUrl = (params: { projectId: string; traceId: string }) =>- buildProductUrl(- `/project/${encodeURIComponent(params.projectId)}/traces/${encodeURIComponent(params.traceId)}`,+export const buildProjectPath = (params: { projectId: string }) =>+ `/project/${encodeURIComponent(params.projectId)}`;++export const buildDashboardsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/dashboards`;++export const buildDatasetsPath = (params: {+ projectId: string;+ folder?: string;+}) =>+ appendProductPathQuery(`${buildProjectPath(params)}/datasets`, {+ folder: params.folder,+ });++export const buildEvalsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/evals`;++export const buildExperimentsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/experiments`;++export const buildModelsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/models`;++export const buildMonitorsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/monitors`;++export const buildPlaygroundPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/playground`;++export const buildProjectMembersPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/settings/members`;++export const buildProjectSettingsPath = (params: {+ projectId: string;+ page?: string;+}) =>+ params.page && params.page !== "index"+ ? `${buildProjectPath(params)}/settings/${params.page}`+ : `${buildProjectPath(params)}/settings`;++export const buildPromptsPath = (params: {+ projectId: string;+ folder?: string;+}) =>+ appendProductPathQuery(`${buildProjectPath(params)}/prompts`, {+ folder: params.folder,+ });++export const buildScoresPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/scores`;++export const buildTracePath = (params: {+ projectId: string;+ traceId: string;+ timestamp?: string;+}) =>+ appendProductPathQuery(+ `${buildProjectPath(params)}/traces/${encodeURIComponent(params.traceId)}`,+ { timestamp: params.timestamp },+ );++export const buildTracesPath = (params: {+ projectId: string;+ isV4Enabled?: boolean;+ params?: TracesPathParams;+ query?: ProductPathQuery;+}) =>+ appendProductPathQuery(+ `${buildProjectPath(params)}/traces`,+ params.params+ ? {+ ...getTracesPathQuery(params.params, Boolean(params.isV4Enabled)),+ ...params.query,+ }+ : (params.query ?? {}),);+function getTracesPathQuery(+ params: TracesPathParams,+ isV4Enabled: boolean,+): ProductPathQuery {+ const filters = params.filters+ ? getTracesFilterState(params.filters, isV4Enabled)+ : [];+ const orderBy = params.orderBy+ ? normalizeTracesOrderBy(params.orderBy, isV4Enabled)+ : undefined;++ return {+ dateRange: params.timeRange+ ? getDateRangeQueryValue(params.timeRange)+ : undefined,+ filter: filters.length > 0 ? encodeFiltersGeneric(filters) : undefined,+ orderBy: orderBy+ ? `column-${orderBy.column}_order-${orderBy.order}`+ : undefined,+ search: params.search?.query,+ searchType: params.search?.type,+ };+}++function getDateRangeQueryValue(timeRange: TracesPathTimeRange) {+ if ("preset" in timeRange) {+ return rangeToString({ range: timeRange.preset });+ }++ return rangeToString({+ from: new Date(timeRange.from),+ to: new Date(timeRange.to),+ });+}++function getTracesFilterState(+ filters: TracesPathFilters,+ isV4Enabled: boolean,+): FilterState {+ const filterState: FilterState = [];++ const addStringOptionsFilter = (+ column: string,+ value: string[] | undefined,+ ) => {+ if (!value || value.length === 0) {+ return;+ }++ filterState.push({+ column,+ operator: "any of",+ type: "stringOptions",+ value,+ });+ };++ const addArrayOptionsFilter = (+ column: string,+ value: string[] | undefined,+ ) => {+ if (!value || value.length === 0) {+ return;+ }++ filterState.push({+ column,+ operator: "any of",+ type: "arrayOptions",+ value,+ });+ };++ addStringOptionsFilter("environment", filters.environment);+ addStringOptionsFilter("level", filters.level);+ if (!isV4Enabled) {+ addStringOptionsFilter("sessionId", filters.sessionId);+ }+ addStringOptionsFilter("traceName", filters.traceName);+ addStringOptionsFilter("userId", filters.userId);+ addArrayOptionsFilter(isV4Enabled ? "tags" : "traceTags", filters.tags);++ if (!isV4Enabled && filters.bookmarked !== undefined) {+ filterState.push({+ column: "bookmarked",+ operator: "=",+ type: "boolean",+ value: filters.bookmarked,+ });+ }++ if (filters.traceId) {+ filterState.push({+ column: isV4Enabled ? "traceId" : "id",+ operator: "=",+ type: "string",+ value: filters.traceId,+ });+ }++ if (filters.version) {+ if (isV4Enabled) {+ filterState.push({+ column: "version",+ operator: "any of",+ type: "stringOptions",+ value: [filters.version],+ });+ } else {+ filterState.push({+ column: "version",+ operator: "=",+ type: "string",+ value: filters.version,+ });+ }+ }++ for (const metadataFilter of filters.metadata ?? []) {+ filterState.push({+ column: "metadata",+ key: metadataFilter.key,+ operator: "=",+ type: "stringObject",+ value: metadataFilter.value,+ });+ }++ return filterState;+}++function normalizeTracesOrderBy(+ orderBy: TracesPathOrderBy,+ isV4Enabled: boolean,+) {+ if (orderBy.column === "timestamp" || orderBy.column === "startTime") {+ return {+ column: isV4Enabled ? "startTime" : "timestamp",+ order: orderBy.order,+ };+ }++ return orderBy;+}++export const buildSessionPath = (params: {+ projectId: string;+ sessionId: string;+}) =>+ `${buildProjectPath(params)}/sessions/${encodeURIComponent(params.sessionId)}`;++export const buildSessionsPath = (params: { projectId: string }) =>+ `${buildProjectPath(params)}/sessions`;++export const buildTraceUrl = (params: { projectId: string; traceId: string }) =>+ buildProductUrl(buildTracePath(params));+export const buildObservationUrl = (params: {projectId: string;traceId: string;observationId: string;}) =>- buildProductUrl(- `/project/${encodeURIComponent(params.projectId)}/traces/${encodeURIComponent(params.traceId)}`,- { observation: params.observationId },- );+ buildProductUrl(buildTracePath(params), {+ observation: params.observationId,+ });export const buildSessionUrl = (params: {projectId: string;sessionId: string;-}) =>- buildProductUrl(- `/project/${encodeURIComponent(params.projectId)}/sessions/${encodeURIComponent(params.sessionId)}`,- );+}) => buildProductUrl(buildSessionPath(params));export const buildCommentObjectUrl = (params: {projectId: string;