Skip to content

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

feat(agent): Trace in-app agent in langfuse (#13748)

Ben Bachemfcf7142f0efa
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index a664ce0953..997a2b829b 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -532,6 +532,7 @@ export enum LangfuseInternalTraceEnvironment {
LLMJudge = "langfuse-llm-as-a-judge",
CodeEval = "langfuse-code-eval",
NaturalLanguageFilter = "langfuse-natural-language-filter",
+ InAppAgent = "langfuse-in-app-agent",
}
export type ProcessedTraceEvent = {
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index 4484f7fb70..f85490f77b 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -10,6 +10,22 @@ const adapterEvents = vi.hoisted(() => ({
inputs: [] as unknown[],
}));
+const instrumentationMocks = vi.hoisted(() => {
+ const instrumentation = {
+ recordEvents: vi.fn(),
+ end: vi.fn(),
+ endWithError: vi.fn(),
+ flush: vi.fn(),
+ };
+
+ return {
+ instrumentation,
+ createInAppAgentInstrumentation: vi.fn(({ tracing }) =>
+ tracing ? instrumentation : undefined,
+ ),
+ };
+});
+
vi.mock("@ag-ui/mastra", () => ({
MastraAgent: vi.fn().mockImplementation(function () {
return {
@@ -54,7 +70,16 @@ vi.mock("@mastra/mcp", () => ({
}),
}));
+vi.mock("@/src/features/in-app-agent/server/instrumentation", () => ({
+ createInAppAgentInstrumentation:
+ instrumentationMocks.createInAppAgentInstrumentation,
+}));
+
describe("createAgUiStream", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
it("serializes valid events including adapter message snapshots", async () => {
const { createAgUiStream } =
await import("@/src/features/in-app-agent/server/agent");
@@ -133,6 +158,13 @@ describe("createAgUiStream", () => {
publicKey: "pk",
secretKey: "sk",
},
+ langfuseTracing: {
+ environment: "langfuse-in-app-agent",
+ metadata: { langfuse_project_id: "project-1" },
+ userId: "user-1",
+ traceId: "0123456789abcdef0123456789abcdef",
+ targetProjectId: "project-1",
+ },
},
});
const streamedText = await readStream(stream, (event) => {
@@ -167,6 +199,29 @@ describe("createAgUiStream", () => {
`persist:${EventType.RUN_FINISHED}`,
`stream:${EventType.RUN_FINISHED}`,
]);
+ expect(
+ instrumentationMocks.createInAppAgentInstrumentation,
+ ).toHaveBeenCalledWith({
+ input,
+ tracing: expect.objectContaining({
+ environment: "langfuse-in-app-agent",
+ targetProjectId: "project-1",
+ }),
+ });
+ expect(
+ instrumentationMocks.instrumentation.recordEvents.mock.calls.flatMap(
+ ([events]) => (events as AgUiEvent[]).map((event) => event.type),
+ ),
+ ).toEqual([
+ EventType.RUN_STARTED,
+ EventType.MESSAGES_SNAPSHOT,
+ EventType.TEXT_MESSAGE_START,
+ EventType.TEXT_MESSAGE_CONTENT,
+ EventType.TEXT_MESSAGE_END,
+ EventType.RUN_FINISHED,
+ ]);
+ expect(instrumentationMocks.instrumentation.end).toHaveBeenCalledWith({});
+ expect(instrumentationMocks.instrumentation.flush).toHaveBeenCalled();
});
it("lets HttpAgent subscribers observe streamed run errors", async () => {
diff --git a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
new file mode 100644
index 0000000000..724c259e02
--- /dev/null
+++ b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
@@ -0,0 +1,296 @@
+import { EventType } from "@ag-ui/core";
+
+import type { AgUiRunAgentInput } from "@/src/features/in-app-agent/schema";
+import { InAppAgentInstrumentation } from "@/src/features/in-app-agent/server/instrumentation";
+
+const traceId = "0123456789abcdef0123456789abcdef";
+
+const mocks = vi.hoisted(() => {
+ const toolSpan = {
+ update: vi.fn(),
+ end: vi.fn(),
+ };
+ const agentSpan = {
+ observationId: "agent-span-1",
+ traceId: "0123456789abcdef0123456789abcdef",
+ span: vi.fn(() => toolSpan),
+ update: vi.fn(),
+ end: vi.fn(),
+ };
+ const trace = {
+ span: vi.fn(() => agentSpan),
+ update: vi.fn(),
+ };
+ const handler = {
+ langfuse: {
+ trace: vi.fn(() => trace),
+ enqueue: vi.fn(),
+ },
+ };
+
+ return {
+ agentSpan,
+ toolSpan,
+ trace,
+ handler,
+ processTracedEvents: vi.fn(async () => undefined),
+ getInternalTracingHandler: vi.fn(() => ({
+ handler,
+ processTracedEvents: vi.fn(async () => undefined),
+ })),
+ };
+});
+
+vi.mock("@langfuse/shared/src/server", () => ({
+ getInternalTracingHandler: mocks.getInternalTracingHandler,
+ redis: undefined,
+ ClickHouseClientManager: {
+ getInstance: vi.fn(() => ({
+ closeAllConnections: vi.fn(async () => undefined),
+ })),
+ },
+ logger: {
+ debug: vi.fn(),
+ error: vi.fn(),
+ warn: vi.fn(),
+ },
+}));
+
+const input: AgUiRunAgentInput = {
+ threadId: "conversation-1",
+ runId: "run-1",
+ state: null,
+ messages: [{ id: "message-1", role: "user", content: "hello" }],
+ tools: [],
+ context: [],
+ forwardedProps: {},
+};
+
+describe("InAppAgentInstrumentation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("records agent output and tool calls as tool observations", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ delta: "hi ",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ delta: "there",
+ },
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-1",
+ toolCallName: "listObservations",
+ },
+ {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-1",
+ delta: '{"limit":',
+ },
+ {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-1",
+ delta: "10}",
+ },
+ {
+ type: EventType.TOOL_CALL_END,
+ toolCallId: "tool-1",
+ },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-1",
+ content: "tool result",
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ },
+ ]);
+
+ expect(mocks.getInternalTracingHandler).toHaveBeenCalledWith(
+ expect.objectContaining({
+ environment: "prod",
+ metadata: { langfuse_project_id: "project-1" },
+ targetProjectId: "project-1",
+ traceId,
+ traceName: "in-app-agent",
+ userId: "user-1",
+ }),
+ );
+ expect(mocks.handler.langfuse.trace).toHaveBeenCalledWith(
+ expect.objectContaining({ id: traceId, name: "in-app-agent" }),
+ );
+ expect(mocks.handler.langfuse.trace.mock.calls[0][0]).not.toHaveProperty(
+ "input",
+ );
+ expect(mocks.trace.span).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "agent-run", input: "hello" }),
+ );
+ expect(mocks.agentSpan.span).not.toHaveBeenCalled();
+ expect(mocks.handler.langfuse.enqueue).toHaveBeenCalledWith(
+ "tool-create",
+ expect.objectContaining({
+ id: "tool-1",
+ traceId,
+ parentObservationId: "agent-span-1",
+ name: "listObservations",
+ input: { limit: 10 },
+ output: "tool result",
+ startTime: expect.any(Date),
+ endTime: expect.any(Date),
+ completionStartTime: expect.any(Date),
+ metadata: expect.objectContaining({ toolCallId: "tool-1" }),
+ }),
+ );
+ expect(mocks.agentSpan.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ output: "hi there",
+ }),
+ );
+ expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
+ });
+
+ it("records run failures on the agent span", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-1",
+ toolCallName: "getTrace",
+ },
+ {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-1",
+ delta: '{"traceId":"trace-1"}',
+ },
+ ]);
+ instrumentation.endWithError(new Error("agent failed"));
+
+ expect(mocks.handler.langfuse.enqueue).toHaveBeenCalledWith(
+ "tool-create",
+ expect.objectContaining({
+ input: { traceId: "trace-1" },
+ level: "ERROR",
+ statusMessage: "agent failed",
+ metadata: expect.objectContaining({ error: "agent failed" }),
+ }),
+ );
+ expect(mocks.agentSpan.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ level: "ERROR",
+ statusMessage: "agent failed",
+ metadata: expect.objectContaining({ error: "agent failed" }),
+ }),
+ );
+ });
+
+ it("does not write trace input and output", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ delta: "second turn output",
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ },
+ ]);
+
+ expect(mocks.handler.langfuse.trace.mock.calls[0][0]).not.toHaveProperty(
+ "input",
+ );
+ expect(mocks.agentSpan.update).toHaveBeenCalledWith(
+ expect.objectContaining({ output: "second turn output" }),
+ );
+ expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
+ });
+
+ it("compacts text message chunks before recording output", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.TEXT_MESSAGE_CHUNK,
+ messageId: "assistant-message-1",
+ role: "assistant",
+ delta: "chunk ",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CHUNK,
+ messageId: "assistant-message-1",
+ delta: "output",
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ },
+ ]);
+
+ expect(mocks.agentSpan.update).toHaveBeenCalledWith(
+ expect.objectContaining({ output: "chunk output" }),
+ );
+ });
+
+ it("records reasoning text in agent span metadata", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordEvents([
+ {
+ type: EventType.REASONING_MESSAGE_CONTENT,
+ messageId: "reasoning-1",
+ delta: "Checking ",
+ },
+ {
+ type: EventType.REASONING_MESSAGE_CHUNK,
+ messageId: "reasoning-1",
+ delta: "filters",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ delta: "Done",
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ },
+ ]);
+
+ expect(mocks.agentSpan.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ output: "Done",
+ metadata: expect.objectContaining({ reasoning: "Checking filters" }),
+ }),
+ );
+ });
+
+ it("ignores events after instrumentation ended", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.end({});
+ instrumentation.recordEvents([
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-after-end",
+ toolCallName: "lateTool",
+ },
+ ]);
+
+ expect(mocks.agentSpan.span).not.toHaveBeenCalled();
+ });
+});
+
+function createInstrumentation() {
+ return new InAppAgentInstrumentation({
+ input,
+ metadata: { langfuse_project_id: "project-1" },
+ userId: "user-1",
+ traceId,
+ targetProjectId: "project-1",
+ environment: "prod",
+ });
+}
diff --git a/web/src/features/in-app-agent/server/agent.ts b/web/src/features/in-app-agent/server/agent.ts
index 67f4587113..5aae5858db 100644
--- a/web/src/features/in-app-agent/server/agent.ts
+++ b/web/src/features/in-app-agent/server/agent.ts
@@ -9,6 +9,8 @@ import type {
AgUiEvent,
AgUiRunAgentInput,
} from "@/src/features/in-app-agent/schema";
+import type { InAppAgentTracingConfig } from "@/src/features/in-app-agent/server/instrumentation";
+import { createInAppAgentInstrumentation } from "@/src/features/in-app-agent/server/instrumentation";
import { logger } from "@langfuse/shared/src/server";
const ASSISTANT_TITLE = "Langfuse Assistant";
@@ -36,6 +38,7 @@ type CreateAgUiStreamOptions = {
publicKey: string;
secretKey: string;
};
+ langfuseTracing?: InAppAgentTracingConfig;
};
export function createAgUiStream(params: {
@@ -50,6 +53,10 @@ export function createAgUiStream(params: {
const langfuseMcpAuthHeader = `Basic ${Buffer.from(
`${params.options.langfuseMcp.publicKey}:${params.options.langfuseMcp.secretKey}`,
).toString("base64")}`;
+ const instrumentation = createInAppAgentInstrumentation({
+ input: params.input,
+ tracing: params.options.langfuseTracing,
+ });
let subscription: { unsubscribe: () => void } | undefined;
let ending = false;
@@ -127,6 +134,8 @@ export function createAgUiStream(params: {
return;
}
+ instrumentation?.endWithError(error);
+ instrumentation?.flush();
ending = true;
closed = true;
shouldEnqueue = false;
@@ -216,6 +225,8 @@ export function createAgUiStream(params: {
return;
}
+ instrumentation?.end({ aborted: true });
+ instrumentation?.flush();
ending = true;
shouldEnqueue = false;
removeAbortHandler();
@@ -291,10 +302,14 @@ export function createAgUiStream(params: {
return;
}
- for (const agUiEvent of normalizeAdapterEvent(
+ const agUiEvents = normalizeAdapterEvent(
event satisfies AgUiEvent,
params.input,
- )) {
+ );
+
+ instrumentation?.recordEvents(agUiEvents);
+
+ for (const agUiEvent of agUiEvents) {
if (
agUiEvent.type === EventType.RUN_ERROR &&
streamedRunError === null
@@ -321,7 +336,10 @@ export function createAgUiStream(params: {
}
if (streamedRunError !== null) {
- closeController(handleStreamedRunError);
+ closeController(() => {
+ instrumentation?.flush();
+ return handleStreamedRunError();
+ });
return;
}
@@ -331,10 +349,12 @@ export function createAgUiStream(params: {
threadId: params.input.threadId,
});
- enqueueEvent(createRunErrorEvent(params.input, error), () =>
+ const runErrorEvent = createRunErrorEvent(params.input, error);
+ instrumentation?.recordEvents([runErrorEvent]);
+ enqueueEvent(runErrorEvent, () =>
params.options.onError?.(error),
);
- closeController();
+ closeController(() => instrumentation?.flush());
},
complete() {
if (ending || closed) {
@@ -348,8 +368,15 @@ export function createAgUiStream(params: {
closeController(
streamedRunError === null
- ? params.options.onComplete
- : handleStreamedRunError,
+ ? () => {
+ instrumentation?.end({});
+ instrumentation?.flush();
+ return params.options.onComplete?.();
+ }
+ : () => {
+ instrumentation?.flush();
+ return handleStreamedRunError();
+ },
);
},
});
@@ -370,10 +397,10 @@ export function createAgUiStream(params: {
threadId: params.input.threadId,
});
- enqueueEvent(createRunErrorEvent(params.input, error), () =>
- params.options.onError?.(error),
- );
- closeController();
+ const runErrorEvent = createRunErrorEvent(params.input, error);
+ instrumentation?.recordEvents([runErrorEvent]);
+ enqueueEvent(runErrorEvent, () => params.options.onError?.(error));
+ closeController(() => instrumentation?.flush());
});
},
cancel() {
@@ -382,6 +409,8 @@ export function createAgUiStream(params: {
}
ending = true;
+ instrumentation?.end({ aborted: true });
+ instrumentation?.flush();
shouldEnqueue = false;
removeAbortHandler();
interruptAdapter?.();
diff --git a/web/src/features/in-app-agent/server/eventCompaction.ts b/web/src/features/in-app-agent/server/eventCompaction.ts
new file mode 100644
index 0000000000..7bb07ce54c
--- /dev/null
+++ b/web/src/features/in-app-agent/server/eventCompaction.ts
@@ -0,0 +1,52 @@
+import { EventType } from "@ag-ui/core";
+
+import type { AgUiEvent } from "@/src/features/in-app-agent/schema";
+
+export function compactTextMessageChunks(
+ events: readonly AgUiEvent[],
+): AgUiEvent[] {
+ const compactedEvents: AgUiEvent[] = [];
+
+ for (const event of events) {
+ const previousEvent = compactedEvents.at(-1);
+
+ if (
+ event.type === EventType.TEXT_MESSAGE_CHUNK &&
+ previousEvent?.type === EventType.TEXT_MESSAGE_CHUNK &&
+ getString(event, "messageId") === getString(previousEvent, "messageId") &&
+ getTextChunkRole(event) === "assistant" &&
+ getTextChunkRole(previousEvent) === "assistant"
+ ) {
+ compactedEvents[compactedEvents.length - 1] = {
+ ...previousEvent,
+ delta:
+ (getString(previousEvent, "delta") ?? "") +
+ (getString(event, "delta") ?? ""),
+ };
+ continue;
+ }
+
+ compactedEvents.push(event);
+ }
+
+ return compactedEvents;
+}
+
+function getTextChunkRole(event: unknown) {
+ const role = getString(event, "role");
+
+ return role === undefined || role === "assistant" ? "assistant" : role;
+}
+
+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);
+}
diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.ts
index f385f769b1..a4b9e869ac 100644
--- a/web/src/features/in-app-agent/server/handler.ts
+++ b/web/src/features/in-app-agent/server/handler.ts
@@ -137,6 +137,7 @@ export default async function handler(request: Request) {
organization: {
select: {
aiFeaturesEnabled: true,
+ aiTelemetryEnabled: true,
},
},
},
@@ -151,6 +152,7 @@ export default async function handler(request: Request) {
const sanitizedInput = sanitizeAgentInput(input);
const awsProfile = env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE;
const bedrockModelId = env.LANGFUSE_AWS_BEDROCK_MODEL;
+ const targetProjectId = env.LANGFUSE_AI_FEATURES_PROJECT_ID;
if (!bedrockModelId) {
throw new BaseError(
@@ -281,6 +283,28 @@ export default async function handler(request: Request) {
publicKey: mcpApiKey.publicKey,
secretKey: mcpApiKey.secretKey,
},
+ langfuseTracing:
+ project.organization.aiTelemetryEnabled && targetProjectId
+ ? {
+ targetProjectId,
+ environment: "langfuse-in-app-agent",
+ userId: auth.userId,
+ traceId: conversation.id,
+ metadata: {
+ langfuse_ai_feature: "in-app-agent",
+ langfuse_user_id: auth.userId,
+ langfuse_project_id: projectId,
+ conversation_id: conversation.id,
+ thread_id: sanitizedInput.threadId,
+ run_id: sanitizedInput.runId,
+ cloud_region: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ agent_session_type:
+ parsedState.data.type === "existingConversation"
+ ? "existing"
+ : "new",
+ },
+ }
+ : undefined,
},
});
diff --git a/web/src/features/in-app-agent/server/instrumentation.ts b/web/src/features/in-app-agent/server/instrumentation.ts
new file mode 100644
index 0000000000..54bcc28d09
--- /dev/null
+++ b/web/src/features/in-app-agent/server/instrumentation.ts
@@ -0,0 +1,399 @@
+import { EventType } from "@ag-ui/core";
+import { getInternalTracingHandler, logger } from "@langfuse/shared/src/server";
+
+import type {
+ AgUiEvent,
+ AgUiRunAgentInput,
+} from "@/src/features/in-app-agent/schema";
+import { compactTextMessageChunks } from "@/src/features/in-app-agent/server/eventCompaction";
+
+export type InAppAgentTracingConfig = {
+ environment: string;
+ metadata: Record<string, unknown>;
+ userId: string;
+ traceId: string;
+ targetProjectId: string;
+};
+
+export type InAppAgentInstrumentationParams = {
+ input: AgUiRunAgentInput;
+ tracing?: InAppAgentTracingConfig;
+};
+
+const IN_APP_AGENT_TRACE_NAME = "in-app-agent";
+const IN_APP_AGENT_SPAN_NAME = "agent-run";
+type InternalTracingHandler = ReturnType<typeof getInternalTracingHandler>;
+type InAppAgentTrace = ReturnType<
+ InternalTracingHandler["handler"]["langfuse"]["trace"]
+>;
+type InAppAgentSpan = ReturnType<InAppAgentTrace["span"]>;
+type InAppAgentLangfuse = InternalTracingHandler["handler"]["langfuse"];
+type ToolObservationBody = {
+ id: string;
+ traceId: string;
+ parentObservationId: string | null;
+ name: string;
+ startTime: Date;
+ endTime: Date;
+ completionStartTime: Date;
+ input?: unknown;
+ output?: unknown;
+ level?: "ERROR";
+ statusMessage?: string;
+ metadata?: Record<string, unknown>;
+};
+
+export function createInAppAgentInstrumentation({
+ input,
+ tracing,
+}: InAppAgentInstrumentationParams) {
+ if (!tracing?.targetProjectId) {
+ return undefined;
+ }
+
+ try {
+ return new InAppAgentInstrumentation({
+ input,
+ metadata: tracing.metadata,
+ userId: tracing.userId,
+ traceId: tracing.traceId,
+ targetProjectId: tracing.targetProjectId,
+ environment: tracing.environment,
+ });
+ } catch (error) {
+ logger.warn("Failed to initialize in-app agent Langfuse tracing", error);
+ return undefined;
+ }
+}
+
+export class InAppAgentInstrumentation {
+ private readonly processTracedEvents: () => Promise<void>;
+ private readonly langfuse: InAppAgentLangfuse;
+ private readonly trace: InAppAgentTrace;
+ private readonly span: InAppAgentSpan;
+ private readonly toolSpans = new Map<
+ string,
+ {
+ name: string;
+ startTime: Date;
+ args: string;
+ argsComplete: boolean;
+ output?: unknown;
+ }
+ >();
+ private readonly metadata: Record<string, unknown>;
+ private output = "";
+ private reasoning = "";
+ private ended = false;
+
+ constructor(params: {
+ input: AgUiRunAgentInput;
+ metadata: Record<string, unknown>;
+ userId: string;
+ traceId: string;
+ targetProjectId: string;
+ environment: string;
+ }) {
+ this.metadata = params.metadata;
+
+ const { handler, processTracedEvents } = getInternalTracingHandler({
+ targetProjectId: params.targetProjectId,
+ traceId: params.traceId,
+ traceName: IN_APP_AGENT_TRACE_NAME,
+ environment: params.environment,
+ userId: params.userId,
+ metadata: params.metadata,
+ });
+ this.processTracedEvents = processTracedEvents;
+ this.langfuse = handler.langfuse;
+
+ this.trace = this.langfuse.trace({
+ id: params.traceId,
+ name: IN_APP_AGENT_TRACE_NAME,
+ userId: params.userId,
+ sessionId: params.input.threadId,
+ metadata: params.metadata,
+ tags: ["in-app-agent"],
+ });
+ this.span = this.trace.span({
+ name: IN_APP_AGENT_SPAN_NAME,
+ input: getLastUserMessageText(params.input),
+ metadata: params.metadata,
+ });
+ }
+
+ recordEvents(events: AgUiEvent[]) {
+ if (this.ended) {
+ return;
+ }
+
+ const compactedEvents = compactTextMessageChunks(events);
+
+ for (const event of compactedEvents) {
+ this.recordEvent(event);
+ }
+ }
+
+ endWithError(error: unknown) {
+ if (this.ended) {
+ return;
+ }
+
+ const message = error instanceof Error ? error.message : String(error);
+ this.endOpenToolSpans({ error: message }, message);
+ this.span.update({
+ output: this.output || undefined,
+ level: "ERROR",
+ statusMessage: message,
+ metadata: {
+ ...this.metadata,
+ ...(this.reasoning ? { reasoning: this.reasoning } : {}),
+ error: message,
+ },
+ });
+ this.trace.update({
+ metadata: { ...this.metadata, error: message },
+ });
+ this.span.end();
+ this.ended = true;
+ }
+
+ end(params?: { aborted?: boolean; result?: unknown }) {
+ if (this.ended) {
+ return;
+ }
+
+ this.endOpenToolSpans(params?.aborted ? { aborted: true } : undefined);
+ const metadata = {
+ ...this.metadata,
+ ...(this.reasoning ? { reasoning: this.reasoning } : {}),
+ ...(params?.aborted ? { aborted: true } : {}),
+ ...(params?.result ? { result: params.result } : {}),
+ };
+ this.span.update({
+ output: this.output || undefined,
+ metadata,
+ });
+ this.trace.update({ metadata });
+ this.span.end();
+ this.ended = true;
+ }
+
+ flush() {
+ this.processTracedEvents().catch((error) => {
+ logger.warn("Failed to flush in-app agent Langfuse tracing", error);
+ });
+ }
+
+ private recordEvent(event: AgUiEvent) {
+ switch (event.type) {
+ case EventType.TEXT_MESSAGE_CHUNK:
+ case EventType.TEXT_MESSAGE_CONTENT:
+ if (typeof event.delta === "string") {
+ this.output += event.delta;
+ }
+ return;
+ case EventType.REASONING_MESSAGE_CHUNK:
+ case EventType.REASONING_MESSAGE_CONTENT:
+ if (typeof event.delta === "string") {
+ this.reasoning += event.delta;
+ }
+ return;
+ case EventType.TOOL_CALL_START:
+ this.startToolSpan(event);
+ return;
+ case EventType.TOOL_CALL_ARGS:
+ this.appendToolArgs(event);
+ return;
+ case EventType.TOOL_CALL_RESULT:
+ this.recordToolResult(event);
+ return;
+ case EventType.TOOL_CALL_END:
+ this.endToolSpan(event);
+ return;
+ case EventType.RUN_ERROR:
+ this.endWithError(
+ typeof event.message === "string"
+ ? event.message
+ : "Unknown assistant error",
+ );
+ return;
+ case EventType.RUN_FINISHED:
+ this.end({ result: event.result });
+ return;
+ case EventType.RUN_STARTED:
+ case EventType.TEXT_MESSAGE_START:
+ case EventType.TEXT_MESSAGE_END:
+ case EventType.STATE_SNAPSHOT:
+ case EventType.STATE_DELTA:
+ case EventType.MESSAGES_SNAPSHOT:
+ case EventType.ACTIVITY_SNAPSHOT:
+ case EventType.ACTIVITY_DELTA:
+ case EventType.RAW:
+ case EventType.CUSTOM:
+ case EventType.STEP_STARTED:
+ case EventType.STEP_FINISHED:
+ case EventType.REASONING_START:
+ case EventType.REASONING_MESSAGE_START:
+ case EventType.REASONING_MESSAGE_END:
+ case EventType.REASONING_END:
+ case EventType.REASONING_ENCRYPTED_VALUE:
+ return;
+ default:
+ return;
+ }
+ }
+
+ private startToolSpan(event: AgUiEvent) {
+ if (typeof event.toolCallId !== "string") {
+ return;
+ }
+
+ const name =
+ typeof event.toolCallName === "string" ? event.toolCallName : "tool-call";
+ this.toolSpans.set(event.toolCallId, {
+ name,
+ startTime: new Date(),
+ args: "",
+ argsComplete: false,
+ });
+ }
+
+ private appendToolArgs(event: AgUiEvent) {
+ if (
+ typeof event.toolCallId !== "string" ||
+ typeof event.delta !== "string"
+ ) {
+ return;
+ }
+
+ const tool = this.toolSpans.get(event.toolCallId);
+ if (tool) {
+ tool.args += event.delta;
+ }
+ }
+
+ private recordToolResult(event: AgUiEvent) {
+ if (typeof event.toolCallId !== "string") {
+ return;
+ }
+
+ const tool = this.toolSpans.get(event.toolCallId);
+ if (tool) {
+ tool.output = event.content;
+ this.endToolSpanIfComplete(event.toolCallId, tool);
+ }
+ }
+
+ private endToolSpan(event: AgUiEvent) {
+ if (typeof event.toolCallId !== "string") {
+ return;
+ }
+
+ const tool = this.toolSpans.get(event.toolCallId);
+ if (!tool) {
+ return;
+ }
+
+ tool.argsComplete = true;
+ this.endToolSpanIfComplete(event.toolCallId, tool);
+ }
+
+ private endToolSpanIfComplete(
+ toolCallId: string,
+ tool: {
+ name: string;
+ startTime: Date;
+ args: string;
+ argsComplete: boolean;
+ output?: unknown;
+ },
+ ) {
+ if (!tool.argsComplete || tool.output === undefined) {
+ return;
+ }
+
+ this.createToolObservation(toolCallId, tool);
+ this.toolSpans.delete(toolCallId);
+ }
+
+ private createToolObservation(
+ toolCallId: string,
+ tool: {
+ name: string;
+ startTime: Date;
+ args: string;
+ output?: unknown;
+ },
+ options?: {
+ metadata?: Record<string, unknown>;
+ statusMessage?: string;
+ },
+ ) {
+ const body: ToolObservationBody = {
+ id: toolCallId,
+ traceId: this.span.traceId,
+ parentObservationId: this.span.observationId,
+ name: tool.name,
+ startTime: tool.startTime,
+ endTime: new Date(),
+ completionStartTime: tool.startTime,
+ input: parseJsonOrString(tool.args),
+ output: tool.output,
+ ...(options?.statusMessage
+ ? { level: "ERROR", statusMessage: options.statusMessage }
+ : {}),
+ metadata: {
+ ...(options?.metadata ?? {}),
+ toolCallId,
+ },
+ };
+
+ (
+ this.langfuse as unknown as {
+ enqueue: (type: string, body: ToolObservationBody) => void;
+ }
+ ).enqueue("tool-create", body);
+ }
+
+ private endOpenToolSpans(
+ metadata?: Record<string, unknown>,
+ statusMessage?: string,
+ ) {
+ for (const [toolCallId, tool] of this.toolSpans.entries()) {
+ this.createToolObservation(toolCallId, tool, {
+ metadata,
+ statusMessage,
+ });
+ this.toolSpans.delete(toolCallId);
+ }
+ }
+}
+
+function getLastUserMessageText(input: AgUiRunAgentInput): string | undefined {
+ const lastMessage = input.messages.at(-1);
+
+ if (lastMessage?.role !== "user") {
+ return undefined;
+ }
+
+ if (typeof lastMessage.content === "string") {
+ return lastMessage.content;
+ }
+
+ return lastMessage.content
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
+ .join("");
+}
+
+function parseJsonOrString(value: string): unknown {
+ if (!value) {
+ return undefined;
+ }
+
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
diff --git a/web/src/features/in-app-agent/server/persistence.ts b/web/src/features/in-app-agent/server/persistence.ts
index 3283ba076c..5dc220dcda 100644
--- a/web/src/features/in-app-agent/server/persistence.ts
+++ b/web/src/features/in-app-agent/server/persistence.ts
@@ -1,5 +1,5 @@
-import { EventType } from "@ag-ui/core";
import { compactEvents } from "@ag-ui/client";
+import { EventType } from "@ag-ui/core";
import { LangfuseConflictError, LangfuseNotFoundError } from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
@@ -14,6 +14,7 @@ import {
type AgUiEvent,
type AgUiMessage,
} from "@/src/features/in-app-agent/schema";
+import { compactTextMessageChunks } from "@/src/features/in-app-agent/server/eventCompaction";
// 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.
@@ -692,34 +693,6 @@ function compactPersistedEvents(events: readonly AgUiEvent[]): AgUiEvent[] {
return compactEvents(compactTextMessageChunks(events)) as AgUiEvent[];
}
-function compactTextMessageChunks(events: readonly AgUiEvent[]): AgUiEvent[] {
- const compactedEvents: AgUiEvent[] = [];
-
- for (const event of events) {
- const previousEvent = compactedEvents.at(-1);
-
- if (
- event.type === EventType.TEXT_MESSAGE_CHUNK &&
- previousEvent?.type === EventType.TEXT_MESSAGE_CHUNK &&
- getString(event, "messageId") === getString(previousEvent, "messageId") &&
- getTextChunkRole(event) === "assistant" &&
- getTextChunkRole(previousEvent) === "assistant"
- ) {
- compactedEvents[compactedEvents.length - 1] = {
- ...previousEvent,
- delta:
- (getString(previousEvent, "delta") ?? "") +
- (getString(event, "delta") ?? ""),
- };
- continue;
- }
-
- compactedEvents.push(event);
- }
-
- return compactedEvents;
-}
-
function dropUnpairedAssistantToolCalls(messages: readonly AgUiMessage[]) {
const toolResultIds = new Set(
messages.flatMap((message) =>