🪢 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): persist and restore agent sessions (#13720)
Nimarbcdfe596dc24
diff --git a/packages/shared/prisma/migrations/20260601190000_add_in_app_agent_persistence/migration.sql b/packages/shared/prisma/migrations/20260601190000_add_in_app_agent_persistence/migration.sqlnew file mode 100644index 0000000000..730c03613b--- /dev/null+++ b/packages/shared/prisma/migrations/20260601190000_add_in_app_agent_persistence/migration.sql@@ -0,0 +1,58 @@+CREATE TYPE "InAppAgentConversationVisibilityScope" AS ENUM ('PERSONAL', 'PROJECT');++CREATE TABLE "in_app_agent_conversations" (+ "id" TEXT NOT NULL,+ "project_id" TEXT NOT NULL,+ "created_by_user_id" TEXT,+ "title" TEXT,+ "visibility_scope" "InAppAgentConversationVisibilityScope" NOT NULL DEFAULT 'PERSONAL',+ "provider_session_id" TEXT,+ "deleted_at" TIMESTAMP(3),+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "in_app_agent_conversations_pkey" PRIMARY KEY ("id", "project_id")+);++CREATE TABLE "in_app_agent_runs" (+ "id" TEXT NOT NULL,+ "project_id" TEXT NOT NULL,+ "conversation_id" TEXT NOT NULL,+ "triggered_by_user_id" TEXT,+ "model" TEXT,+ "mcp_api_key_id" TEXT,+ "error_code" TEXT,+ "error_message" TEXT,+ "finished_at" TIMESTAMP(3),+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "in_app_agent_runs_pkey" PRIMARY KEY ("id", "project_id")+);++CREATE TABLE "in_app_agent_events" (+ "project_id" TEXT NOT NULL,+ "conversation_id" TEXT NOT NULL,+ "run_id" TEXT NOT NULL,+ "sequence_number" INTEGER NOT NULL,+ "type" TEXT NOT NULL,+ "event" JSONB NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "in_app_agent_events_pkey" PRIMARY KEY ("project_id", "conversation_id", "sequence_number")+);++CREATE INDEX "in_app_agent_conversations_project_user_list_idx" ON "in_app_agent_conversations"("project_id", "created_by_user_id", "deleted_at", "updated_at", "id");+CREATE INDEX "in_app_agent_events_project_run_idx" ON "in_app_agent_events"("project_id", "run_id");+CREATE INDEX "in_app_agent_runs_project_conversation_created_idx" ON "in_app_agent_runs"("project_id", "conversation_id", "created_at");++ALTER TABLE "in_app_agent_conversations" ADD CONSTRAINT "in_app_agent_conversations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "in_app_agent_conversations" ADD CONSTRAINT "in_app_agent_conversations_created_by_user_id_fkey" FOREIGN KEY ("created_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++ALTER TABLE "in_app_agent_runs" ADD CONSTRAINT "in_app_agent_runs_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "in_app_agent_runs" ADD CONSTRAINT "in_app_agent_runs_conversation_id_project_id_fkey" FOREIGN KEY ("conversation_id", "project_id") REFERENCES "in_app_agent_conversations"("id", "project_id") ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "in_app_agent_runs" ADD CONSTRAINT "in_app_agent_runs_triggered_by_user_id_fkey" FOREIGN KEY ("triggered_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++ALTER TABLE "in_app_agent_events" ADD CONSTRAINT "in_app_agent_events_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "in_app_agent_events" ADD CONSTRAINT "in_app_agent_events_conversation_id_project_id_fkey" FOREIGN KEY ("conversation_id", "project_id") REFERENCES "in_app_agent_conversations"("id", "project_id") ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "in_app_agent_events" ADD CONSTRAINT "in_app_agent_events_run_id_project_id_fkey" FOREIGN KEY ("run_id", "project_id") REFERENCES "in_app_agent_runs"("id", "project_id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 16caf305cb..33b990ded7 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -77,6 +77,8 @@ model User {commentReactions CommentReaction[]notificationPreferences NotificationPreference[]defaultViews DefaultView[] @relation("DefaultViewUser")+ inAppAgentConversations InAppAgentConversation[] @relation("InAppAgentConversationCreatedByUser")+ inAppAgentRuns InAppAgentRun[] @relation("InAppAgentRunTriggeredByUser")@@map("users")}@@ -171,6 +173,9 @@ model Project {AnnotationQueueAssignment AnnotationQueueAssignment[]NotificationPreference NotificationPreference[]DefaultView DefaultView[]+ InAppAgentConversation InAppAgentConversation[]+ InAppAgentEvent InAppAgentEvent[]+ InAppAgentRun InAppAgentRun[]@@index([orgId])@@map("projects")@@ -206,6 +211,72 @@ model ApiKey {@@map("api_keys")}+enum InAppAgentConversationVisibilityScope {+ PERSONAL+ PROJECT+}++model InAppAgentConversation {+ id String+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ createdByUserId String? @map("created_by_user_id")+ createdByUser User? @relation("InAppAgentConversationCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)+ title String?+ visibilityScope InAppAgentConversationVisibilityScope @default(PERSONAL) @map("visibility_scope")+ providerSessionId String? @map("provider_session_id")+ deletedAt DateTime? @map("deleted_at")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ events InAppAgentEvent[]+ runs InAppAgentRun[]++ @@id([id, projectId])+ @@index([projectId, createdByUserId, deletedAt, updatedAt, id], map: "in_app_agent_conversations_project_user_list_idx")+ @@map("in_app_agent_conversations")+}++model InAppAgentEvent {+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ conversationId String @map("conversation_id")+ conversation InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)+ runId String @map("run_id")+ run InAppAgentRun @relation(fields: [runId, projectId], references: [id, projectId], onDelete: Cascade)+ sequenceNumber Int @map("sequence_number")+ type String+ event Json @db.JsonB+ createdAt DateTime @default(now()) @map("created_at")++ @@id([projectId, conversationId, sequenceNumber])+ @@index([projectId, runId], map: "in_app_agent_events_project_run_idx")+ @@map("in_app_agent_events")+}++model InAppAgentRun {+ id String+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ conversationId String @map("conversation_id")+ conversation InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)+ triggeredByUserId String? @map("triggered_by_user_id")+ triggeredByUser User? @relation("InAppAgentRunTriggeredByUser", fields: [triggeredByUserId], references: [id], onDelete: SetNull)+ model String?+ mcpApiKeyId String? @map("mcp_api_key_id")+ errorCode String? @map("error_code")+ errorMessage String? @map("error_message")+ finishedAt DateTime? @map("finished_at")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ events InAppAgentEvent[]++ @@id([id, projectId])+ @@index([projectId, conversationId, createdAt], map: "in_app_agent_runs_project_conversation_created_idx")+ @@map("in_app_agent_runs")+}+model BackgroundMigration {id String @id @default(cuid())name String @uniquediff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex f6c9e60125..3e1b654fe4 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -32,6 +32,7 @@ import {generateEvalScoreId,generateEvalTraceId,} from "./utils/seed-helpers";+import { seedInAppAgentDemoConversation } from "./utils/in-app-agent-seed";import { seedDatasetVersions } from "./seed-dataset-versions";import { seedMediaTraces } from "./seed-media";@@ -163,7 +164,7 @@ async function main() {},});- await prisma.prompt.upsert({+ const summaryPrompt = await prisma.prompt.upsert({where: {projectId_name_version: {projectId: seedProjectId,@@ -182,6 +183,13 @@ async function main() {update: {},});+ await seedInAppAgentDemoConversation({+ prisma,+ projectId: project1.id,+ userId: user.id,+ summaryPrompt,+ });+const seedApiKey = {id: "seed-api-key",secret: process.env.SEED_SECRET_KEY ?? "sk-lf-1234567890", // eslint-disable-line turbo/no-undeclared-env-varsdiff --git a/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts b/packages/shared/scripts/seeder/utils/in-app-agent-seed.tsnew file mode 100644index 0000000000..af13e9faf7--- /dev/null+++ b/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts@@ -0,0 +1,349 @@+import {+ type Prisma,+ type PrismaClient,+ type Prompt,+} from "../../../src/index";++type SummaryPrompt = Pick<+ Prompt,+ | "id"+ | "name"+ | "version"+ | "type"+ | "prompt"+ | "labels"+ | "tags"+ | "config"+ | "createdAt"+ | "updatedAt"+ | "createdBy"+ | "projectId"+>;++export async function seedInAppAgentDemoConversation({+ prisma,+ projectId,+ userId,+ summaryPrompt,+}: {+ prisma: PrismaClient;+ projectId: string;+ userId: string;+ summaryPrompt: SummaryPrompt;+}) {+ const conversationId = "aconv_seed_conversation";+ const firstRunId = "arun_seed_intro";+ const secondRunId = "arun_seed_prompt_lookup";+ const firstUserMessageId = "amsg_seed_intro_user";+ const secondUserMessageId = "amsg_seed_prompt_lookup_user";+ const firstAssistantMessageId = "amsg_seed_intro_assistant";+ const secondAssistantMessageId = "amsg_seed_prompt_lookup_assistant";+ const listPromptsToolCallId = "toolu_seed_list_prompts";+ const getPromptToolCallId = "toolu_seed_get_prompt";+ const firstRunCreatedAt = new Date("2026-06-04T07:56:33.794Z");+ const firstRunFinishedAt = new Date("2026-06-04T07:56:42.684Z");+ const secondRunCreatedAt = new Date("2026-06-04T07:56:52.770Z");+ const secondRunFinishedAt = new Date("2026-06-04T07:57:02.810Z");+ const promptContent =+ typeof summaryPrompt.prompt === "string"+ ? summaryPrompt.prompt+ : JSON.stringify(summaryPrompt.prompt);+ const labelsText =+ summaryPrompt.labels.length > 0 ? summaryPrompt.labels.join(", ") : "None";+ const tagsText =+ summaryPrompt.tags.length > 0 ? summaryPrompt.tags.join(", ") : "None";+ const promptCreatedAt = summaryPrompt.createdAt.toISOString();+ const promptUpdatedAt = summaryPrompt.updatedAt.toISOString();++ const listPromptsResult = JSON.stringify({+ data: [+ {+ name: summaryPrompt.name,+ type: summaryPrompt.type,+ versions: [summaryPrompt.version],+ labels: summaryPrompt.labels,+ tags: summaryPrompt.tags,+ lastUpdatedAt: promptUpdatedAt,+ lastConfig: summaryPrompt.config,+ },+ ],+ meta: {+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ },+ });+ const getPromptResult = JSON.stringify({+ id: summaryPrompt.id,+ name: summaryPrompt.name,+ version: summaryPrompt.version,+ type: summaryPrompt.type,+ prompt: promptContent,+ labels: summaryPrompt.labels,+ tags: summaryPrompt.tags,+ config: summaryPrompt.config,+ createdAt: promptCreatedAt,+ updatedAt: promptUpdatedAt,+ createdBy: summaryPrompt.createdBy,+ projectId: summaryPrompt.projectId,+ });+ const assistantIntro =+ "I'm your Langfuse assistant! I can help you with:\n\n" ++ "**Langfuse Data & Analysis:**\n" ++ "- Query and explore your traces, observations, and spans\n" ++ "- Review and analyze scores, annotations, and feedback\n" ++ "- Inspect datasets, prompts, and experiment runs\n" ++ "- Understand your application's performance metrics\n" ++ "- Retrieve specific traces, observations, or scores by ID\n\n" ++ "**Prompts & Configuration:**\n" ++ "- Fetch and review prompts (including specific versions or labels)\n" ++ "- Check prompt dependencies and structures\n" ++ "- Look up models and score configurations\n\n" ++ "**Codebase & Development:**\n" ++ "- Explore and search your codebase\n" ++ "- Understand file structure and patterns\n" ++ "- Help with code review and analysis\n" ++ "- Assist with git operations and commits\n" ++ "- Run and manage tasks\n\n" ++ "**What would you like to do?** Some common examples:\n" ++ '- "Show me traces from the last hour"\n' ++ '- "Get the latest version of [prompt name]"\n' ++ '- "What scores have been created recently?"\n' ++ '- "Help me find [file/function] in the codebase"\n' ++ '- "Review my pull request"\n\n' ++ "Just let me know what you need!";+ const assistantPromptSummary =+ "**Your Prompts:**\n\n" ++ "You have **1 prompt** in your project:\n\n" ++ "| Name | Type | Version | Labels |\n" ++ "|------|------|---------|--------|\n" ++ `| \`${summaryPrompt.name}\` | ${summaryPrompt.type} | ${summaryPrompt.version} | ${labelsText} |\n\n` ++ `**Content of ${summaryPrompt.name} (v${summaryPrompt.version}):**\n\n` ++ "```\n" ++ `${promptContent}\n` ++ "```\n\n" ++ "**Details:**\n" ++ `- **ID**: ${summaryPrompt.id}\n` ++ `- **Created**: ${formatInAppAgentSeedDate(summaryPrompt.createdAt)}\n` ++ `- **Created by**: ${summaryPrompt.createdBy}\n` ++ `- **Labels**: ${labelsText}\n` ++ `- **Tags**: ${tagsText}\n\n` ++ "The prompt uses two template variables: `{{variable}}` and `{{anotherVariable}}`.";++ const eventRows: Array<{+ projectId: string;+ conversationId: string;+ runId: string;+ sequenceNumber: number;+ type: string;+ event: Prisma.InputJsonValue;+ createdAt: Date;+ }> = [];+ const addEvent = (+ runId: string,+ type: string,+ event: Record<string, unknown>,+ ) => {+ const sequenceNumber = eventRows.length;+ eventRows.push({+ projectId,+ conversationId,+ runId,+ sequenceNumber,+ type,+ event: event as Prisma.InputJsonValue,+ createdAt: new Date(firstRunFinishedAt.getTime() + sequenceNumber * 1000),+ });+ };++ addEvent(firstRunId, "RUN_STARTED", {+ type: "RUN_STARTED",+ threadId: conversationId,+ runId: firstRunId,+ input: {+ threadId: conversationId,+ runId: firstRunId,+ state: null,+ messages: [+ {+ id: firstUserMessageId,+ role: "user",+ content: "Hi, what can you help me with?",+ },+ ],+ tools: [],+ context: [],+ forwardedProps: {},+ },+ });+ addEvent(firstRunId, "TEXT_MESSAGE_START", {+ type: "TEXT_MESSAGE_START",+ messageId: firstAssistantMessageId,+ role: "assistant",+ });+ addEvent(firstRunId, "TEXT_MESSAGE_CONTENT", {+ type: "TEXT_MESSAGE_CONTENT",+ messageId: firstAssistantMessageId,+ delta: assistantIntro,+ });+ addEvent(firstRunId, "TEXT_MESSAGE_END", {+ type: "TEXT_MESSAGE_END",+ messageId: firstAssistantMessageId,+ });+ addEvent(firstRunId, "RUN_FINISHED", {+ type: "RUN_FINISHED",+ threadId: conversationId,+ runId: firstRunId,+ });+ addEvent(secondRunId, "RUN_STARTED", {+ type: "RUN_STARTED",+ threadId: conversationId,+ runId: secondRunId,+ input: {+ threadId: conversationId,+ runId: secondRunId,+ state: null,+ messages: [+ {+ id: secondUserMessageId,+ role: "user",+ content:+ "List my prompts and give me the content of the first prompt.",+ },+ ],+ tools: [],+ context: [],+ forwardedProps: {},+ },+ });+ addEvent(secondRunId, "TOOL_CALL_START", {+ type: "TOOL_CALL_START",+ toolCallId: listPromptsToolCallId,+ toolCallName: "listPrompts",+ parentMessageId: "amsg_seed_list_prompts_tool_parent",+ });+ addEvent(secondRunId, "TOOL_CALL_ARGS", {+ type: "TOOL_CALL_ARGS",+ toolCallId: listPromptsToolCallId,+ delta: '{"page": 1, "limit": 50}',+ });+ addEvent(secondRunId, "TOOL_CALL_END", {+ type: "TOOL_CALL_END",+ toolCallId: listPromptsToolCallId,+ });+ addEvent(secondRunId, "TOOL_CALL_RESULT", {+ type: "TOOL_CALL_RESULT",+ messageId: `${listPromptsToolCallId}-result`,+ toolCallId: listPromptsToolCallId,+ role: "tool",+ content: listPromptsResult,+ });+ addEvent(secondRunId, "TOOL_CALL_START", {+ type: "TOOL_CALL_START",+ toolCallId: getPromptToolCallId,+ toolCallName: "getPrompt",+ parentMessageId: "amsg_seed_get_prompt_tool_parent",+ });+ addEvent(secondRunId, "TOOL_CALL_ARGS", {+ type: "TOOL_CALL_ARGS",+ toolCallId: getPromptToolCallId,+ delta: `{"name": "${summaryPrompt.name}"}`,+ });+ addEvent(secondRunId, "TOOL_CALL_END", {+ type: "TOOL_CALL_END",+ toolCallId: getPromptToolCallId,+ });+ addEvent(secondRunId, "TOOL_CALL_RESULT", {+ type: "TOOL_CALL_RESULT",+ messageId: `${getPromptToolCallId}-result`,+ toolCallId: getPromptToolCallId,+ role: "tool",+ content: getPromptResult,+ });+ addEvent(secondRunId, "TEXT_MESSAGE_START", {+ type: "TEXT_MESSAGE_START",+ messageId: secondAssistantMessageId,+ role: "assistant",+ });+ addEvent(secondRunId, "TEXT_MESSAGE_CONTENT", {+ type: "TEXT_MESSAGE_CONTENT",+ messageId: secondAssistantMessageId,+ delta: assistantPromptSummary,+ });+ addEvent(secondRunId, "TEXT_MESSAGE_END", {+ type: "TEXT_MESSAGE_END",+ messageId: secondAssistantMessageId,+ });+ addEvent(secondRunId, "RUN_FINISHED", {+ type: "RUN_FINISHED",+ threadId: conversationId,+ runId: secondRunId,+ });++ await prisma.$transaction(async (tx) => {+ await tx.inAppAgentEvent.deleteMany({+ where: { projectId, conversationId },+ });+ await tx.inAppAgentRun.deleteMany({+ where: { projectId, conversationId },+ });+ await tx.inAppAgentConversation.upsert({+ where: {+ id_projectId: {+ id: conversationId,+ projectId,+ },+ },+ create: {+ id: conversationId,+ projectId,+ createdByUserId: userId,+ title: "Seed Conversation",+ createdAt: firstRunCreatedAt,+ updatedAt: secondRunFinishedAt,+ },+ update: {+ createdByUserId: userId,+ title: "Seed Conversation",+ providerSessionId: null,+ deletedAt: null,+ updatedAt: secondRunFinishedAt,+ },+ });+ await tx.inAppAgentRun.createMany({+ data: [+ {+ id: firstRunId,+ projectId,+ conversationId,+ triggeredByUserId: userId,+ model: "haiku",+ finishedAt: firstRunFinishedAt,+ createdAt: firstRunCreatedAt,+ updatedAt: firstRunFinishedAt,+ },+ {+ id: secondRunId,+ projectId,+ conversationId,+ triggeredByUserId: userId,+ model: "haiku",+ finishedAt: secondRunFinishedAt,+ createdAt: secondRunCreatedAt,+ updatedAt: secondRunFinishedAt,+ },+ ],+ });+ await tx.inAppAgentEvent.createMany({+ data: eventRows,+ });+ });+}++function formatInAppAgentSeedDate(date: Date) {+ return date+ .toISOString()+ .replace("T", " at ")+ .replace(/\.\d{3}Z$/, " UTC");+}diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsnew file mode 100644index 0000000000..fc58914c16--- /dev/null+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -0,0 +1,1004 @@+import type { Session } from "next-auth";+import { EventType } from "@ag-ui/core";+import { randomUUID } from "crypto";++import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";+import {+ createInAppAgentConversationId,+ createInAppAgentRunId,+} from "@/src/features/in-app-agent/ids";+import type { AgUiEvent } from "@/src/features/in-app-agent/schema";+import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";+import {+ createRun,+ ensureOwnedConversation,+ finishRun,+ replaceRunEvents,+ shouldFlushPersistedEvent,+ toPersistableAgentEvent,+} from "@/src/features/in-app-agent/server/persistence";+import { createInnerTRPCContext } from "@/src/server/api/trpc";++describe("in-app agent persistence", () => {+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ beforeEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ });++ const createCaller = async (userId = `user-${randomUUID()}`) => {+ const setup = await createOrgProjectAndApiKey();++ await prisma.organization.update({+ where: { id: setup.orgId },+ data: { aiFeaturesEnabled: true },+ });++ await prisma.user.create({+ data: {+ id: userId,+ email: `${userId}@example.com`,+ },+ });++ const session: Session = {+ expires: "1",+ user: {+ id: userId,+ name: "Agent User",+ canCreateOrganizations: true,+ organizations: [+ {+ id: setup.orgId,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ name: "Test Organization",+ metadata: {},+ projects: [+ {+ id: setup.projectId,+ role: "ADMIN",+ name: "Test Project",+ deletedAt: null,+ retentionDays: null,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ inAppAgent: true,+ templateFlag: true,+ excludeClickhouseRead: false,+ },+ admin: false,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });++ return {+ ...setup,+ userId,+ caller: inAppAgentRouter.createCaller({ ...ctx, prisma }),+ session,+ };+ };++ const createConversation = (params: {+ projectId: string;+ userId: string;+ conversationId?: string;+ }) =>+ ensureOwnedConversation({+ prisma,+ projectId: params.projectId,+ conversationId: params.conversationId ?? createInAppAgentConversationId(),+ userId: params.userId,+ });++ const createConversationRun = async (params: {+ projectId: string;+ conversationId: string;+ userId: string;+ runId?: string;+ }) =>+ createRun({+ prisma,+ runId: params.runId ?? createInAppAgentRunId(),+ projectId: params.projectId,+ conversationId: params.conversationId,+ triggeredByUserId: params.userId,+ model: "haiku",+ mcpApiKeyId: "api-key-id-1",+ });++ const startCompactRun = async (params: {+ projectId: string;+ conversationId: string;+ runId: string;+ messageId: string;+ content: string;+ }) => {+ const userMessage = {+ id: params.messageId,+ role: "user" as const,+ content: params.content,+ };+ const events: AgUiEvent[] = [+ {+ type: EventType.RUN_STARTED,+ threadId: params.conversationId,+ runId: params.runId,+ input: {+ threadId: params.conversationId,+ runId: params.runId,+ state: null,+ messages: [userMessage],+ tools: [],+ context: [],+ forwardedProps: {},+ },+ },+ ];++ await replaceRunEvents({+ prisma,+ projectId: params.projectId,+ conversationId: params.conversationId,+ runId: params.runId,+ events,+ });++ return events;+ };++ const processAndPersistEvent = async (params: {+ projectId: string;+ conversationId: string;+ runId: string;+ events: AgUiEvent[];+ event: AgUiEvent;+ }) => {+ const persistedEvent = toPersistableAgentEvent(params.event);++ if (!persistedEvent) {+ return;+ }++ params.events.push(persistedEvent);++ if (!shouldFlushPersistedEvent(persistedEvent)) {+ return;+ }++ await replaceRunEvents({+ prisma,+ projectId: params.projectId,+ conversationId: params.conversationId,+ runId: params.runId,+ events: params.events,+ });+ };++ const appendAssistantText = async (params: {+ projectId: string;+ conversationId: string;+ runId: string;+ events: AgUiEvent[];+ messageId: string;+ chunks: string[];+ }) => {+ await processAndPersistEvent({+ ...params,+ event: {+ type: EventType.TEXT_MESSAGE_START,+ messageId: params.messageId,+ role: "assistant",+ },+ });++ for (const delta of params.chunks) {+ await processAndPersistEvent({+ ...params,+ event: {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: params.messageId,+ delta,+ },+ });+ }++ await processAndPersistEvent({+ ...params,+ event: {+ type: EventType.TEXT_MESSAGE_END,+ messageId: params.messageId,+ },+ });+ };++ it("stores compacted events and restores multi-turn messages", async () => {+ const { caller, projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run1 = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await prisma.inAppAgentConversation.update({+ where: { id_projectId: { id: conversation.id, projectId } },+ data: { providerSessionId: "claude-session-secret" },+ });++ const events1 = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run1.id,+ messageId: "user-message-1",+ content: "Please inspect today's traces for outliers",+ });+ await appendAssistantText({+ projectId,+ conversationId: conversation.id,+ runId: run1.id,+ events: events1,+ messageId: "assistant-message-1",+ chunks: ["I will inspect recent traces", " and look for outliers."],+ });+ await finishRun({+ prisma,+ runId: run1.id,+ projectId,+ });++ const run2 = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ const events2 = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run2.id,+ messageId: "user-message-2",+ content: "Inspect the next trace",+ });+ await appendAssistantText({+ projectId,+ conversationId: conversation.id,+ runId: run2.id,+ events: events2,+ messageId: "assistant-message-2",+ chunks: ["Next trace inspected."],+ });++ const detail = await caller.getConversation({+ projectId,+ conversationId: conversation.id,+ });++ expect(detail.conversation).not.toHaveProperty("providerSessionId");+ expect(detail.conversation).not.toHaveProperty("provider");+ expect(detail.state).toEqual({+ type: "existingConversation",+ projectId,+ conversationId: conversation.id,+ });+ expect(detail.messages).toEqual([+ {+ id: "user-message-1",+ role: "user",+ content: "Please inspect today's traces for outliers",+ },+ {+ id: "assistant-message-1",+ role: "assistant",+ content: "I will inspect recent traces and look for outliers.",+ },+ {+ id: "user-message-2",+ role: "user",+ content: "Inspect the next trace",+ },+ {+ id: "assistant-message-2",+ role: "assistant",+ content: "Next trace inspected.",+ },+ ]);++ const events = await prisma.inAppAgentEvent.findMany({+ where: { projectId, conversationId: conversation.id },+ orderBy: { sequenceNumber: "asc" },+ select: { sequenceNumber: true, type: true, event: true },+ });++ expect(events.map((event) => event.sequenceNumber)).toEqual([+ 0, 1, 2, 3, 4, 5, 6, 7,+ ]);+ expect(events.map((event) => event.type)).toEqual([+ EventType.RUN_STARTED,+ EventType.TEXT_MESSAGE_START,+ EventType.TEXT_MESSAGE_CONTENT,+ EventType.TEXT_MESSAGE_END,+ EventType.RUN_STARTED,+ EventType.TEXT_MESSAGE_START,+ EventType.TEXT_MESSAGE_CONTENT,+ EventType.TEXT_MESSAGE_END,+ ]);+ expect(events[0]?.event).toMatchObject({+ type: EventType.RUN_STARTED,+ input: {+ messages: [+ {+ id: "user-message-1",+ role: "user",+ content: "Please inspect today's traces for outliers",+ },+ ],+ },+ });+ expect(events[2]?.event).toMatchObject({+ type: EventType.TEXT_MESSAGE_CONTENT,+ delta: "I will inspect recent traces and look for outliers.",+ });+ expect(events[4]?.event).toMatchObject({+ type: EventType.RUN_STARTED,+ input: {+ messages: [+ {+ id: "user-message-2",+ role: "user",+ content: "Inspect the next trace",+ },+ ],+ },+ });+ expect(events[6]?.event).toMatchObject({+ type: EventType.TEXT_MESSAGE_CONTENT,+ delta: "Next trace inspected.",+ });++ const listedConversations = await caller.listConversations({ projectId });+ expect(listedConversations.conversations.map((item) => item.id)).toContain(+ conversation.id,+ );+ });++ it("does not reduce partial assistant content before the end event", async () => {+ const { caller, 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: "partial-user",+ content: "Start a long answer",+ });+ await processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event: {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "partial-assistant",+ role: "assistant",+ },+ });+ await processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event: {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "partial-assistant",+ delta: "Half-written",+ },+ });++ await expect(+ caller.getConversation({ projectId, conversationId: conversation.id }),+ ).resolves.toMatchObject({+ messages: [+ {+ id: "partial-user",+ role: "user",+ content: "Start a long answer",+ },+ ],+ });+ await expect(+ prisma.inAppAgentEvent.count({+ where: { projectId, conversationId: conversation.id, runId: run.id },+ }),+ ).resolves.toBe(1);+ });++ it("stores and reduces tool calls, tool results, and activities", async () => {+ const { projectId, userId, caller } = 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: "tool-user",+ content: "Search traces",+ });+ const process = (event: AgUiEvent) =>+ processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event,+ });++ await process({+ type: EventType.TEXT_MESSAGE_START,+ messageId: "tool-assistant",+ role: "assistant",+ });+ await process({+ type: EventType.TOOL_CALL_START,+ toolCallId: "tool-call-1",+ toolCallName: "list_traces",+ parentMessageId: "tool-assistant",+ });+ await process({+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: '{"limit":',+ });+ await process({+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: "10}",+ });+ await process({+ type: EventType.TOOL_CALL_END,+ toolCallId: "tool-call-1",+ });+ await process({+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "tool-assistant",+ delta: "I searched traces.",+ });+ await process({+ type: EventType.TEXT_MESSAGE_END,+ messageId: "tool-assistant",+ });+ await process({+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-result-1",+ toolCallId: "tool-call-1",+ content: "[]",+ role: "tool",+ });+ await process({+ type: EventType.REASONING_MESSAGE_START,+ messageId: "reasoning-1",+ role: "reasoning",+ });+ await process({+ type: EventType.REASONING_MESSAGE_CONTENT,+ messageId: "reasoning-1",+ delta: "Checking filters",+ });+ await process({+ type: EventType.REASONING_ENCRYPTED_VALUE,+ subtype: "message",+ entityId: "reasoning-1",+ encryptedValue: "encrypted-reasoning",+ });+ await process({+ type: EventType.REASONING_MESSAGE_END,+ messageId: "reasoning-1",+ });+ await process({+ type: EventType.ACTIVITY_SNAPSHOT,+ messageId: "activity-1",+ activityType: "progress",+ content: { status: "done" },+ });++ await expect(+ caller.getConversation({ projectId, conversationId: conversation.id }),+ ).resolves.toMatchObject({+ messages: [+ {+ id: "tool-user",+ role: "user",+ content: "Search traces",+ },+ {+ id: "tool-assistant",+ role: "assistant",+ content: "I searched traces.",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "list_traces",+ arguments: '{"limit":10}',+ },+ },+ ],+ },+ {+ id: "tool-result-1",+ role: "tool",+ content: "[]",+ toolCallId: "tool-call-1",+ },+ {+ id: "activity-1",+ role: "activity",+ activityType: "progress",+ content: { status: "done" },+ },+ ],+ });++ await expect(+ prisma.inAppAgentEvent.count({+ where: { projectId, conversationId: conversation.id, runId: run.id },+ }),+ ).resolves.toBe(9);+ });++ it("stores only compact events and skips raw adapter payloads", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ const eventsBuffer = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ messageId: "safe-user",+ content: "visible user text",+ });+ const process = (event: AgUiEvent) =>+ processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events: eventsBuffer,+ event,+ });++ await process({+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-safe",+ role: "assistant",+ rawEvent: { token: "raw-text-start-secret" },+ });+ await process({+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "assistant-safe",+ delta: "visible assistant text",+ rawEvent: { token: "raw-text-content-secret" },+ providerSessionId: "content-secret",+ });++ for (const event of [+ {+ type: EventType.CUSTOM,+ name: "system:status",+ value: { session_id: "provider-status-secret" },+ },+ {+ type: EventType.STATE_DELTA,+ delta: [+ {+ op: "replace",+ path: "",+ value: { providerSessionId: "state-delta-secret" },+ },+ ],+ },+ {+ type: EventType.REASONING_MESSAGE_CONTENT,+ messageId: "reasoning-1",+ delta: "reasoning-secret",+ },+ {+ type: EventType.RAW,+ event: { Authorization: "Basic raw-secret" },+ },+ ]) {+ await process(event);+ }++ const events = await prisma.inAppAgentEvent.findMany({+ where: { projectId, conversationId: conversation.id, runId: run.id },+ orderBy: { sequenceNumber: "asc" },+ select: { type: true, event: true },+ });++ expect(events.map((event) => event.type)).toEqual([EventType.RUN_STARTED]);+ expect(events[0]?.event).toMatchObject({+ type: EventType.RUN_STARTED,+ input: {+ messages: [+ {+ id: "safe-user",+ role: "user",+ content: "visible user text",+ },+ ],+ },+ });+ expect(JSON.stringify(events)).not.toContain("secret");+ });++ it("ignores adapter message snapshots when persisting compact events", async () => {+ const { caller, 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: "snapshot-user",+ content: "Keep this",+ });+ await processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event: {+ type: EventType.MESSAGES_SNAPSHOT,+ messages: [+ {+ id: "snapshot-only",+ role: "assistant",+ content: "Do not restore me",+ },+ ],+ },+ });++ await expect(+ caller.getConversation({ projectId, conversationId: conversation.id }),+ ).resolves.toMatchObject({+ messages: [+ {+ id: "snapshot-user",+ role: "user",+ content: "Keep this",+ },+ ],+ });++ await expect(+ prisma.inAppAgentEvent.count({+ where: { projectId, conversationId: conversation.id, runId: run.id },+ }),+ ).resolves.toBe(1);+ });++ it("does not expose another user's conversation in the same project", async () => {+ const owner = await createCaller();+ const otherUserId = `user-${randomUUID()}`;++ await prisma.user.create({+ data: {+ id: otherUserId,+ email: `${otherUserId}@example.com`,+ },+ });++ const otherSession: Session = {+ ...owner.session,+ user: {+ ...owner.session.user!,+ id: otherUserId,+ },+ };++ const otherCtx = createInnerTRPCContext({+ session: otherSession,+ headers: {},+ });+ const otherCaller = inAppAgentRouter.createCaller({ ...otherCtx, prisma });++ const conversation = await createConversation({+ projectId: owner.projectId,+ userId: owner.userId,+ });++ await expect(+ otherCaller.getConversation({+ projectId: owner.projectId,+ conversationId: conversation.id,+ }),+ ).rejects.toThrow("Agent conversation not found");++ const visibleConversations = await otherCaller.listConversations({+ projectId: owner.projectId,+ });++ expect(visibleConversations.conversations).toEqual([]);+ expect(visibleConversations.nextCursor).toBeUndefined();+ });++ it("allows conversation and run ids to repeat across projects", async () => {+ const owner = await createCaller();+ const other = await createCaller();+ const conversation = await createConversation({+ projectId: owner.projectId,+ userId: owner.userId,+ });++ const otherConversation = await ensureOwnedConversation({+ prisma,+ projectId: other.projectId,+ conversationId: conversation.id,+ userId: other.userId,+ });++ expect(otherConversation).toMatchObject({+ id: conversation.id,+ projectId: other.projectId,+ createdByUserId: other.userId,+ });++ const runId = createInAppAgentRunId();+ await createConversationRun({+ projectId: owner.projectId,+ conversationId: conversation.id,+ userId: owner.userId,+ runId,+ });+ await expect(+ createConversationRun({+ projectId: other.projectId,+ conversationId: otherConversation.id,+ userId: other.userId,+ runId,+ }),+ ).resolves.toMatchObject({+ id: runId,+ projectId: other.projectId,+ });+ });++ it("finishes runs once and preserves the first terminal error", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ expect(run.mcpApiKeyId).toBe("api-key-id-1");+ expect(run.finishedAt).toBeNull();++ await finishRun({+ prisma,+ runId: run.id,+ projectId,+ errorCode: "agent_error",+ errorMessage: "Original agent error",+ });+ await finishRun({+ prisma,+ runId: run.id,+ projectId,+ errorCode: "cancelled",+ errorMessage: "Client aborted request",+ });++ await expect(+ prisma.inAppAgentRun.findUniqueOrThrow({+ where: { id_projectId: { id: run.id, projectId } },+ }),+ ).resolves.toMatchObject({+ errorCode: "agent_error",+ errorMessage: "Original agent error",+ });+ });++ it("ignores event flushes from already-finished runs", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run1 = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ const events1 = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run1.id,+ messageId: "user-message-1",+ content: "First",+ });++ await finishRun({ prisma, runId: run1.id, projectId });++ const run2 = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run2.id,+ messageId: "user-message-2",+ content: "Second",+ });++ await appendAssistantText({+ projectId,+ conversationId: conversation.id,+ runId: run1.id,+ events: events1,+ messageId: "assistant-message-1",+ chunks: ["Late output"],+ });++ const events = await prisma.inAppAgentEvent.findMany({+ where: { projectId, conversationId: conversation.id },+ orderBy: { sequenceNumber: "asc" },+ select: { runId: true, type: true },+ });++ expect(events).toEqual([+ { runId: run1.id, type: EventType.RUN_STARTED },+ { runId: run2.id, type: EventType.RUN_STARTED },+ ]);+ });++ it("blocks a second active run in the same conversation", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });++ await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await expect(+ createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ }),+ ).rejects.toThrow("Assistant is already responding in this conversation");+ });++ it("marks old unfinished runs stale before starting a new run", async () => {+ const { projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const staleRun = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await prisma.inAppAgentRun.update({+ where: { id_projectId: { id: staleRun.id, projectId } },+ data: { createdAt: new Date("2026-05-20T10:00:00.000Z") },+ });++ const newRun = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await expect(+ prisma.inAppAgentRun.findUniqueOrThrow({+ where: { id_projectId: { id: staleRun.id, projectId } },+ }),+ ).resolves.toMatchObject({+ errorCode: "stale",+ errorMessage: "Run was marked stale before starting a new run",+ });+ expect(newRun.finishedAt).toBeNull();+ });++ it("paginates conversation list with a stable cursor", async () => {+ const { caller, projectId, userId } = await createCaller();+ const idPrefix = `pagination-${randomUUID()}`;+ const latest = new Date("2026-05-20T10:00:00.000Z");+ const middle = new Date("2026-05-20T09:00:00.000Z");+ const oldest = new Date("2026-05-20T08:00:00.000Z");++ await prisma.inAppAgentConversation.createMany({+ data: [+ {+ id: `${idPrefix}-a`,+ projectId,+ createdByUserId: userId,+ createdAt: latest,+ updatedAt: latest,+ },+ {+ id: `${idPrefix}-b`,+ projectId,+ createdByUserId: userId,+ createdAt: latest,+ updatedAt: latest,+ },+ {+ id: `${idPrefix}-c`,+ projectId,+ createdByUserId: userId,+ createdAt: middle,+ updatedAt: middle,+ },+ {+ id: `${idPrefix}-d`,+ projectId,+ createdByUserId: userId,+ createdAt: oldest,+ updatedAt: oldest,+ },+ ],+ });++ const firstPage = await caller.listConversations({ projectId, limit: 2 });++ expect(firstPage.conversations.map((item) => item.id)).toEqual([+ `${idPrefix}-b`,+ `${idPrefix}-a`,+ ]);+ expect(firstPage.nextCursor).toEqual({+ updatedAt: latest,+ id: `${idPrefix}-a`,+ });++ const secondPage = await caller.listConversations({+ projectId,+ limit: 2,+ cursor: firstPage.nextCursor,+ });++ expect(secondPage.conversations.map((item) => item.id)).toEqual([+ `${idPrefix}-c`,+ `${idPrefix}-d`,+ ]);+ expect(secondPage.nextCursor).toBeUndefined();+ });+});diff --git a/web/src/__tests__/server/in-app-agent-session-token.servertest.ts b/web/src/__tests__/server/in-app-agent-session-token.servertest.tsdeleted file mode 100644index aaec39d631..0000000000--- a/web/src/__tests__/server/in-app-agent-session-token.servertest.ts+++ /dev/null@@ -1,69 +0,0 @@-import {- InvalidInAppAgentSessionTokenError,- signInAppAgentSessionToken,- verifyInAppAgentSessionToken,-} from "@/src/features/in-app-agent/server/auth";--const tokenParams = {- userId: "user-1",- projectId: "project-1",- threadId: "thread-1",- claudeSessionId: "session-1",-};--describe("in-app agent session tokens", () => {- afterEach(() => {- vi.useRealTimers();- });-- it("signs and verifies a Claude session token", () => {- const token = signInAppAgentSessionToken(tokenParams);-- expect(- verifyInAppAgentSessionToken(token, {- userId: tokenParams.userId,- threadId: tokenParams.threadId,- }),- ).toEqual({- projectId: tokenParams.projectId,- claudeSessionId: tokenParams.claudeSessionId,- });- });-- it("rejects tokens for a different user or thread", () => {- const token = signInAppAgentSessionToken(tokenParams);-- expect(() =>- verifyInAppAgentSessionToken(token, {- userId: "other-user",- threadId: tokenParams.threadId,- }),- ).toThrow(InvalidInAppAgentSessionTokenError);- });-- it("rejects tampered tokens", () => {- const token = signInAppAgentSessionToken(tokenParams);-- expect(() =>- verifyInAppAgentSessionToken(`${token}tampered`, {- userId: tokenParams.userId,- threadId: tokenParams.threadId,- }),- ).toThrow(InvalidInAppAgentSessionTokenError);- });-- it("rejects expired tokens", () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-05-13T00:00:00.000Z"));- const token = signInAppAgentSessionToken(tokenParams);-- vi.setSystemTime(new Date("2026-05-21T00:00:00.000Z"));-- expect(() =>- verifyInAppAgentSessionToken(token, {- userId: tokenParams.userId,- threadId: tokenParams.threadId,- }),- ).toThrow(InvalidInAppAgentSessionTokenError);- });-});diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsnew file mode 100644index 0000000000..7d4e86c32c--- /dev/null+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -0,0 +1,176 @@+import { EventType } from "@ag-ui/core";+import { describe, expect, it, vi } from "vitest";++import type { AgUiEvent } from "@/src/features/in-app-agent/schema";++const adapterEvents = vi.hoisted(() => ({+ items: [] as AgUiEvent[],+}));++vi.mock("@ag-ui/claude-agent-sdk", () => ({+ ClaudeAgentAdapter: vi.fn().mockImplementation(function () {+ return {+ interrupt: vi.fn().mockResolvedValue(undefined),+ run: () => ({+ subscribe: (subscriber: {+ next: (event: AgUiEvent) => void;+ complete: () => void;+ }) => {+ for (const event of adapterEvents.items) {+ subscriber.next(event);+ }+ subscriber.complete();+ return { unsubscribe: vi.fn() };+ },+ }),+ };+ }),+}));++describe("createAgUiStream", () => {+ it("serializes valid events and drops partial adapter message snapshots", async () => {+ const { createAgUiStream } =+ await import("@/src/features/in-app-agent/server/agent");+ const input = {+ threadId: "conversation-1",+ runId: "run-1",+ messages: [+ {+ id: "user-message-1",+ role: "user" as const,+ content: "hello",+ },+ ],+ tools: [],+ context: [],+ state: {+ type: "existingConversation",+ projectId: "project-1",+ conversationId: "conversation-1",+ },+ forwardedProps: {},+ };+ const persistedEvents: AgUiEvent[] = [];+ const eventOrder: string[] = [];++ adapterEvents.items = [+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ {+ type: EventType.MESSAGES_SNAPSHOT,+ messages: [+ {+ id: "user-message-1",+ role: "user",+ content: "hello",+ },+ ],+ },+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-message-1",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "assistant-message-1",+ delta: "hi",+ },+ {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "assistant-message-1",+ },+ {+ type: EventType.RUN_FINISHED,+ threadId: input.threadId,+ runId: input.runId,+ },+ ];++ const stream = createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ onResumeSessionId: () => input.state,+ onEvent: async (event) => {+ persistedEvents.push(event);+ eventOrder.push(`persist:${event.type}`);+ await Promise.resolve();+ },+ awsBedrock: {},+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ },+ },+ });+ const streamedText = await readStream(stream, (event) => {+ eventOrder.push(`stream:${event.type}`);+ });++ expect(streamedText).not.toContain(EventType.MESSAGES_SNAPSHOT);+ expect(persistedEvents.map((event) => event.type)).toEqual([+ EventType.RUN_STARTED,+ EventType.TEXT_MESSAGE_START,+ EventType.TEXT_MESSAGE_CONTENT,+ EventType.TEXT_MESSAGE_END,+ EventType.RUN_FINISHED,+ ]);+ expect(persistedEvents[0]).toMatchObject({+ type: EventType.RUN_STARTED,+ });+ expect(persistedEvents[0]).not.toHaveProperty("input");+ expect(eventOrder).toEqual([+ `persist:${EventType.RUN_STARTED}`,+ `stream:${EventType.RUN_STARTED}`,+ `persist:${EventType.TEXT_MESSAGE_START}`,+ `stream:${EventType.TEXT_MESSAGE_START}`,+ `persist:${EventType.TEXT_MESSAGE_CONTENT}`,+ `stream:${EventType.TEXT_MESSAGE_CONTENT}`,+ `persist:${EventType.TEXT_MESSAGE_END}`,+ `stream:${EventType.TEXT_MESSAGE_END}`,+ `persist:${EventType.RUN_FINISHED}`,+ `stream:${EventType.RUN_FINISHED}`,+ ]);+ });+});++async function readStream(+ stream: ReadableStream<Uint8Array>,+ onEvent?: (event: AgUiEvent) => void,+) {+ const reader = stream.getReader();+ const decoder = new TextDecoder();+ let text = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) {+ return text;+ }+ const chunk = decoder.decode(value);+ text += chunk;++ for (const event of parseEvents(chunk)) {+ onEvent?.(event);+ }+ }+}++function parseEvents(chunk: string) {+ return chunk+ .split("\n\n")+ .filter(Boolean)+ .flatMap((line): AgUiEvent[] => {+ const json = line.replace(/^data: /, "");+ try {+ return [JSON.parse(json) as AgUiEvent];+ } catch {+ return [];+ }+ });+}diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.tsindex dc5dfec727..21a9a71658 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts@@ -162,12 +162,16 @@ export const filters = {*/customShow: (route: Route,- _ctx: NavigationFilterContext,+ ctx: NavigationFilterContext,organization: Organization,): Route | null => {if (!route.show) return route;// Convert null to undefined for route.show compatibility- return route.show({ organization: organization ?? undefined })+ return route.show({+ organization: organization ?? undefined,+ projectId: ctx.routerProjectId,+ isLangfuseCloud: ctx.isLangfuseCloud,+ })? route: null;},diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex 2dc7aa4388..137b6d94aa 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -61,6 +61,8 @@ export type Route = {productModule?: ProductModule; // Product module this route belongs to. Used to show/hide modules via ui customization.show?: (p: {organization: User["organizations"][number] | undefined;+ projectId: string | undefined;+ isLangfuseCloud: boolean;}) => boolean;group?: RouteGroup; // group this route belongs to (within a section)};@@ -235,7 +237,8 @@ export const ROUTES: Route[] = [section: RouteSection.Secondary,pathname: "",featureFlag: "inAppAgent",- show: ({ organization }) => organization?.aiFeaturesEnabled === true,+ show: ({ organization, projectId, isLangfuseCloud }) =>+ isLangfuseCloud && organization !== undefined && projectId !== undefined,menuNode: <InAppAiAgentButton />,},{diff --git a/web/src/components/nav/in-app-ai-agent-button.tsx b/web/src/components/nav/in-app-ai-agent-button.tsxindex 91894e882a..3da7123982 100644--- a/web/src/components/nav/in-app-ai-agent-button.tsx+++ b/web/src/components/nav/in-app-ai-agent-button.tsx@@ -1,14 +1,27 @@+import { useState } from "react";import { Bot } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";import { SidebarMenuButton, useSidebar } from "@/src/components/ui/sidebar";import { useInAppAiAgent } from "@/src/features/in-app-agent/components/InAppAiAgentProvider";+import { AIFeaturesDisabledNotice } from "@/src/features/organizations/components/AIFeaturesDisabledNotice";+import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";export const InAppAiAgentButton = () => {+ const { organization } = useQueryProjectOrOrganization();const { isAvailable, setOpen } = useInAppAiAgent();const { setOpen: setSupportDrawerOpen } = useSupportDrawer();const { isMobile, setOpenMobile: setOpenMobileSidebar } = useSidebar();-+ const [enableDialogOpen, setEnableDialogOpen] = useState(false);if (!isAvailable) {return null;}@@ -18,24 +31,59 @@ export const InAppAiAgentButton = () => {setOpen((currentOpen) => !currentOpen);};- return (- <SidebarMenuButton- isActive={false}- onClick={() => {- if (isMobile) {- setOpenMobileSidebar(false);- setTimeout(() => {- // push to next tick to avoid flickering when hiding sidebar on mobile- toggleInAppAiAgent();- }, 1);- return;- }+ const handleClick = () => {+ if (isMobile) {+ setOpenMobileSidebar(false);+ }+ if (organization && !organization.aiFeaturesEnabled) {+ setSupportDrawerOpen(false);+ setEnableDialogOpen(true);+ return;+ }++ if (isMobile) {+ setTimeout(() => {+ // push to next tick to avoid flickering when hiding sidebar on mobiletoggleInAppAiAgent();- }}- >- <Bot className="h-4 w-4" />- AI Assistant- </SidebarMenuButton>+ }, 1);+ return;+ }++ toggleInAppAiAgent();+ };++ return (+ <>+ <SidebarMenuButton isActive={false} onClick={handleClick}>+ <Bot className="h-4 w-4" />+ AI Assistant+ </SidebarMenuButton>++ <Dialog open={enableDialogOpen} onOpenChange={setEnableDialogOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>AI features are disabled</DialogTitle>+ </DialogHeader>+ <DialogBody>+ <AIFeaturesDisabledNotice organizationId={organization?.id}>+ The AI assistant requires AI features to be enabled for this+ organization.+ </AIFeaturesDisabledNotice>+ </DialogBody>+ <DialogFooter>+ <div className="flex justify-end">+ <Button+ type="button"+ variant="outline"+ onClick={() => setEnableDialogOpen(false)}+ >+ Close+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);};diff --git a/web/src/components/table/data-table-ai-filters.tsx b/web/src/components/table/data-table-ai-filters.tsxindex 442b8b6e3c..cbdd5092e3 100644--- a/web/src/components/table/data-table-ai-filters.tsx+++ b/web/src/components/table/data-table-ai-filters.tsx@@ -7,10 +7,10 @@ import {TooltipProvider,TooltipTrigger,} from "@/src/components/ui/tooltip";-import { Info, ExternalLink } from "lucide-react";+import { Info } from "lucide-react";import { useQueryProject } from "@/src/features/projects/hooks";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";-import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { AIFeaturesDisabledNotice } from "@/src/features/organizations/components/AIFeaturesDisabledNotice";import { api } from "@/src/utils/api";import { type FilterState } from "@langfuse/shared";@@ -26,11 +26,6 @@ export function DataTableAIFilters({const projectId = useProjectIdFromURL();const { organization } = useQueryProject();- const hasAdminAccess = useHasOrganizationAccess({- organizationId: organization?.id ?? undefined,- scope: "organization:update",- });-const createFilterMutation =api.naturalLanguageFilters.createCompletion.useMutation();@@ -68,30 +63,10 @@ export function DataTableAIFilters({// When AI features are not enabledif (!organization?.aiFeaturesEnabled) {return (- <div className="flex flex-col gap-3">- <p className="text-muted-foreground text-sm">- AI-powered filters use natural language to generate deterministic- filters.- {!hasAdminAccess &&- " Ask your organization administrator to enable AI features in organization settings."}- </p>- {hasAdminAccess && organization?.id && (- <Button- onClick={() => {- window.open(- `/organization/${organization.id}/settings`,- "_blank",- );- }}- variant="outline"- size="sm"- className="w-fit"- >- Enable in Organization Settings- <ExternalLink className="ml-2 h-4 w-4" />- </Button>- )}- </div>+ <AIFeaturesDisabledNotice organizationId={organization?.id}>+ AI-powered filters use natural language to generate deterministic+ filters.+ </AIFeaturesDisabledNotice>);}diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsxindex 9236168028..d32c1aac9a 100644--- a/web/src/features/filters/components/filter-builder.tsx+++ b/web/src/features/filters/components/filter-builder.tsx@@ -65,6 +65,7 @@ import {} from "@/src/components/ui/input-command";import { useQueryProject } from "@/src/features/projects/hooks";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";+import { openAIFeaturesSettings } from "@/src/features/organizations/components/AIFeaturesDisabledNotice";/*** Extended ColumnDefinition with optional alert for UI display.@@ -502,10 +503,7 @@ function FilterBuilderForm({<ButtononClick={() => {if (!organization?.aiFeaturesEnabled && organization?.id) {- window.open(- `/organization/${organization.id}/settings`,- "_blank",- );+ openAIFeaturesSettings(organization.id);} else {setShowAiFilter(!showAiFilter);}@@ -513,7 +511,6 @@ function FilterBuilderForm({type="button"variant="outline"size="default"- disabled={false}title={!organization?.aiFeaturesEnabled? "AI features are disabled for your organization. Click to enable them in organization settings."diff --git a/web/src/features/in-app-agent/AGENTS.md b/web/src/features/in-app-agent/AGENTS.mdnew file mode 100644index 0000000000..dac65b3eeb--- /dev/null+++ b/web/src/features/in-app-agent/AGENTS.md@@ -0,0 +1,3 @@+## Working with AG-UI+* always check the AG-UI docs here: https://docs.ag-ui.com/llms.txt+* always append .md when trying to access the docs, a lot more precisediff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsxindex 08c0253af7..36069cea4d 100644--- a/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentDrawer.tsx@@ -22,13 +22,34 @@ type ControlledInAppAgentDrawerProps =export function ControlledInAppAgentDrawer(props: ControlledInAppAgentDrawerProps,) {- const { error, isRunning, messages, submit } = useInAppAiAgent();+ const {+ conversations,+ error,+ hasMoreConversations,+ isLoadingMoreConversations,+ isRunning,+ isSelectedConversationHydrating,+ isSubmitting,+ loadMoreConversations,+ messages,+ selectConversation,+ selectedConversationId,+ submit,+ } = useInAppAiAgent();+ const isInputDisabled =+ isRunning || isSubmitting || isSelectedConversationHydrating;+const drawerMessages = useMemo(() => {const parsedMessages = z.array(AgUiMessageSchema).parse(messages);const mappedMessages = parsedMessages.flatMap((message, index): InAppAgentDrawerMessage[] => {- if (message.role === "system" || message.role === "activity") {+ if (+ message.role === "system" ||+ message.role === "developer" ||+ message.role === "tool" ||+ message.role === "activity"+ ) {return [];}@@ -116,8 +137,15 @@ export function ControlledInAppAgentDrawer(return (<InAppAgentDrawererror={error}- isRunning={isRunning}+ isInputDisabled={isInputDisabled}messages={drawerMessages}+ conversations={conversations}+ hasMoreConversations={hasMoreConversations}+ isLoadingMoreConversations={isLoadingMoreConversations}+ selectedConversationId={selectedConversationId}+ onLoadMoreConversations={loadMoreConversations}+ onSelectConversation={selectConversation}+ onNewConversation={() => selectConversation(null)}onSubmit={submit}{...closeButtonProps}/>diff --git a/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsxindex be7a09f359..744c5fe448 100644--- a/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentDrawer.stories.tsx@@ -2,6 +2,19 @@ import preview from "../../../../.storybook/preview";import { fn } from "storybook/test";import { InAppAgentDrawer } from "./InAppAgentDrawer";+const conversations = [+ {+ id: "conversation-1",+ title: "Latency outliers",+ updatedAt: new Date("2026-05-19T10:00:00.000Z"),+ },+ {+ id: "conversation-2",+ title: "Score correlation",+ updatedAt: new Date("2026-05-19T09:00:00.000Z"),+ },+];+const meta = preview.meta({component: InAppAgentDrawer,parameters: {@@ -16,7 +29,14 @@ const meta = preview.meta({],args: {error: null,- isRunning: false,+ isInputDisabled: false,+ conversations,+ hasMoreConversations: false,+ isLoadingMoreConversations: false,+ selectedConversationId: undefined,+ onLoadMoreConversations: fn(),+ onNewConversation: fn(),+ onSelectConversation: fn(),onClose: fn(),onSubmit: fn(),showCloseButton: true,@@ -31,6 +51,7 @@ export const Empty = meta.story({export const Conversation = meta.story({args: {+ selectedConversationId: "conversation-1",messages: [{id: "user-1",@@ -104,7 +125,7 @@ export const LoadingResponse = meta.story({export const Connecting = meta.story({args: {- isRunning: true,+ isInputDisabled: true,messages: [{id: "user-1",diff --git a/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx b/web/src/features/in-app-agent/components/InAppAgentDrawer.tsxindex 77e17cf506..e676418b59 100644--- a/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentDrawer.tsx@@ -1,9 +1,17 @@"use client";import { type KeyboardEvent, useEffect, useRef, useState } from "react";-import { PanelRightClose, SendHorizontal } from "lucide-react";+import { PanelRightClose, Plus, SendHorizontal } from "lucide-react";import { Button } from "@/src/components/ui/button";import { cn } from "@/src/utils/tailwind";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";import {InAppAgentMessage,type InAppAgentMessageContent,@@ -11,6 +19,8 @@ import {} from "./InAppAgentMessage";const AUTO_SCROLL_THRESHOLD_PX = 200;+const NEW_CONVERSATION_VALUE = "__new__";+const LOAD_MORE_CONVERSATIONS_VALUE = "__load_more__";export type InAppAgentDrawerMessage = {id: string;@@ -18,6 +28,12 @@ export type InAppAgentDrawerMessage = {content: InAppAgentMessageContent[];};+export type InAppAgentDrawerConversation = {+ id: string;+ title: string | null;+ updatedAt: Date;+};+type InAppAgentDrawerCloseButtonProps =| {showCloseButton: false;@@ -30,13 +46,32 @@ type InAppAgentDrawerCloseButtonProps =export type InAppAgentDrawerProps = {error: string | null;- isRunning: boolean;+ isInputDisabled: boolean;messages: InAppAgentDrawerMessage[];- onSubmit: (input: string) => void;+ conversations: InAppAgentDrawerConversation[];+ hasMoreConversations: boolean;+ isLoadingMoreConversations: boolean;+ selectedConversationId: string | undefined;+ onLoadMoreConversations: () => void;+ onSelectConversation: (conversationId: string) => void;+ onNewConversation: () => void;+ onSubmit: (input: string) => Promise<boolean>;} & InAppAgentDrawerCloseButtonProps;export function InAppAgentDrawer(props: InAppAgentDrawerProps) {- const { error, isRunning, messages, onSubmit } = props;+ const {+ conversations,+ error,+ hasMoreConversations,+ isInputDisabled,+ isLoadingMoreConversations,+ messages,+ onLoadMoreConversations,+ onNewConversation,+ onSelectConversation,+ onSubmit,+ selectedConversationId,+ } = props;const viewportRef = useRef<HTMLDivElement>(null);const scrollPositionRef = useRef<{scrollHeight: number;@@ -85,10 +120,70 @@ export function InAppAgentDrawer(props: InAppAgentDrawerProps) {return (<section className="bg-background flex h-full min-w-0 flex-col"><header className="bg-background flex h-11.25 shrink-0 items-center justify-between border-b px-3">- <div className="flex min-w-0 items-center gap-2">+ <div className="flex min-w-0 flex-1 items-center gap-2"><div className="min-w-0"><p className="truncate text-sm font-semibold">AI Assistant</p></div>+ <Select+ value={selectedConversationId ?? NEW_CONVERSATION_VALUE}+ onValueChange={(value) => {+ if (value === NEW_CONVERSATION_VALUE) {+ onNewConversation();+ return;+ }++ if (value === LOAD_MORE_CONVERSATIONS_VALUE) {+ return;+ }++ onSelectConversation(value);+ }}+ disabled={isInputDisabled}+ >+ <SelectTrigger+ aria-label="Select agent conversation"+ className="h-8 max-w-52 min-w-0 flex-1"+ >+ <SelectValue placeholder="New conversation" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={NEW_CONVERSATION_VALUE}>+ New conversation+ </SelectItem>+ {conversations.map((conversation) => (+ <SelectItem key={conversation.id} value={conversation.id}>+ {conversation.title?.trim() || "Untitled conversation"}+ </SelectItem>+ ))}+ {hasMoreConversations ? (+ <>+ <SelectSeparator />+ <SelectItem+ value={LOAD_MORE_CONVERSATIONS_VALUE}+ className="h-8"+ disabled={isLoadingMoreConversations}+ onSelect={(event) => {+ event.preventDefault();+ onLoadMoreConversations();+ }}+ >+ {isLoadingMoreConversations ? "Loading..." : "Load more"}+ </SelectItem>+ </>+ ) : null}+ </SelectContent>+ </Select>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="h-8 w-8 shrink-0"+ onClick={onNewConversation}+ disabled={isInputDisabled}+ aria-label="Start new AI agent conversation"+ >+ <Plus className="h-4 w-4" />+ </Button></div>{props.showCloseButton !== false && (<Button@@ -163,12 +258,21 @@ export function InAppAgentDrawer(props: InAppAgentDrawerProps) {const content = input.trim();- if (!content || isRunning) {+ if (!content || isInputDisabled) {return;}- onSubmit(content);- setInput("");+ onSubmit(content)+ .then((accepted) => {+ if (!accepted) {+ return;+ }++ setInput((currentInput) =>+ currentInput.trim() === content ? "" : currentInput,+ );+ })+ .catch(() => undefined);}}><textarea@@ -185,7 +289,7 @@ export function InAppAgentDrawer(props: InAppAgentDrawerProps) {event.currentTarget.form?.requestSubmit();}}}- disabled={isRunning}+ disabled={isInputDisabled}aria-label="Ask about Langfuse"placeholder="Ask about Langfuse..."rows={1}@@ -196,7 +300,7 @@ export function InAppAgentDrawer(props: InAppAgentDrawerProps) {size="icon"className="h-10 w-10 rounded-md"aria-label="Send message"- disabled={isRunning || !input.trim()}+ disabled={isInputDisabled || !input.trim()}><SendHorizontal className="h-4 w-4" /></Button>diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 4454290009..fd5392c55f 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -12,52 +12,76 @@ import {} from "react";import { HttpAgent } from "@ag-ui/client";import { useRouter } from "next/router";-import { z } from "zod";++import useSessionStorage from "@/src/components/useSessionStorage";import { env } from "@/src/env.mjs";-import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import {+ createInAppAgentConversationId,+ createInAppAgentMessageId,+} from "@/src/features/in-app-agent/ids";import {AgUiMessageSchema,- InAppAgentRuntimeStateSchema,- PersistentInAppAiAgentSessionSchema,- type InAppAgentRuntimeState,- type PersistentInAppAiAgentSession,type AgUiMessage,+ type InAppAgentRuntimeState,} from "@/src/features/in-app-agent/schema";-import useSessionStorage from "@/src/components/useSessionStorage";--const SESSION_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-session";-const OPEN_STORAGE_KEY = "langfuse:in-app-ai-agent-open";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { api } from "@/src/utils/api";-const getInitialAgentState = (projectId: string): InAppAgentRuntimeState => ({- type: "newSession",- projectId,-});+const SELECTED_CONVERSATION_STORAGE_KEY_PREFIX =+ "langfuse:in-app-ai-agent-selected-conversation";+const OPEN_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-open";-const getEmptySession = (projectId: string): PersistentInAppAiAgentSession => ({- state: getInitialAgentState(projectId),- messages: [],-});+const getConversationAgentState = (+ projectId: string,+ conversationId: string,+ isNewConversation: boolean,+): InAppAgentRuntimeState =>+ isNewConversation+ ? { type: "newConversation", projectId }+ : { type: "existingConversation", projectId, conversationId };const NOOP_CONTEXT: InAppAiAgentContextType = {isAvailable: false,open: false,setOpen: () => undefined,isRunning: false,+ isSubmitting: false,+ isSelectedConversationHydrating: false,error: null,messages: [],- submit: () => undefined,+ conversations: [],+ hasMoreConversations: false,+ isLoadingMoreConversations: false,+ selectedConversationId: undefined,+ loadMoreConversations: () => undefined,+ selectConversation: () => undefined,+ submit: async () => false,};-type InAppAiAgentMessage = Extract<AgUiMessage, { role: "user" | "assistant" }>;+type InAppAiAgentMessage = AgUiMessage;++export type InAppAiAgentConversation = {+ id: string;+ title: string | null;+ updatedAt: Date;+};type InAppAiAgentContextType = {isAvailable: boolean;open: boolean;setOpen: Dispatch<SetStateAction<boolean>>;isRunning: boolean;+ isSubmitting: boolean;+ isSelectedConversationHydrating: boolean;error: string | null;messages: InAppAiAgentMessage[];- submit: (content: string) => void;+ conversations: InAppAiAgentConversation[];+ hasMoreConversations: boolean;+ isLoadingMoreConversations: boolean;+ selectedConversationId: string | undefined;+ loadMoreConversations: () => void;+ selectConversation: (conversationId: string | null) => void;+ submit: (content: string) => Promise<boolean>;};const InAppAiAgentContext = createContext<InAppAiAgentContextType | null>(null);@@ -81,6 +105,7 @@ export function InAppAiAgentProvider({return (<InAppAiAgentProjectProvider+ key={projectId}projectId={projectId}defaultOpen={defaultOpen}>@@ -95,15 +120,13 @@ function InAppAiAgentProjectProvider({defaultOpen,}: InAppAiAgentProviderProps & { projectId: string }) {const [open, setOpen] = useSessionStorage<boolean>(- OPEN_STORAGE_KEY,+ `${OPEN_STORAGE_KEY_PREFIX}:${projectId}`,defaultOpen ?? false,);return (<InAppAiAgentProviderInner- key={projectId}projectId={projectId}- sessionStorageKey={`${SESSION_STORAGE_KEY_PREFIX}:${projectId}`}open={open}setOpen={setOpen}>@@ -114,7 +137,6 @@ function InAppAiAgentProjectProvider({type InAppAiAgentProviderInnerProps = PropsWithChildren<{projectId: string;- sessionStorageKey: string;open: boolean;setOpen: Dispatch<SetStateAction<boolean>>;}>;@@ -122,201 +144,336 @@ type InAppAiAgentProviderInnerProps = PropsWithChildren<{function InAppAiAgentProviderInner({children,projectId,- sessionStorageKey,open,setOpen,}: InAppAiAgentProviderInnerProps) {- const [storedSession, setStoredSession] =- useSessionStorage<PersistentInAppAiAgentSession>(- sessionStorageKey,- getEmptySession(projectId),- );-+ const utils = api.useUtils();+ const [selectedConversationId, setSelectedConversationId] = useSessionStorage<+ string | null+ >(`${SELECTED_CONVERSATION_STORAGE_KEY_PREFIX}:${projectId}`, null);+ const [messages, setMessages] = useState<InAppAiAgentMessage[]>([]);const [isRunning, setIsRunning] = useState(false);+ const [isSubmitting, setIsSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);const agentRef = useRef<HttpAgent | null>(null);+ const intentionalAbortRef = useRef(false);+ const submitInFlightRef = useRef(false);const subscriptionRef = useRef<ReturnType<HttpAgent["subscribe"]> | null>(null,);- const restoredSession = useMemo(() => {- const result = PersistentInAppAiAgentSessionSchema.safeParse(storedSession);-- return result.success ? result.data : getEmptySession(projectId);- }, [projectId, storedSession]);+ const conversationListQuery =+ api.inAppAgent.listConversations.useInfiniteQuery(+ { projectId },+ {+ enabled: open,+ getNextPageParam: (lastPage) => lastPage.nextCursor,+ },+ );+ const conversationQuery = api.inAppAgent.getConversation.useQuery(+ {+ projectId,+ conversationId: selectedConversationId ?? "",+ },+ {+ enabled: open && Boolean(selectedConversationId) && !isSubmitting,+ },+ );- const restoredMessages = useMemo(- () => restoredSession.messages.filter(isAgentConversationMessage),- [restoredSession.messages],+ const conversations = useMemo(+ () =>+ conversationListQuery.data?.pages.flatMap((page) => page.conversations) ??+ [],+ [conversationListQuery.data?.pages],);+ const hasMoreConversations = conversationListQuery.hasNextPage === true;+ const isLoadingMoreConversations = conversationListQuery.isFetchingNextPage;+ const fetchNextConversationsPage = conversationListQuery.fetchNextPage;+ const loadMoreConversations = useCallback(() => {+ if (!hasMoreConversations || isLoadingMoreConversations) {+ return;+ }- const persistSession = useCallback(- (params: {- agent: { threadId: string };- messages: readonly unknown[];- state: unknown;- }) => {- const state = InAppAgentRuntimeStateSchema.safeParse(params.state);-- setStoredSession((previousStoredSession) => {- const previousSession = PersistentInAppAiAgentSessionSchema.safeParse(- previousStoredSession,- );- const previousMessages = previousSession.success- ? previousSession.data.messages.filter(isAgentConversationMessage)- : [];- const incomingMessages = z- .array(AgUiMessageSchema)- .safeParse(params.messages);-- const incomingMessageIds = new Set(- incomingMessages.success- ? incomingMessages.data.map((message) => message.id)- : [],- );- const result = PersistentInAppAiAgentSessionSchema.safeParse({- threadId: params.agent.threadId,- state: state.success ? state.data : getInitialAgentState(projectId),- messages: incomingMessages.success- ? [- ...previousMessages.filter(- (message) => !incomingMessageIds.has(message.id),- ),- ...incomingMessages.data.filter(isAgentConversationMessage),- ]- : previousMessages,- });+ fetchNextConversationsPage().catch((error) => {+ const errorMessage = getAgentErrorMessage(error);+ showErrorToast("Failed to load conversations", errorMessage);+ console.error("Failed to load in-app agent conversations", error);+ });+ }, [+ fetchNextConversationsPage,+ hasMoreConversations,+ isLoadingMoreConversations,+ ]);++ useEffect(() => {+ if (!conversationListQuery.error) {+ return;+ }++ const errorMessage = getAgentErrorMessage(conversationListQuery.error);+ showErrorToast("Failed to load conversations", errorMessage);+ console.error("Failed to load in-app agent conversations", {+ error: conversationListQuery.error,+ projectId,+ });+ }, [conversationListQuery.error, projectId]);++ const isSelectedConversationHydrating =+ Boolean(selectedConversationId) &&+ conversationQuery.isLoading &&+ !conversationQuery.data;+ const resetAgent = useCallback(() => {+ if (agentRef.current?.isRunning) {+ intentionalAbortRef.current = true;+ }++ subscriptionRef.current?.unsubscribe();+ subscriptionRef.current = null;+ agentRef.current?.abortRun();+ agentRef.current = null;+ }, []);++ // Hydrate local state from the selected persisted conversation once it loads.+ useEffect(() => {+ if (!selectedConversationId) {+ if (!isRunning) {+ resetAgent();+ setMessages([]);+ }+ return;+ }++ if (!conversationQuery.data || isRunning) {+ return;+ }++ const storedMessages = conversationQuery.data.messages.filter(+ isAgentConversationMessage,+ );- return result.success ? result.data : getEmptySession(projectId);+ if (messages.length > storedMessages.length) {+ return;+ }++ resetAgent();+ // TODO: Avoid replacing hydrated messages when only server-generated ids+ // differ from optimistic client ids; this can cause a small post-run flicker.+ setMessages(storedMessages);+ }, [+ conversationQuery.data,+ isRunning,+ messages.length,+ resetAgent,+ selectedConversationId,+ ]);++ // Clear local selection when the selected conversation cannot be loaded.+ useEffect(() => {+ if (!selectedConversationId || isRunning || !conversationQuery.error) {+ return;+ }++ if (conversationQuery.error.data?.code !== "NOT_FOUND") {+ console.error("Failed to load in-app agent conversation", {+ error: conversationQuery.error,+ projectId,+ conversationId: selectedConversationId,});- },- [projectId, setStoredSession],- );+ return;+ }++ resetAgent();+ setMessages([]);+ setSelectedConversationId(null);+ }, [+ conversationQuery.error,+ isRunning,+ projectId,+ resetAgent,+ selectedConversationId,+ setSelectedConversationId,+ ]);++ useEffect(() => {+ return () => {+ resetAgent();+ };+ }, [resetAgent]);++ const ensureSubscription = useCallback((agent: HttpAgent) => {+ if (subscriptionRef.current) {+ return;+ }++ subscriptionRef.current = agent.subscribe({+ onMessagesChanged: ({ messages }) => {+ setMessages(messages.filter(isAgentConversationMessage));+ },+ onStateChanged: ({ messages }) => {+ setMessages(messages.filter(isAgentConversationMessage));+ },+ });+ }, []);- const ensureSubscription = useCallback(- (agent: HttpAgent) => {- if (subscriptionRef.current) {- return;+ const getOrCreateAgent = useCallback(+ (+ conversationId: string,+ initialMessages: InAppAiAgentMessage[],+ isNewConversation: boolean,+ ) => {+ if (agentRef.current?.threadId === conversationId) {+ return agentRef.current;}- subscriptionRef.current = agent.subscribe({- onMessagesChanged: ({ messages, state, agent }) => {- persistSession({- agent,- messages,- state,- });- },- onStateChanged: ({ messages, state, agent }) => {- persistSession({- agent,- messages,- state,- });- },+ resetAgent();++ const agent = new HttpAgent({+ url: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`,+ threadId: conversationId,+ initialMessages,+ initialState: getConversationAgentState(+ projectId,+ conversationId,+ isNewConversation,+ ),});++ agentRef.current = agent;++ return agent;},- [persistSession],+ [projectId, resetAgent],);+ const releaseSubmitLock = useCallback(() => {+ submitInFlightRef.current = false;+ setIsSubmitting(false);+ }, []);+const runAgent = useCallback(- (agent: HttpAgent, retryOnInvalidSession = true) => {- persistSession({- agent,- messages: agent.messages,- state: agent.state,- });+ (agent: HttpAgent, conversationId: string) => {setIsRunning(true);- let retriedWithFreshSession = false;-agent.runAgent().catch((error) => {- if (retryOnInvalidSession && isInvalidSessionTokenError(error)) {- retriedWithFreshSession = true;- subscriptionRef.current?.unsubscribe();- subscriptionRef.current = null;- agent.abortRun();-- const freshAgent = new HttpAgent({- url: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`,- threadId: agent.threadId,- initialMessages: agent.messages.filter(- isAgentConversationMessage,- ),- initialState: getInitialAgentState(projectId),- });-- agentRef.current = freshAgent;- ensureSubscription(freshAgent);- runAgent(freshAgent, false);+ if (intentionalAbortRef.current) {return;}const errorMessage = getAgentErrorMessage(error);setError(errorMessage);- showErrorToast("Assistant failed", errorMessage);console.error("In-app agent drawer error", error);}).finally(() => {- if (retriedWithFreshSession) {- return;- }-setIsRunning(false);- persistSession({- agent,- messages: agent.messages,- state: agent.state,+ setMessages(agent.messages.filter(isAgentConversationMessage));+ utils.inAppAgent.listConversations.invalidate({ projectId });+ utils.inAppAgent.getConversation.invalidate({+ projectId,+ conversationId,});+ releaseSubmitLock();+ intentionalAbortRef.current = false;});},- [ensureSubscription, persistSession, projectId],+ [+ projectId,+ releaseSubmitLock,+ utils.inAppAgent.getConversation,+ utils.inAppAgent.listConversations,+ ],);- useEffect(() => {- return () => {- subscriptionRef.current?.unsubscribe();- agentRef.current?.abortRun();- };- }, []);+ const selectConversation = useCallback(+ (conversationId: string | null) => {+ setError(null);+ resetAgent();+ setMessages([]);+ setSelectedConversationId(conversationId);+ },+ [resetAgent, setSelectedConversationId],+ );const submit = useCallback(- (content: string) => {- if (!content) {- return;+ async (content: string) => {+ if (+ !content ||+ isRunning ||+ isSelectedConversationHydrating ||+ submitInFlightRef.current+ ) {+ return false;}+ submitInFlightRef.current = true;+ setIsSubmitting(true);setError(null);- // Create the agent if none exists- if (!agentRef.current) {- agentRef.current = new HttpAgent({- url: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`,- threadId: restoredSession.threadId,- initialMessages: restoredMessages,- initialState: restoredSession.state,- });- }-- const agent = agentRef.current;+ let startedRun = false;+ try {+ const isNewConversation = !selectedConversationId;+ const conversationId =+ selectedConversationId ?? createInAppAgentConversationId();++ if (isNewConversation) {+ setSelectedConversationId(conversationId);+ }++ const storedMessages =+ conversationQuery.data?.conversation.id === conversationId+ ? conversationQuery.data.messages+ : undefined;+ const initialMessages = !isNewConversation+ ? getHydratedMessages(messages, storedMessages)+ : [];+ // TODO: Avoid hydrating the full history once the agent client can send+ // only the latest user turn; the server ignores older messages.+ const agent = getOrCreateAgent(+ conversationId,+ initialMessages,+ isNewConversation,+ );- if (agent.isRunning) {- return;+ if (agent.isRunning) {+ return false;+ }++ ensureSubscription(agent);++ const userMessage = {+ id: createInAppAgentMessageId(),+ role: "user",+ content,+ } satisfies AgUiMessage;++ agent.addMessage(userMessage);+ setMessages(agent.messages.filter(isAgentConversationMessage));+ startedRun = true;+ runAgent(agent, conversationId);+ return true;+ } catch (error) {+ const errorMessage = getAgentErrorMessage(error);+ setError(errorMessage);+ console.error("Failed to start in-app agent conversation", error);+ return false;+ } finally {+ if (!startedRun) {+ releaseSubmitLock();+ }}-- ensureSubscription(agent);-- const userMessage = {- id: crypto.randomUUID(),- role: "user",- content,- } satisfies AgUiMessage;-- agent.addMessage(userMessage);- runAgent(agent);},- [ensureSubscription, restoredMessages, restoredSession, runAgent],+ [+ conversationQuery.data,+ ensureSubscription,+ getOrCreateAgent,+ isSelectedConversationHydrating,+ isRunning,+ messages,+ releaseSubmitLock,+ runAgent,+ selectedConversationId,+ setSelectedConversationId,+ ],);const value = useMemo<InAppAiAgentContextType>(@@ -325,11 +482,34 @@ function InAppAiAgentProviderInner({open,setOpen,isRunning,+ isSubmitting,+ isSelectedConversationHydrating,error,- messages: restoredMessages,+ messages,+ conversations,+ hasMoreConversations,+ isLoadingMoreConversations,+ selectedConversationId: selectedConversationId ?? undefined,+ loadMoreConversations,+ selectConversation,submit,}),- [error, isRunning, open, restoredMessages, setOpen, submit],+ [+ conversations,+ error,+ hasMoreConversations,+ isLoadingMoreConversations,+ isRunning,+ isSelectedConversationHydrating,+ isSubmitting,+ loadMoreConversations,+ messages,+ open,+ selectConversation,+ selectedConversationId,+ setOpen,+ submit,+ ],);return (@@ -339,30 +519,23 @@ function InAppAiAgentProviderInner({);}-function isInvalidSessionTokenError(error: unknown): boolean {- if (!error || typeof error !== "object") {- return false;- }-- const payload = "payload" in error ? error.payload : undefined;-- return (- typeof payload === "object" &&- payload !== null &&- "code" in payload &&- payload.code === "invalid_session_token"- );-}-function isAgentConversationMessage(message: unknown,): message is InAppAiAgentMessage {const result = AgUiMessageSchema.safeParse(message);- return (- result.success &&- (result.data.role === "user" || result.data.role === "assistant")- );+ return result.success;+}++function getHydratedMessages(+ localMessages: InAppAiAgentMessage[],+ storedMessages: readonly unknown[] | undefined,+): InAppAiAgentMessage[] {+ if (localMessages.length > 0) {+ return localMessages;+ }++ return storedMessages?.filter(isAgentConversationMessage) ?? [];}function getAgentErrorMessage(error: unknown): string {diff --git a/web/src/features/in-app-agent/ids.ts b/web/src/features/in-app-agent/ids.tsnew file mode 100644index 0000000000..210de24da9--- /dev/null+++ b/web/src/features/in-app-agent/ids.ts@@ -0,0 +1,6 @@+import { createId } from "@paralleldrive/cuid2";++// more descriptive IDs to easier debug & understand+export const createInAppAgentConversationId = () => `aconv_${createId()}`;+export const createInAppAgentRunId = () => `arun_${createId()}`;+export const createInAppAgentMessageId = () => `amsg_${createId()}`;diff --git a/web/src/features/in-app-agent/schema.ts b/web/src/features/in-app-agent/schema.tsindex ba981a7726..cc82d93362 100644--- a/web/src/features/in-app-agent/schema.ts+++ b/web/src/features/in-app-agent/schema.ts@@ -153,25 +153,16 @@ export type AgUiCustomEvent = AgUiEvent & {export const InAppAgentRuntimeStateSchema = z.discriminatedUnion("type", [z.object({- type: z.literal("newSession"),+ type: z.literal("newConversation"),projectId: z.string(),}),z.object({- type: z.literal("existingSession"),- claudeSessionToken: z.string(),+ type: z.literal("existingConversation"),+ projectId: z.string(),+ conversationId: z.string(),}),]);export type InAppAgentRuntimeState = z.infer<typeof InAppAgentRuntimeStateSchema>;--export const PersistentInAppAiAgentSessionSchema = z.object({- threadId: z.string().optional(),- state: InAppAgentRuntimeStateSchema,- messages: z.array(AgUiMessageSchema).default([]),-});--export type PersistentInAppAiAgentSession = z.infer<- typeof PersistentInAppAiAgentSessionSchema->;diff --git a/web/src/features/in-app-agent/server/agent.ts b/web/src/features/in-app-agent/server/agent.tsindex 7b711ef4df..ea83c39340 100644--- a/web/src/features/in-app-agent/server/agent.ts+++ b/web/src/features/in-app-agent/server/agent.ts@@ -7,6 +7,7 @@ import type {AgUiEvent,AgUiRunAgentInput,} from "@/src/features/in-app-agent/schema";+import { logger } from "@langfuse/shared/src/server";const ASSISTANT_TITLE = "Langfuse Assistant";const ASSISTANT_SYSTEM_PROMPT = [@@ -19,8 +20,12 @@ const MAX_AGENT_BUDGET_USD = 5;type CreateAgUiStreamOptions = {resumeSessionId?: string;+ onResumeSessionId: (sessionId: string) => unknown;+ onEvent?: (event: AgUiEvent) => void | Promise<void>;+ onComplete?: () => void | Promise<void>;+ onAbort?: () => void | Promise<void>;+ onError?: (error: unknown) => void | Promise<void>;onFinish?: () => void | Promise<void>;- createResumeStateForSessionId: (sessionId: string) => unknown;awsBedrock: {region?: string;profile?: string;@@ -77,6 +82,7 @@ export function createAgUiStream(params: {...(awsSdkLoadConfig ? { AWS_SDK_LOAD_CONFIG: awsSdkLoadConfig } : {}),},includePartialMessages: true,+ // TODO: Persist and configure an exact provider model id once we stop using SDK aliases.model: "haiku",});@@ -93,9 +99,12 @@ export function createAgUiStream(params: {: params.input;let subscription: { unsubscribe: () => void } | undefined;+ let ending = false;let closed = false;let finished = false;+ let shouldEnqueue = true;let abortHandler: (() => void) | undefined;+ let eventQueue = Promise.resolve();const removeAbortHandler = () => {if (!abortHandler) {@@ -112,40 +121,167 @@ export function createAgUiStream(params: {}finished = true;- try {- Promise.resolve(params.options.onFinish?.()).catch((error) => {- console.error("Error in agent stream cleanup:", error);+ eventQueue+ .then(() => params.options.onFinish?.())+ .catch((error) => {+ logger.error("Error in agent stream cleanup", {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ });});+ };++ const runTerminalCallback = async (+ callback: (() => void | Promise<void>) | undefined,+ errorContext: string,+ ) => {+ try {+ await callback?.();} catch (error) {- console.error("Error in agent stream cleanup:", error);+ logger.error(errorContext, {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ });}};+ const abortStream = (close?: () => void) => {+ if (ending || closed) {+ return;+ }++ ending = true;+ shouldEnqueue = false;+ removeAbortHandler();+ subscription?.unsubscribe();+ adapter.interrupt().catch(() => undefined);++ eventQueue+ .then(() =>+ runTerminalCallback(+ () => params.options.onAbort?.(),+ "Error while marking agent stream as aborted",+ ),+ )+ .then(() => {+ if (closed) {+ return;+ }++ closed = true;+ close?.();+ })+ .catch((error) => {+ closed = true;+ logger.error("Error while aborting agent stream", {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ });+ })+ .finally(finish);+ };+return new ReadableStream<Uint8Array>({start(controller) {- const closeController = () => {+ let streamedRunError: string | null = null;+ let streamedRunErrorHandled = false;++ const failStream = (error: unknown, eventType?: string) => {if (closed) {return;}+ ending = true;closed = true;removeAbortHandler();- controller.close();- finish();+ subscription?.unsubscribe();+ adapter.interrupt().catch(() => undefined);++ logger.error("Failed to persist in-app agent event", {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ eventType,+ });++ runTerminalCallback(+ () => params.options.onError?.(error),+ "Error while marking agent stream as failed",+ ).finally(finish);++ controller.error(error);};- const abort = () => {- adapter.interrupt().catch(() => undefined);- closeController();+ const enqueueEvent = (+ agUiEvent: AgUiEvent,+ afterPersist?: () => void | Promise<void>,+ ) => {+ eventQueue = eventQueue+ .then(async () => {+ if (closed) {+ return;+ }++ await params.options.onEvent?.(agUiEvent);+ await afterPersist?.();++ if (closed || !shouldEnqueue) {+ return;+ }++ controller.enqueue(+ encoder.encode(`data: ${JSON.stringify(agUiEvent)}\n\n`),+ );+ })+ .catch((error) => failStream(error, String(agUiEvent.type)));+ };++ const handleStreamedRunError = () => {+ if (streamedRunError === null || streamedRunErrorHandled) {+ return;+ }++ streamedRunErrorHandled = true;+ return params.options.onError?.(new Error(streamedRunError));+ };++ const closeController = (+ terminalCallback?: () => void | Promise<void>,+ ) => {+ if (ending || closed) {+ return;+ }++ ending = true;+ removeAbortHandler();+ eventQueue+ .then(async () => {+ if (closed) {+ return;+ }++ await terminalCallback?.();++ if (closed) {+ return;+ }++ closed = true;+ controller.close();+ })+ .catch((error) => failStream(error))+ .finally(finish);};abortHandler = () => {- subscription?.unsubscribe();- abort();+ abortStream(() => controller.close());};if (params.signal.aborted) {- abort();+ abortStream(() => controller.close());return;}@@ -153,64 +289,113 @@ export function createAgUiStream(params: {subscription = adapter.run(adapterInput).subscribe({next(event) {- if (closed || params.signal.aborted) {- abort();+ if (ending || closed) {+ return;+ }++ if (params.signal.aborted) {+ abortStream(() => controller.close());return;}for (const agUiEvent of normalizeAdapterEvent(event,- params.options.createResumeStateForSessionId,+ params.input,+ params.options.onResumeSessionId,)) {- controller.enqueue(- encoder.encode(`data: ${JSON.stringify(agUiEvent)}\n\n`),+ if (+ agUiEvent.type === EventType.RUN_ERROR &&+ streamedRunError === null+ ) {+ streamedRunError = getRunErrorMessage(agUiEvent);+ }++ enqueueEvent(+ agUiEvent,+ agUiEvent.type === EventType.RUN_ERROR+ ? handleStreamedRunError+ : undefined,);}},error(error) {- if (closed || params.signal.aborted) {- closeController();+ if (ending || closed) {return;}- console.error("Error in agent execution:", error);+ if (params.signal.aborted) {+ abortStream(() => controller.close());+ return;+ }++ if (streamedRunError !== null) {+ closeController(handleStreamedRunError);+ return;+ }+ logger.error("Error in agent execution", {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ });const message =error instanceof Error ? error.message : "Unknown assistant error";- controller.enqueue(- encoder.encode(- `data: ${JSON.stringify({- type: EventType.RUN_ERROR,- message,- } satisfies AgUiEvent)}\n\n`,- ),- );+ const runErrorEvent = {+ type: EventType.RUN_ERROR,+ threadId: params.input.threadId,+ runId: params.input.runId,+ message,+ } satisfies AgUiEvent;++ enqueueEvent(runErrorEvent, () => params.options.onError?.(error));closeController();},complete() {- closeController();+ if (ending || closed) {+ return;+ }++ if (params.signal.aborted) {+ abortStream(() => controller.close());+ return;+ }++ closeController(+ streamedRunError === null+ ? params.options.onComplete+ : handleStreamedRunError,+ );},});},cancel() {- if (closed) {- return;- }-- closed = true;- removeAbortHandler();- subscription?.unsubscribe();- adapter.interrupt().catch(() => undefined);- finish();+ abortStream();},});}function normalizeAdapterEvent(event: AgUiEvent,- createResumeStateForSessionId: (sessionId: string) => unknown,+ input: AgUiRunAgentInput,+ onResumeSessionId: (sessionId: string) => unknown,): AgUiEvent[] {+ if (event.type === EventType.MESSAGES_SNAPSHOT) {+ return [];+ }++ if (event.type === EventType.RUN_STARTED) {+ const publicEvent = { ...event };+ delete publicEvent.input;++ return [+ {+ ...publicEvent,+ ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),+ },+ ];+ }+if (isSystemInitEvent(event)) {let sessionId: string | undefined;@@ -228,20 +413,22 @@ function normalizeAdapterEvent(}}- return sessionId- ? [+ if (!sessionId) {+ return [];+ }++ return [+ {+ type: EventType.STATE_DELTA,+ delta: [{- type: EventType.STATE_DELTA,- delta: [- {- op: "replace",- path: "",- value: createResumeStateForSessionId(sessionId),- },- ],+ op: "replace",+ path: "",+ value: onResumeSessionId(sessionId),},- ]- : [];+ ],+ },+ ];}return [event];@@ -250,3 +437,9 @@ function normalizeAdapterEvent(function isSystemInitEvent(event: AgUiEvent): event is AgUiCustomEvent {return event.type === EventType.CUSTOM && event.name === "system:init";}++function getRunErrorMessage(event: AgUiEvent) {+ return typeof event.message === "string" && event.message.trim()+ ? event.message+ : "Unknown assistant error";+}diff --git a/web/src/features/in-app-agent/server/auth.ts b/web/src/features/in-app-agent/server/auth.tsdeleted file mode 100644index 31689cd849..0000000000--- a/web/src/features/in-app-agent/server/auth.ts+++ /dev/null@@ -1,144 +0,0 @@-import crypto from "crypto";-import { z } from "zod";--import { env } from "@/src/env.mjs";--const IN_APP_AGENT_SESSION_TOKEN_PREFIX = "lfcas_";-const IN_APP_AGENT_SESSION_TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60;--export class InvalidInAppAgentSessionTokenError extends Error {- constructor() {- super("Invalid in-app agent session token");- this.name = "InvalidInAppAgentSessionTokenError";- }-}--const InAppAgentSessionTokenPayloadSchema = z.object({- v: z.literal(1),- userId: z.string(),- projectId: z.string(),- threadId: z.string(),- claudeSessionId: z.string(),- exp: z.number().int(),-});--const EncodedInAppAgentSessionTokenPayloadSchema = z- .string()- .transform((payload, ctx) => {- try {- return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));- } catch {- ctx.addIssue({- code: "custom",- message: "Invalid token payload",- });- return z.NEVER;- }- })- .pipe(InAppAgentSessionTokenPayloadSchema);--const InAppAgentSessionTokenSchema = z- .string()- .startsWith(IN_APP_AGENT_SESSION_TOKEN_PREFIX)- .transform((token, ctx) => {- const [encodedPayload, signature, ...extraParts] = token- .slice(IN_APP_AGENT_SESSION_TOKEN_PREFIX.length)- .split(".");-- if (!encodedPayload || !signature || extraParts.length > 0) {- ctx.addIssue({- code: "custom",- message: "Invalid token format",- });- return z.NEVER;- }-- const payload =- EncodedInAppAgentSessionTokenPayloadSchema.safeParse(encodedPayload);-- if (!payload.success) {- ctx.addIssue({- code: "custom",- message: "Invalid token payload",- });- return z.NEVER;- }-- return {- encodedPayload,- payload: payload.data,- signature,- };- });--export function signInAppAgentSessionToken(params: {- userId: string;- projectId: string;- threadId: string;- claudeSessionId: string;-}): string {- const payload = Buffer.from(- JSON.stringify({- v: 1,- ...params,- exp:- Math.floor(Date.now() / 1000) + IN_APP_AGENT_SESSION_TOKEN_TTL_SECONDS,- }),- "utf8",- ).toString("base64url");-- return `${IN_APP_AGENT_SESSION_TOKEN_PREFIX}${payload}.${sign(payload)}`;-}--export function verifyInAppAgentSessionToken(- token: string,- params: {- userId: string;- threadId: string;- },-): {- projectId: string;- claudeSessionId: string;-} {- const parsedToken = InAppAgentSessionTokenSchema.safeParse(token);-- if (!parsedToken.success) {- throw new InvalidInAppAgentSessionTokenError();- }-- const { encodedPayload, payload, signature } = parsedToken.data;-- if (!safeEqual(signature, sign(encodedPayload))) {- throw new InvalidInAppAgentSessionTokenError();- }-- if (- payload.userId !== params.userId ||- payload.threadId !== params.threadId ||- payload.exp < Math.floor(Date.now() / 1000)- ) {- throw new InvalidInAppAgentSessionTokenError();- }-- return {- projectId: payload.projectId,- claudeSessionId: payload.claudeSessionId,- };-}--function sign(payload: string): string {- return crypto- .createHmac("sha256", env.NEXTAUTH_SECRET ?? env.SALT)- .update(payload, "utf8")- .digest("base64url");-}--function safeEqual(left: string, right: string): boolean {- const leftBuffer = Buffer.from(left);- const rightBuffer = Buffer.from(right);-- return (- leftBuffer.length === rightBuffer.length &&- crypto.timingSafeEqual(leftBuffer, rightBuffer)- );-}diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.tsindex 7547cfd2b1..903cdd4d10 100644--- a/web/src/features/in-app-agent/server/handler.ts+++ b/web/src/features/in-app-agent/server/handler.ts@@ -1,20 +1,31 @@+import { EventType } from "@ag-ui/core";import { getServerSession } from "next-auth";import { env } from "@/src/env.mjs";+import {+ createInAppAgentMessageId,+ createInAppAgentRunId,+} from "@/src/features/in-app-agent/ids";import {AgUiRunAgentInputSchema,type AgUiRunAgentInput,+ type AgUiEvent,InAppAgentRuntimeStateSchema,type AgUiMessage,} from "@/src/features/in-app-agent/schema";import { createAgUiStream } from "@/src/features/in-app-agent/server/agent";import {- InvalidInAppAgentSessionTokenError,- signInAppAgentSessionToken,- verifyInAppAgentSessionToken,-} from "@/src/features/in-app-agent/server/auth";+ createRun,+ ensureOwnedConversation,+ finishRun,+ replaceRunEvents,+ shouldFlushPersistedEvent,+ toPersistableAgentEvent,+ updateProviderSessionId,+} from "@/src/features/in-app-agent/server/persistence";import { getAuthOptions } from "@/src/server/auth";import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";+import { assertUnreachable } from "@/src/utils/types";import {BaseError,ForbiddenError,@@ -22,12 +33,11 @@ import {UnauthorizedError,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { assertUnreachable } from "@/src/utils/types";+import { logger, redis } from "@langfuse/shared/src/server";import {createAndAddApiKeysToDb,deleteApiKeyFromDb,} from "@langfuse/shared/src/server/auth/apiKeys";-import { logger, redis } from "@langfuse/shared/src/server";const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";const MAX_IN_APP_AGENT_INPUT_BYTES = 1024 * 1024;@@ -87,18 +97,22 @@ export default async function handler(request: Request) {const auth = { userId: session.user.id, user: session.user };- const { projectId, claudeSessionId } = (() => {- if (parsedState.data.type === "newSession") {+ const { projectId, conversationId } = (() => {+ if (parsedState.data.type === "newConversation") {return {projectId: parsedState.data.projectId,- claudeSessionId: undefined,+ conversationId: input.threadId,};}- return verifyInAppAgentSessionToken(parsedState.data.claudeSessionToken, {- userId: auth.userId,- threadId: input.threadId,- });+ if (parsedState.data.conversationId !== input.threadId) {+ throw new InvalidRequestError("Conversation id does not match thread");+ }++ return {+ projectId: parsedState.data.projectId,+ conversationId: parsedState.data.conversationId,+ };})();if (!isProjectMemberOrAdmin(auth.user, projectId)) {@@ -134,45 +148,172 @@ export default async function handler(request: Request) {const sanitizedInput = sanitizeAgentInput(input);const awsProfile = env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE;++ const conversation = await ensureOwnedConversation({+ prisma,+ projectId,+ conversationId,+ userId: auth.userId,+ });+return await withInAppAgentMcpApiKeyCleanup(projectId,- (mcpApiKey, cleanupMcpApiKey) => {- const stream = createAgUiStream({- input: sanitizedInput,- signal: request.signal,- options: {- resumeSessionId: claudeSessionId,- createResumeStateForSessionId: (claudeSessionId) => ({- type: "existingSession",- claudeSessionToken: signInAppAgentSessionToken({- userId: auth.userId,+ async (mcpApiKey, cleanupMcpApiKey) => {+ let runCreated = false;++ try {+ await createRun({+ prisma,+ runId: sanitizedInput.runId,+ projectId,+ conversationId: conversation.id,+ triggeredByUserId: auth.userId,+ // TODO: Store the exact provider model id, not the Claude SDK alias.+ model: "haiku",+ mcpApiKeyId: mcpApiKey.id,+ });+ runCreated = true;++ const persistedEvents: AgUiEvent[] = [+ {+ type: EventType.RUN_STARTED,+ threadId: sanitizedInput.threadId,+ runId: sanitizedInput.runId,+ ...(sanitizedInput.parentRunId+ ? { parentRunId: sanitizedInput.parentRunId }+ : {}),+ input: sanitizedInput,+ },+ ];++ const replacePersistedRunEvents = () =>+ replaceRunEvents({+ prisma,+ projectId,+ conversationId: conversation.id,+ runId: sanitizedInput.runId,+ events: persistedEvents,+ });++ await replacePersistedRunEvents();++ let providerSessionPersistence: Promise<void> = Promise.resolve();+ const persistProviderSessionId = (claudeSessionId: string) => {+ providerSessionPersistence = updateProviderSessionId({+ prisma,+ projectId,+ conversationId: conversation.id,+ providerSessionId: claudeSessionId,+ }).catch((error) => {+ logger.error("Failed to persist agent session id", {+ error,+ projectId,+ conversationId: conversation.id,+ });+ });+ };++ const finishCurrentRun = (error?: {+ errorCode: string;+ errorMessage: string;+ }) =>+ providerSessionPersistence.then(() =>+ finishRun({+ prisma,+ runId: sanitizedInput.runId,projectId,- threadId: sanitizedInput.threadId,- claudeSessionId,+ ...error,}),- }),- awsBedrock: {- region: env.LANGFUSE_AWS_BEDROCK_REGION,- ...(awsProfile ? { profile: awsProfile } : {}),+ );++ const stream = createAgUiStream({+ input: sanitizedInput,+ signal: request.signal,+ options: {+ // TODO: Claude's default session storage is pod-local. Add a shared+ // SessionStore or replay persisted history before relying on cross-pod resumes.+ resumeSessionId: conversation.providerSessionId ?? undefined,+ onResumeSessionId: (claudeSessionId) => {+ persistProviderSessionId(claudeSessionId);++ return {+ type: "existingConversation",+ projectId,+ conversationId: conversation.id,+ };+ },+ onEvent: (event) => {+ const persistedEvent = toPersistableAgentEvent(event);++ if (!persistedEvent) {+ return;+ }++ if (persistedEvent.type === EventType.RUN_STARTED) {+ return;+ }++ persistedEvents.push(persistedEvent);++ if (!shouldFlushPersistedEvent(persistedEvent)) {+ return;+ }++ return replacePersistedRunEvents();+ },+ onComplete: () =>+ replacePersistedRunEvents().then(() => finishCurrentRun()),+ onAbort: () =>+ finishCurrentRun({+ errorCode: "cancelled",+ errorMessage: "Client aborted request",+ }),+ onError: (error) =>+ finishCurrentRun({+ errorCode: "agent_error",+ errorMessage:+ error instanceof Error+ ? error.message+ : "Unknown agent error",+ }),+ onFinish: cleanupMcpApiKey,+ awsBedrock: {+ region: env.LANGFUSE_AWS_BEDROCK_REGION,+ ...(awsProfile ? { profile: awsProfile } : {}),+ },+ langfuseMcp: {+ url: getLangfuseMcpUrl(),+ publicKey: mcpApiKey.publicKey,+ secretKey: mcpApiKey.secretKey,+ },},- langfuseMcp: {- url: getLangfuseMcpUrl(),- publicKey: mcpApiKey.publicKey,- secretKey: mcpApiKey.secretKey,+ });++ return new Response(stream, {+ headers: {+ "Content-Type": "text/event-stream; charset=utf-8",+ "Content-Encoding": "none",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ "X-Accel-Buffering": "no",},- onFinish: cleanupMcpApiKey,- },- });-- return new Response(stream, {- headers: {- "Content-Type": "text/event-stream; charset=utf-8",- "Content-Encoding": "none",- "Cache-Control": "no-cache, no-transform",- Connection: "keep-alive",- "X-Accel-Buffering": "no",- },- });+ });+ } catch (error) {+ if (runCreated) {+ await finishRun({+ prisma,+ runId: sanitizedInput.runId,+ projectId,+ errorCode: "init_failed",+ errorMessage:+ error instanceof Error+ ? error.message+ : "Agent initialization failed",+ });+ }++ throw error;+ }},);} catch (err) {@@ -180,13 +321,6 @@ export default async function handler(request: Request) {return Response.json({ error: err.message }, { status: err.httpCode });}- if (err instanceof InvalidInAppAgentSessionTokenError) {- return Response.json(- { error: err.message, code: "invalid_session_token" },- { status: 400 },- );- }-throw err;}}@@ -217,7 +351,7 @@ async function withInAppAgentMcpApiKeyCleanup<T>(createResponse: (mcpApiKey: Awaited<ReturnType<typeof createInAppAgentMcpApiKey>>,cleanupMcpApiKey: () => Promise<void>,- ) => T,+ ) => T | Promise<T>,): Promise<T> {const mcpApiKey = await createInAppAgentMcpApiKey(projectId);let cleanupPromise: Promise<void> | undefined;@@ -237,7 +371,7 @@ async function withInAppAgentMcpApiKeyCleanup<T>(};try {- return createResponse(mcpApiKey, cleanupMcpApiKey);+ return await createResponse(mcpApiKey, cleanupMcpApiKey);} catch (err) {await cleanupMcpApiKey().catch((cleanupErr) => {logger.error("Failed to clean up in-app agent MCP API key", cleanupErr);@@ -259,7 +393,11 @@ async function cleanupInAppAgentMcpApiKey(params: {});}-function sanitizeAgentInput(input: AgUiRunAgentInput): AgUiRunAgentInput {+type SanitizedAgentInput = AgUiRunAgentInput & {+ messages: [SanitizedUserMessage];+};++function sanitizeAgentInput(input: AgUiRunAgentInput): SanitizedAgentInput {const lastUserMessage = getLastUserMessage(input.messages);if (!lastUserMessage) {@@ -268,19 +406,25 @@ function sanitizeAgentInput(input: AgUiRunAgentInput): AgUiRunAgentInput {return {threadId: input.threadId,- runId: input.runId,+ runId: createInAppAgentRunId(),...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),state: null,- messages: [lastUserMessage],+ messages: [{ ...lastUserMessage, id: createInAppAgentMessageId() }],tools: [],context: [],forwardedProps: {},};}+type SanitizedUserMessage = {+ id: string;+ role: "user";+ content: string;+};+function getLastUserMessage(messages: AgUiMessage[],-): Extract<AgUiMessage, { role: "user" }> | undefined {+): SanitizedUserMessage | undefined {const lastMessage = messages.at(-1);if (lastMessage?.role !== "user") {diff --git a/web/src/features/in-app-agent/server/persistence.ts b/web/src/features/in-app-agent/server/persistence.tsnew file mode 100644index 0000000000..3ab7ba317b--- /dev/null+++ b/web/src/features/in-app-agent/server/persistence.ts@@ -0,0 +1,690 @@+import { EventType } from "@ag-ui/core";+import { compactEvents } from "@ag-ui/client";++import { LangfuseConflictError, LangfuseNotFoundError } from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";+import type {+ InAppAgentConversation,+ Prisma,+ PrismaClient,+} from "@langfuse/shared/src/db";++import {+ AgUiMessageSchema,+ type AgUiEvent,+ type AgUiMessage,+} from "@/src/features/in-app-agent/schema";++// 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.+const ACTIVE_RUN_STALE_AFTER_MS = 150 * 1000;+const ACTIVE_RUN_CONFLICT_MESSAGE =+ "Assistant is already responding in this conversation";+const STALE_RUN_ERROR_CODE = "stale";+const STALE_RUN_ERROR_MESSAGE =+ "Run was marked stale before starting a new run";++export type SerializedInAppAgentConversation = {+ id: string;+ title: string | null;+ createdAt: Date;+ updatedAt: Date;+};++export function serializeConversation(+ conversation: Pick<+ InAppAgentConversation,+ "id" | "title" | "createdAt" | "updatedAt"+ >,+): SerializedInAppAgentConversation {+ return {+ id: conversation.id,+ title: conversation.title,+ createdAt: conversation.createdAt,+ updatedAt: conversation.updatedAt,+ };+}++export async function getOwnedConversationOrThrow(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+ userId: string;+}) {+ const conversation = await params.prisma.inAppAgentConversation.findFirst({+ where: {+ id: params.conversationId,+ projectId: params.projectId,+ createdByUserId: params.userId,+ deletedAt: null,+ },+ });++ if (!conversation) {+ throw new LangfuseNotFoundError("Agent conversation not found");+ }++ return conversation;+}++export async function ensureOwnedConversation(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+ userId: string;+}) {+ const existing = await params.prisma.inAppAgentConversation.findUnique({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ });++ if (existing) {+ if (existing.createdByUserId !== params.userId || existing.deletedAt) {+ throw new LangfuseNotFoundError("Agent conversation not found");+ }++ return existing;+ }++ return params.prisma.inAppAgentConversation.create({+ data: {+ id: params.conversationId,+ projectId: params.projectId,+ createdByUserId: params.userId,+ // TODO: we want to auto-generate titles based on content later+ title: getDefaultConversationTitle(new Date()),+ },+ });+}++export async function createRun(params: {+ prisma: PrismaClient;+ runId: string;+ projectId: string;+ conversationId: string;+ triggeredByUserId: string;+ model?: string;+ mcpApiKeyId?: string;+}) {+ const now = new Date();+ const staleBefore = new Date(now.getTime() - ACTIVE_RUN_STALE_AFTER_MS);++ return params.prisma.$transaction(async (tx) => {+ await lockConversation(tx, params.projectId, params.conversationId);++ // The v1 agent is foreground-only. If a stream dies before finishRun runs,+ // lazily mark the old run stale so it does not block the conversation forever.+ await tx.inAppAgentRun.updateMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ finishedAt: null,+ createdAt: { lt: staleBefore },+ },+ data: {+ finishedAt: now,+ errorCode: STALE_RUN_ERROR_CODE,+ errorMessage: STALE_RUN_ERROR_MESSAGE,+ },+ });++ const activeRun = await tx.inAppAgentRun.findFirst({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ finishedAt: null,+ },+ select: { id: true },+ });++ if (activeRun) {+ throw new LangfuseConflictError(ACTIVE_RUN_CONFLICT_MESSAGE);+ }++ return tx.inAppAgentRun.create({+ data: {+ id: params.runId,+ projectId: params.projectId,+ conversationId: params.conversationId,+ triggeredByUserId: params.triggeredByUserId,+ model: params.model,+ mcpApiKeyId: params.mcpApiKeyId,+ },+ });+ });+}++export async function finishRun(params: {+ prisma: PrismaClient;+ runId: string;+ projectId: string;+ errorCode?: string | null;+ errorMessage?: string | null;+}) {+ await params.prisma.inAppAgentRun+ .updateMany({+ where: {+ id: params.runId,+ projectId: params.projectId,+ finishedAt: null,+ },+ data: {+ finishedAt: new Date(),+ errorCode: params.errorCode ?? null,+ errorMessage: params.errorMessage ?? null,+ },+ })+ .catch((error) =>+ logger.error("Failed to finish in-app agent run", {+ error,+ runId: params.runId,+ projectId: params.projectId,+ }),+ );+}++export async function updateProviderSessionId(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+ providerSessionId: string;+}) {+ await params.prisma.inAppAgentConversation.update({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ data: { providerSessionId: params.providerSessionId },+ });+}++export async function replaceRunEvents(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+ runId: string;+ events: readonly AgUiEvent[];+}) {+ await params.prisma.$transaction(async (tx) => {+ await lockConversation(tx, params.projectId, params.conversationId);++ const activeRun = await tx.inAppAgentRun.findFirst({+ where: {+ id: params.runId,+ projectId: params.projectId,+ conversationId: params.conversationId,+ finishedAt: null,+ },+ select: { id: true },+ });++ if (!activeRun) {+ return;+ }++ await tx.inAppAgentEvent.deleteMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ runId: params.runId,+ },+ });++ const latestEvent = await tx.inAppAgentEvent.findFirst({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ },+ select: { sequenceNumber: true },+ orderBy: { sequenceNumber: "desc" },+ });++ const compactedEvents = compactEvents([...params.events]).map(+ (event, index) => ({+ projectId: params.projectId,+ conversationId: params.conversationId,+ runId: params.runId,+ sequenceNumber: (latestEvent?.sequenceNumber ?? -1) + index + 1,+ type: String(event.type),+ event: event as unknown as Prisma.InputJsonValue,+ }),+ );++ if (compactedEvents.length > 0) {+ await tx.inAppAgentEvent.createMany({+ data: compactedEvents,+ });+ }++ await tx.inAppAgentConversation.update({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ data: { updatedAt: new Date() },+ });+ });+}++export async function getConversationEvents(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+}) {+ const events = await params.prisma.inAppAgentEvent.findMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ },+ orderBy: { sequenceNumber: "asc" },+ select: { event: true },+ });++ return events.map(({ event }) => event as unknown as AgUiEvent);+}++export async function getConversationMessages(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+}) {+ return getMessagesFromEvents(await getConversationEvents(params));+}++export function getMessagesFromEvents(events: readonly AgUiEvent[]) {+ const accumulator = createConversationMessageAccumulator([]);++ for (const event of events) {+ accumulator.processEvent(event);+ }++ return accumulator.getMessages();+}++export function shouldFlushPersistedEvent(event: AgUiEvent) {+ return (+ event.type === EventType.TEXT_MESSAGE_END ||+ event.type === EventType.TOOL_CALL_END ||+ event.type === EventType.TOOL_CALL_RESULT ||+ event.type === EventType.ACTIVITY_SNAPSHOT ||+ event.type === EventType.RUN_FINISHED ||+ event.type === EventType.RUN_ERROR+ );+}++export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {+ switch (event.type) {+ case EventType.RUN_STARTED: {+ const input = isRecord(event.input)+ ? {+ ...event.input,+ messages: Array.isArray(event.input.messages)+ ? parseMessages(event.input.messages)+ : [],+ tools: [],+ context: [],+ forwardedProps: {},+ }+ : undefined;++ return compactObject({+ type: event.type,+ threadId: getString(event, "threadId"),+ runId: getString(event, "runId"),+ parentRunId: getString(event, "parentRunId"),+ input,+ });+ }+ case EventType.TEXT_MESSAGE_START:+ return compactObject({+ type: event.type,+ messageId: getString(event, "messageId"),+ role: getString(event, "role"),+ name: getString(event, "name"),+ });+ case EventType.TEXT_MESSAGE_CONTENT:+ return compactObject({+ type: event.type,+ messageId: getString(event, "messageId"),+ delta: getString(event, "delta") ?? "",+ });+ case EventType.TEXT_MESSAGE_END:+ return compactObject({+ type: event.type,+ messageId: getString(event, "messageId"),+ });+ case EventType.TOOL_CALL_START:+ return compactObject({+ type: event.type,+ toolCallId: getString(event, "toolCallId"),+ toolCallName: getString(event, "toolCallName"),+ parentMessageId: getString(event, "parentMessageId"),+ });+ case EventType.TOOL_CALL_ARGS:+ return compactObject({+ type: event.type,+ toolCallId: getString(event, "toolCallId"),+ delta: getString(event, "delta") ?? "",+ });+ case EventType.TOOL_CALL_END:+ return compactObject({+ type: event.type,+ toolCallId: getString(event, "toolCallId"),+ });+ case EventType.TOOL_CALL_RESULT:+ return compactObject({+ type: event.type,+ messageId: getString(event, "messageId"),+ toolCallId: getString(event, "toolCallId"),+ content: getString(event, "content"),+ role: getString(event, "role"),+ error: getString(event, "error"),+ });+ case EventType.ACTIVITY_SNAPSHOT:+ return compactObject({+ type: event.type,+ messageId: getString(event, "messageId"),+ activityType: getString(event, "activityType"),+ content: isRecord(event.content) ? event.content : undefined,+ replace: typeof event.replace === "boolean" ? event.replace : undefined,+ });+ case EventType.RUN_FINISHED:+ return compactObject({+ type: event.type,+ threadId: getString(event, "threadId"),+ runId: getString(event, "runId"),+ });+ case EventType.RUN_ERROR:+ return compactObject({+ type: event.type,+ threadId: getString(event, "threadId"),+ runId: getString(event, "runId"),+ message: getString(event, "message"),+ code: getString(event, "code"),+ });+ default:+ return null;+ }+}++export function createConversationMessageAccumulator(+ initialMessages: readonly AgUiMessage[],+) {+ const messages: AgUiMessage[] = [];+ const messageIndexes = new Map<string, number>();+ const textDrafts = new Map<string, { id: string; content: string }>();+ const toolCallDrafts = new Map<+ string,+ {+ parentMessageId: string;+ name: string;+ args: string;+ }+ >();++ const upsertMessage = (message: AgUiMessage): boolean => {+ const parsed = AgUiMessageSchema.safeParse(message);++ if (!parsed.success) {+ return false;+ }++ const existingIndex = messageIndexes.get(parsed.data.id);++ if (existingIndex === undefined) {+ messageIndexes.set(parsed.data.id, messages.length);+ messages.push(parsed.data);+ return true;+ }++ messages[existingIndex] = mergeMessages(+ messages[existingIndex]!,+ parsed.data,+ );++ return true;+ };++ for (const message of initialMessages) {+ upsertMessage(message);+ }++ const processEvent = (event: AgUiEvent): boolean => {+ switch (event.type) {+ case EventType.RUN_STARTED: {+ if (!isRecord(event.input) || !Array.isArray(event.input.messages)) {+ break;+ }++ let changed = false;++ for (const message of parseMessages(event.input.messages)) {+ changed = upsertMessage(message) || changed;+ }++ return changed;+ }+ case EventType.TEXT_MESSAGE_START: {+ const messageId = getString(event, "messageId");++ if (messageId && getString(event, "role") === "assistant") {+ textDrafts.set(messageId, { id: messageId, content: "" });+ }+ break;+ }+ case EventType.TEXT_MESSAGE_CONTENT: {+ const messageId = getString(event, "messageId");+ const delta = getString(event, "delta") ?? "";+ const draft = messageId ? textDrafts.get(messageId) : undefined;++ if (draft) {+ draft.content += delta;+ }+ break;+ }+ case EventType.TEXT_MESSAGE_END: {+ const messageId = getString(event, "messageId");+ const draft = messageId ? textDrafts.get(messageId) : undefined;++ if (!draft) {+ break;+ }++ const changed = upsertMessage({+ id: draft.id,+ role: "assistant",+ content: draft.content,+ });++ textDrafts.delete(draft.id);+ return changed;+ }+ case EventType.TOOL_CALL_START: {+ const toolCallId = getString(event, "toolCallId");+ const parentMessageId = getString(event, "parentMessageId");+ const name = getString(event, "toolCallName");++ if (toolCallId && parentMessageId && name) {+ toolCallDrafts.set(toolCallId, {+ parentMessageId,+ name,+ args: "",+ });+ }+ break;+ }+ case EventType.TOOL_CALL_ARGS: {+ const toolCallId = getString(event, "toolCallId");+ const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;++ if (draft) {+ draft.args += getString(event, "delta") ?? "";+ }+ break;+ }+ case EventType.TOOL_CALL_END: {+ const toolCallId = getString(event, "toolCallId");+ const draft = toolCallId ? toolCallDrafts.get(toolCallId) : undefined;++ if (toolCallId && draft) {+ const changed = upsertMessage({+ id: draft.parentMessageId,+ role: "assistant",+ toolCalls: [+ {+ id: toolCallId,+ type: "function",+ function: {+ name: draft.name,+ arguments: draft.args,+ },+ },+ ],+ });+ toolCallDrafts.delete(toolCallId);+ return changed;+ }+ break;+ }+ case EventType.TOOL_CALL_RESULT: {+ const messageId = getString(event, "messageId");+ const toolCallId = getString(event, "toolCallId");+ const content = getString(event, "content");++ if (messageId && toolCallId && content !== undefined) {+ return upsertMessage({+ id: messageId,+ role: "tool",+ content,+ toolCallId,+ ...(getString(event, "error")+ ? { error: getString(event, "error") }+ : {}),+ });+ }+ break;+ }+ case EventType.ACTIVITY_SNAPSHOT: {+ const messageId = getString(event, "messageId");+ const activityType = getString(event, "activityType");+ const content = event.content;++ if (messageId && activityType && isRecord(content)) {+ return upsertMessage({+ id: messageId,+ role: "activity",+ activityType,+ content,+ });+ }+ break;+ }+ default:+ break;+ }++ return false;+ };++ return {+ getMessages: () => [...messages],+ upsertMessage,+ processEvent,+ };+}++type InAppAgentTx = Prisma.TransactionClient;++async function lockConversation(+ tx: InAppAgentTx,+ projectId: string,+ conversationId: string,+) {+ await tx.$queryRaw`+ SELECT 1+ FROM "in_app_agent_conversations"+ WHERE "id" = ${conversationId}+ AND "project_id" = ${projectId}+ FOR UPDATE+ `;+}++function parseMessages(messages: unknown[]): AgUiMessage[] {+ return messages.flatMap((message) => {+ const parsed = AgUiMessageSchema.safeParse(message);+ return parsed.success ? [parsed.data] : [];+ });+}++function mergeMessages(existing: AgUiMessage, next: AgUiMessage): AgUiMessage {+ if (existing.role !== next.role) {+ return next;+ }++ if (existing.role === "assistant" && next.role === "assistant") {+ return compactObject({+ ...existing,+ ...next,+ content: next.content ?? existing.content,+ toolCalls: mergeToolCalls(existing.toolCalls, next.toolCalls),+ }) as AgUiMessage;+ }++ return next;+}++function mergeToolCalls(+ existing: Extract<AgUiMessage, { role: "assistant" }>["toolCalls"],+ next: Extract<AgUiMessage, { role: "assistant" }>["toolCalls"],+) {+ if (!existing?.length) {+ return next;+ }++ if (!next?.length) {+ return existing;+ }++ const byId = new Map(existing.map((toolCall) => [toolCall.id, toolCall]));++ for (const toolCall of next) {+ byId.set(toolCall.id, toolCall);+ }++ return Array.from(byId.values());+}++function getString(event: unknown, key: string): string | undefined {+ if (!isRecord(event)) {+ return undefined;+ }++ const value = event[key];+ return typeof value === "string" ? value : undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function compactObject<T extends Record<string, unknown>>(value: T): T {+ return Object.fromEntries(+ Object.entries(value).filter(([, entry]) => entry !== undefined),+ ) as T;+}++function getDefaultConversationTitle(date: Date) {+ const weekday = date.toLocaleDateString("en-US", { weekday: "long" });+ const hours = String(date.getHours()).padStart(2, "0");+ const minutes = String(date.getMinutes()).padStart(2, "0");++ return `Chat on ${weekday} at ${hours}:${minutes}`;+}diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.tsnew file mode 100644index 0000000000..dc37daf422--- /dev/null+++ b/web/src/features/in-app-agent/server/router.ts@@ -0,0 +1,155 @@+import { z } from "zod";++import { BaseError, ForbiddenError } from "@langfuse/shared";+import type { PrismaClient } from "@langfuse/shared/src/db";+import { env } from "@/src/env.mjs";+import {+ createTRPCRouter,+ protectedProjectProcedure,+ protectedProjectProcedureWithoutTracing,+} from "@/src/server/api/trpc";+import {+ getConversationMessages,+ getOwnedConversationOrThrow,+ serializeConversation,+} from "@/src/features/in-app-agent/server/persistence";++const CONVERSATION_LIST_LIMIT = 50;++const ConversationListCursorSchema = z.object({+ updatedAt: z.date(),+ id: z.string(),+});++const ConversationIdInput = z.object({+ projectId: z.string(),+ conversationId: z.string(),+});++export const inAppAgentRouter = createTRPCRouter({+ listConversations: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ cursor: ConversationListCursorSchema.optional(),+ limit: z.number().int().min(1).max(CONVERSATION_LIST_LIMIT).default(50),+ }),+ )+ .query(async ({ ctx, input }) => {+ await assertInAppAgentAvailable({ ctx, projectId: input.projectId });++ const conversations = await ctx.prisma.inAppAgentConversation.findMany({+ where: {+ projectId: input.projectId,+ createdByUserId: ctx.session.user.id,+ deletedAt: null,+ ...(input.cursor+ ? {+ OR: [+ { updatedAt: { lt: input.cursor.updatedAt } },+ {+ updatedAt: input.cursor.updatedAt,+ id: { lt: input.cursor.id },+ },+ ],+ }+ : {}),+ },+ orderBy: [{ updatedAt: "desc" }, { id: "desc" }],+ take: input.limit + 1,+ });++ const page = conversations.slice(0, input.limit);+ const lastConversation = page.at(-1);++ return {+ conversations: page.map(serializeConversation),+ nextCursor:+ conversations.length > input.limit && lastConversation+ ? {+ updatedAt: lastConversation.updatedAt,+ id: lastConversation.id,+ }+ : undefined,+ };+ }),++ getConversation: protectedProjectProcedureWithoutTracing+ .input(ConversationIdInput)+ .query(async ({ ctx, input }) => {+ await assertInAppAgentAvailable({ ctx, projectId: input.projectId });++ const conversation = await getOwnedConversationOrThrow({+ prisma: ctx.prisma,+ projectId: input.projectId,+ conversationId: input.conversationId,+ userId: ctx.session.user.id,+ });++ const messages = await getConversationMessages({+ prisma: ctx.prisma,+ projectId: input.projectId,+ conversationId: input.conversationId,+ });++ return {+ conversation: serializeConversation(conversation),+ messages,+ state: {+ type: "existingConversation" as const,+ projectId: input.projectId,+ conversationId: input.conversationId,+ },+ };+ }),+});++async function assertInAppAgentAvailable({+ ctx,+ projectId,+}: {+ ctx: {+ session: {+ user: {+ admin?: boolean;+ featureFlags: { inAppAgent?: boolean };+ };+ environment: { enableExperimentalFeatures?: boolean };+ };+ prisma: PrismaClient;+ };+ projectId: string;+}) {+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ throw new BaseError(+ "PreconditionFailedError",+ 412,+ "In-app agent is not available in this environment yet.",+ true,+ );+ }++ const isInAppAgentEnabled =+ ctx.session.user.featureFlags.inAppAgent === true ||+ ctx.session.user.admin === true ||+ ctx.session.environment.enableExperimentalFeatures === true;++ if (!isInAppAgentEnabled) {+ throw new ForbiddenError("Assistant is not enabled for this user");+ }++ const project = await ctx.prisma.project.findUnique({+ where: { id: projectId },+ select: {+ organization: {+ select: {+ aiFeaturesEnabled: true,+ },+ },+ },+ });++ if (!project?.organization.aiFeaturesEnabled) {+ throw new ForbiddenError("Assistant is not enabled for this organization");+ }+}diff --git a/web/src/features/organizations/components/AIFeaturesDisabledNotice.tsx b/web/src/features/organizations/components/AIFeaturesDisabledNotice.tsxnew file mode 100644index 0000000000..4ed9deb8de--- /dev/null+++ b/web/src/features/organizations/components/AIFeaturesDisabledNotice.tsx@@ -0,0 +1,48 @@+import { type ReactNode } from "react";+import { ExternalLink } from "lucide-react";++import { Button } from "@/src/components/ui/button";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";++export function openAIFeaturesSettings(organizationId: string) {+ window.open(+ `/organization/${organizationId}/settings`,+ "_blank",+ "noopener,noreferrer",+ );+}++export function AIFeaturesDisabledNotice({+ organizationId,+ children,+}: {+ organizationId: string | undefined;+ children: ReactNode;+}) {+ const canUpdateOrgSettings = useHasOrganizationAccess({+ organizationId,+ scope: "organization:update",+ });++ return (+ <div className="flex flex-col gap-3">+ <p className="text-muted-foreground text-sm">+ {children}+ {!canUpdateOrgSettings+ ? " Ask your organization administrator to enable AI features in organization settings."+ : null}+ </p>+ {canUpdateOrgSettings && organizationId ? (+ <Button+ onClick={() => openAIFeaturesSettings(organizationId)}+ variant="outline"+ size="sm"+ className="w-fit"+ >+ Enable in Organization Settings+ <ExternalLink className="ml-2 h-4 w-4" />+ </Button>+ ) : null}+ </div>+ );+}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 310df0fd72..4be97163dd 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -56,6 +56,7 @@ import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/aimport { surveysRouter } from "@/src/server/api/routers/surveys";import { naturalLanguageFilterRouter } from "@/src/features/natural-language-filters/server/router";import { notificationPreferencesRouter } from "@/src/server/api/routers/notificationPreferences";+import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";/*** This is the primary router for your server.@@ -120,6 +121,7 @@ export const appRouter = createTRPCRouter({surveys: surveysRouter,naturalLanguageFilters: naturalLanguageFilterRouter,notificationPreferences: notificationPreferencesRouter,+ inAppAgent: inAppAgentRouter,});// export type definition of API