Skip to content

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

feat(in-app-agent): Append-only agent run events (#15405)

Lysander Kieseldddcd5ba24dc
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
index 0d95c13a94..c9296ec7cb 100644
--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
@@ -6,8 +6,9 @@ import type {
AgUiEvent,
InAppAgentToolApprovalRequest,
} from "@/src/ee/features/in-app-agent/schema";
-import { replaceRunEvents } from "@/src/ee/features/in-app-agent/server/persistence";
+import { appendRunEvents } from "@/src/ee/features/in-app-agent/server/persistence";
import { env } from "@/src/env.mjs";
+import { InAppAgentRunStatus } from "@langfuse/shared";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import {
createAndAddApiKeysToDb,
@@ -670,9 +671,10 @@ describe("in-app agent public API route auth", () => {
triggeredByUserId: userId,
model: "haiku",
mcpApiKeyId: "api-key-old-sandbox",
+ status: InAppAgentRunStatus.RUNNING,
},
});
- await replaceRunEvents({
+ await appendRunEvents({
prisma,
projectId: project.id,
conversationId,
@@ -745,9 +747,10 @@ describe("in-app agent public API route auth", () => {
triggeredByUserId: userId,
model: "haiku",
mcpApiKeyId: "api-key-old-sandbox-resume",
+ status: InAppAgentRunStatus.RUNNING,
},
});
- await replaceRunEvents({
+ await appendRunEvents({
prisma,
projectId: project.id,
conversationId,
diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
index 6f9eabf4b8..362e233c5e 100644
--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
@@ -14,6 +14,7 @@ import { vi } from "vitest";
import { InAppAgentRunErrorCode, type Plan } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
+import type { Prisma } from "@langfuse/shared/src/db";
import {
createOrgProjectAndApiKey,
generateLLMText,
@@ -31,7 +32,8 @@ import {
finishRun,
getConversationMessagesForReplay,
maybeInferAndPersistConversationTitle,
- replaceRunEvents,
+ appendRunEvents,
+ flushPendingRunEvents,
shouldFlushPersistedEvent,
toPersistableAgentEvent,
} from "@/src/ee/features/in-app-agent/server/persistence";
@@ -174,29 +176,29 @@ describe("in-app agent persistence", () => {
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: {},
- },
- },
- ];
+ const events: AgUiEvent[] = [];
- await replaceRunEvents({
+ await appendRunEvents({
prisma,
projectId: params.projectId,
conversationId: params.conversationId,
runId: params.runId,
- events,
+ events: [
+ {
+ type: EventType.RUN_STARTED,
+ threadId: params.conversationId,
+ runId: params.runId,
+ input: {
+ threadId: params.conversationId,
+ runId: params.runId,
+ state: null,
+ messages: [userMessage],
+ tools: [],
+ context: [],
+ forwardedProps: {},
+ },
+ },
+ ],
});
return events;
@@ -221,12 +223,12 @@ describe("in-app agent persistence", () => {
return;
}
- await replaceRunEvents({
+ await flushPendingRunEvents({
prisma,
projectId: params.projectId,
conversationId: params.conversationId,
runId: params.runId,
- events: params.events,
+ pendingEvents: params.events,
});
};
@@ -288,6 +290,15 @@ describe("in-app agent persistence", () => {
messageId: "user-message-1",
content: "Please inspect today's traces for outliers",
});
+ const sentinelCreatedAt = new Date("2020-01-02T03:04:05.000Z");
+ await prisma.inAppAgentEvent.updateMany({
+ where: {
+ projectId,
+ conversationId: conversation.id,
+ runId: run1.id,
+ },
+ data: { createdAt: sentinelCreatedAt },
+ });
await appendAssistantText({
projectId,
conversationId: conversation.id,
@@ -388,12 +399,18 @@ describe("in-app agent persistence", () => {
const events = await prisma.inAppAgentEvent.findMany({
where: { projectId, conversationId: conversation.id },
orderBy: { sequenceNumber: "asc" },
- select: { sequenceNumber: true, type: true, event: true },
+ select: {
+ sequenceNumber: true,
+ type: true,
+ event: true,
+ createdAt: true,
+ },
});
expect(events.map((event) => event.sequenceNumber)).toEqual([
0, 1, 2, 3, 4, 5, 6,
]);
+ expect(events[0]?.createdAt).toEqual(sentinelCreatedAt);
expect(events.map((event) => event.type)).toEqual([
EventType.RUN_STARTED,
EventType.TEXT_MESSAGE_START,
@@ -447,6 +464,113 @@ describe("in-app agent persistence", () => {
);
});
+ // Behavior: append-written multi-run history remains replayable after the latest run is rewritten by the legacy writer.
+ // Crucial: the unflagged rollout must be safely reversible without corrupting event order or changing model context.
+ // Necessary: existing append and fencing tests do not exercise the mixed-version writer transition created by a rollback.
+ it("preserves replay when the latest append-written run is rewritten by the legacy writer", 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: "rollback-user-1",
+ content: "Inspect the first trace",
+ });
+ await appendAssistantText({
+ projectId,
+ conversationId: conversation.id,
+ runId: run1.id,
+ events: events1,
+ messageId: "rollback-assistant-1",
+ chunks: ["First trace inspected."],
+ });
+ 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: "rollback-user-2",
+ content: "Inspect the second trace",
+ });
+ await appendAssistantText({
+ projectId,
+ conversationId: conversation.id,
+ runId: run2.id,
+ events: events2,
+ messageId: "rollback-assistant-2",
+ chunks: ["Second trace inspected."],
+ });
+
+ const replayBeforeRollback = await getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ });
+ const latestRunEvents = await prisma.inAppAgentEvent.findMany({
+ where: {
+ projectId,
+ conversationId: conversation.id,
+ runId: run2.id,
+ },
+ orderBy: { sequenceNumber: "asc" },
+ select: { type: true, event: true },
+ });
+
+ await prisma.$transaction(async (tx) => {
+ await tx.inAppAgentEvent.deleteMany({
+ where: {
+ projectId,
+ conversationId: conversation.id,
+ runId: run2.id,
+ },
+ });
+ const latestRemainingEvent = await tx.inAppAgentEvent.findFirst({
+ where: { projectId, conversationId: conversation.id },
+ orderBy: { sequenceNumber: "desc" },
+ select: { sequenceNumber: true },
+ });
+ await tx.inAppAgentEvent.createMany({
+ data: latestRunEvents.map((event, index) => ({
+ projectId,
+ conversationId: conversation.id,
+ runId: run2.id,
+ sequenceNumber:
+ (latestRemainingEvent?.sequenceNumber ?? -1) + index + 1,
+ type: event.type,
+ event: event.event as Prisma.InputJsonValue,
+ })),
+ });
+ });
+
+ const rewrittenEvents = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id },
+ orderBy: { sequenceNumber: "asc" },
+ select: { sequenceNumber: true },
+ });
+ expect(rewrittenEvents.map((event) => event.sequenceNumber)).toEqual(
+ rewrittenEvents.map((_, index) => index),
+ );
+ await expect(
+ getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ }),
+ ).resolves.toEqual(replayBeforeRollback);
+ });
+
it("does not overwrite user-renamed conversation titles", async () => {
const originalBedrockSmallModel = env.LANGFUSE_AWS_BEDROCK_SMALL_MODEL;
const { caller, projectId, userId } = await createCaller();
@@ -633,7 +757,7 @@ describe("in-app agent persistence", () => {
).resolves.toBe(1);
});
- it("stores and reduces tool calls, tool results, and activities", async () => {
+ it("hydrates visible reasoning without including it in model replay", async () => {
const { projectId, userId, caller } = await createCaller();
const conversation = await createConversation({ projectId, userId });
const run = await createConversationRun({
@@ -699,6 +823,9 @@ describe("in-app agent persistence", () => {
content: "[]",
role: "tool",
});
+ await process({
+ type: EventType.REASONING_START,
+ });
await process({
type: EventType.REASONING_MESSAGE_START,
messageId: "reasoning-1",
@@ -707,7 +834,12 @@ describe("in-app agent persistence", () => {
await process({
type: EventType.REASONING_MESSAGE_CONTENT,
messageId: "reasoning-1",
- delta: "Checking filters",
+ delta: "Checking ",
+ });
+ await process({
+ type: EventType.REASONING_MESSAGE_CONTENT,
+ messageId: "reasoning-1",
+ delta: "filters",
});
await process({
type: EventType.REASONING_ENCRYPTED_VALUE,
@@ -719,6 +851,9 @@ describe("in-app agent persistence", () => {
type: EventType.REASONING_MESSAGE_END,
messageId: "reasoning-1",
});
+ await process({
+ type: EventType.REASONING_END,
+ });
await process({
type: EventType.ACTIVITY_SNAPSHOT,
messageId: "activity-1",
@@ -726,64 +861,139 @@ describe("in-app agent persistence", () => {
content: { status: "done" },
});
+ const expectedDisplayMessages = [
+ {
+ id: "tool-user",
+ role: "user" as const,
+ content: "Search traces",
+ },
+ {
+ id: "tool-assistant",
+ role: "assistant" as const,
+ content: "I searched traces.",
+ runId: run.id,
+ toolCalls: [
+ {
+ id: "tool-call-1",
+ type: "function" as const,
+ function: {
+ name: "list_traces",
+ arguments: '{"limit":10}',
+ },
+ },
+ ],
+ },
+ {
+ id: "tool-result-1",
+ role: "tool" as const,
+ content: "[]",
+ toolCallId: "tool-call-1",
+ },
+ {
+ id: "reasoning-1",
+ role: "reasoning" as const,
+ content: "Checking filters",
+ },
+ {
+ id: "activity-1",
+ role: "activity" as const,
+ activityType: "progress",
+ content: { status: "done" },
+ },
+ ];
+ const expectedReplayMessages = [
+ {
+ id: "tool-user",
+ role: "user" as const,
+ content: "Search traces",
+ },
+ {
+ id: "tool-assistant",
+ role: "assistant" as const,
+ content: "I searched traces.",
+ toolCalls: [
+ {
+ id: "tool-call-1",
+ type: "function" as const,
+ function: {
+ name: "list_traces",
+ arguments: '{"limit":10}',
+ },
+ },
+ ],
+ },
+ {
+ id: "tool-result-1",
+ role: "tool" as const,
+ content: "[]",
+ toolCallId: "tool-call-1",
+ },
+ {
+ id: "activity-1",
+ role: "activity" as const,
+ 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" },
- },
- ],
+ messages: expectedDisplayMessages,
});
-
await expect(
- prisma.inAppAgentEvent.count({
- where: { projectId, conversationId: conversation.id, runId: run.id },
+ getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
}),
- ).resolves.toBe(9);
+ ).resolves.toEqual(expectedReplayMessages);
- const persistedEventTypes = (
- await prisma.inAppAgentEvent.findMany({
- where: { projectId, conversationId: conversation.id, runId: run.id },
- select: { type: true },
- })
- ).map((event) => event.type);
- expect(persistedEventTypes).not.toContain(
- EventType.REASONING_MESSAGE_START,
- );
- expect(persistedEventTypes).not.toContain(
- EventType.REASONING_MESSAGE_CONTENT,
+ const persistedEvents = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id, runId: run.id },
+ orderBy: { sequenceNumber: "asc" },
+ select: { sequenceNumber: true, type: true, event: true },
+ });
+ expect(
+ persistedEvents
+ .filter((event) => event.type === EventType.REASONING_MESSAGE_CONTENT)
+ .map((event) => event.event),
+ ).toEqual([
+ expect.objectContaining({
+ type: EventType.REASONING_MESSAGE_CONTENT,
+ delta: "Checking filters",
+ }),
+ ]);
+ expect(JSON.stringify(persistedEvents)).not.toContain(
+ "encrypted-reasoning",
);
- expect(persistedEventTypes).not.toContain(EventType.REASONING_MESSAGE_END);
+
+ await prisma.inAppAgentEvent.create({
+ data: {
+ projectId,
+ conversationId: conversation.id,
+ runId: run.id,
+ sequenceNumber: (persistedEvents.at(-1)?.sequenceNumber ?? -1) + 1,
+ type: "FUTURE_REASONING_METADATA",
+ event: {
+ type: "FUTURE_REASONING_METADATA",
+ payload: "ignored",
+ },
+ },
+ });
+
+ await expect(
+ caller.getConversation({ projectId, conversationId: conversation.id }),
+ ).resolves.toMatchObject({
+ messages: expectedDisplayMessages,
+ });
+ await expect(
+ getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ }),
+ ).resolves.toEqual(expectedReplayMessages);
});
it("stores only compact events and skips raw adapter payloads", async () => {
@@ -1208,8 +1418,8 @@ describe("in-app agent persistence", () => {
]);
});
- it("drops failed redirect tool results before replay", async () => {
- const { projectId, userId } = await createCaller();
+ it("flushes sibling tools while retaining only successful redirect actions for display", async () => {
+ const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
const run = await createConversationRun({
projectId,
@@ -1252,6 +1462,60 @@ describe("in-app agent persistence", () => {
type: EventType.TOOL_CALL_END,
toolCallId: "redirect-tool-call",
});
+ await process({
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "sibling-tool-call",
+ toolCallName: "list_traces",
+ parentMessageId: "assistant-1",
+ });
+ await process({
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "sibling-tool-call",
+ delta: "{}",
+ });
+ await process({
+ type: EventType.TOOL_CALL_END,
+ toolCallId: "sibling-tool-call",
+ });
+ await process({
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "sibling-tool-result",
+ toolCallId: "sibling-tool-call",
+ content: "[]",
+ role: "tool",
+ });
+
+ const expectedReplayMessages = [
+ { id: "user-1", role: "user" as const, content: "open a trace" },
+ {
+ id: "assistant-1",
+ role: "assistant" as const,
+ toolCalls: [
+ {
+ id: "sibling-tool-call",
+ type: "function" as const,
+ function: { name: "list_traces", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ id: "sibling-tool-result",
+ role: "tool" as const,
+ content: "[]",
+ toolCallId: "sibling-tool-call",
+ },
+ ];
+
+ // A completed sibling tool unit must reach the Postgres-backed replay
+ // surface without waiting for an unrelated redirect result.
+ await expect(
+ getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ }),
+ ).resolves.toEqual(expectedReplayMessages);
+
await process({
type: EventType.TOOL_CALL_RESULT,
messageId: "tool-result-1",
@@ -1260,15 +1524,79 @@ describe("in-app agent persistence", () => {
role: "tool",
});
+ await process({
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "successful-redirect-tool-call",
+ toolCallName: IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ parentMessageId: "assistant-1",
+ });
+ await process({
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "successful-redirect-tool-call",
+ delta: '{"destination":"trace"}',
+ });
+ await process({
+ type: EventType.TOOL_CALL_END,
+ toolCallId: "successful-redirect-tool-call",
+ });
+ const redirectActionContent = JSON.stringify({
+ type: "redirectAction",
+ label: "Open trace",
+ href: `/project/${projectId}/traces/trace-1`,
+ });
+ await process({
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "successful-redirect-result",
+ toolCallId: "successful-redirect-tool-call",
+ content: redirectActionContent,
+ role: "tool",
+ });
+
+ // Successful redirect actions must survive refresh as render-only results,
+ // while failed redirects and their evolving call arguments stay absent.
+ await expect(
+ caller.getConversation({
+ projectId,
+ conversationId: conversation.id,
+ }),
+ ).resolves.toMatchObject({
+ messages: [
+ { id: "user-1", role: "user", content: "open a trace" },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ runId: run.id,
+ toolCalls: [
+ {
+ id: "sibling-tool-call",
+ type: "function",
+ function: { name: "list_traces", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ id: "sibling-tool-result",
+ role: "tool",
+ content: "[]",
+ toolCallId: "sibling-tool-call",
+ },
+ {
+ id: "successful-redirect-result",
+ role: "tool",
+ content: redirectActionContent,
+ toolCallId: "successful-redirect-tool-call",
+ },
+ ],
+ });
+
+ // Render-only redirect actions must never enter the next model request.
await expect(
getConversationMessagesForReplay({
prisma,
projectId,
conversationId: conversation.id,
}),
- ).resolves.toEqual([
- { id: "user-1", role: "user", content: "open a trace" },
- ]);
+ ).resolves.toEqual(expectedReplayMessages);
});
it("drops empty assistant messages after removing orphan tool calls before replay", async () => {
diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts
index a748e586e6..3ffbf67564 100644
--- a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts
+++ b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts
@@ -472,6 +472,53 @@ describe("getDrawerMessages", () => {
expect(mappedMessages).toHaveLength(2);
});
+ it("collapses consecutive reasoning messages into one thought block", () => {
+ const mappedMessages = getDrawerMessages({
+ error: null,
+ isRunning: true,
+ messages: [
+ {
+ id: "user-1",
+ role: "user",
+ content: "Investigate latency spikes",
+ },
+ {
+ id: "reasoning-1",
+ role: "reasoning",
+ content: "Checking recent traces before querying metrics.",
+ },
+ {
+ id: "reasoning-2",
+ role: "reasoning",
+ content: "The p95 spike lines up with one endpoint.",
+ },
+ {
+ id: "reasoning-3",
+ role: "reasoning",
+ content: "",
+ isLoading: true,
+ },
+ ] satisfies InAppAiAgentMessage[],
+ });
+
+ expect(mappedMessages).toMatchObject([
+ {
+ id: "user-1",
+ role: "user",
+ },
+ {
+ id: "reasoning-1",
+ role: "assistant",
+ content: {
+ type: "reasoning",
+ text: "Checking recent traces before querying metrics.\n\nThe p95 spike lines up with one endpoint.",
+ isStreaming: true,
+ },
+ },
+ ]);
+ expect(mappedMessages).toHaveLength(2);
+ });
+
it("marks reasoning complete when a run stops before assistant text arrives", () => {
const mappedMessages = getDrawerMessages({
error: "The run was interrupted before an answer was generated.",
diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.ts
index 2ad5d23d52..28ec8e1ae1 100644
--- a/web/src/ee/features/in-app-agent/components/utils/utils.ts
+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts
@@ -302,6 +302,28 @@ export function getDrawerMessages({
return;
}
+ const previousMessage = mappedMessages[mappedMessages.length - 1];
+
+ // Hydrated history flattens the text and tool content that separated
+ // thinking phases live, leaving them adjacent; collapse them into one
+ // block, mirroring how consecutive tool calls collapse into one group.
+ if (
+ previousMessage?.role === "assistant" &&
+ previousMessage.content.type === "reasoning"
+ ) {
+ mappedMessages[mappedMessages.length - 1] = {
+ ...previousMessage,
+ content: {
+ ...previousMessage.content,
+ text: [previousMessage.content.text, message.content]
+ .filter((text) => text.trim())
+ .join("\n\n"),
+ isStreaming,
+ },
+ };
+ return;
+ }
+
mappedMessages.push({
id: message.id,
role,
diff --git a/web/src/ee/features/in-app-agent/server/eventCompaction.ts b/web/src/ee/features/in-app-agent/server/eventCompaction.ts
index 46278b7036..1ad29cc2a8 100644
--- a/web/src/ee/features/in-app-agent/server/eventCompaction.ts
+++ b/web/src/ee/features/in-app-agent/server/eventCompaction.ts
@@ -32,6 +32,42 @@ export function compactTextMessageChunks(
return compactedEvents;
}
+export function compactPersistedEventDeltas(
+ events: readonly AgUiEvent[],
+): AgUiEvent[] {
+ const compactedEvents: AgUiEvent[] = [];
+
+ for (const event of compactTextMessageChunks(events)) {
+ const previousEvent = compactedEvents.at(-1);
+
+ if (
+ isReasoningDelta(event) &&
+ previousEvent &&
+ isReasoningDelta(previousEvent) &&
+ getString(event, "messageId") === getString(previousEvent, "messageId")
+ ) {
+ compactedEvents[compactedEvents.length - 1] = {
+ ...previousEvent,
+ delta:
+ (getString(previousEvent, "delta") ?? "") +
+ (getString(event, "delta") ?? ""),
+ };
+ continue;
+ }
+
+ compactedEvents.push(event);
+ }
+
+ return compactedEvents;
+}
+
+function isReasoningDelta(event: AgUiEvent) {
+ return (
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT
+ );
+}
+
function getTextChunkRole(event: unknown) {
const role = getString(event, "role");
diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.ts
index 3350287bd8..4e3d247d0f 100644
--- a/web/src/ee/features/in-app-agent/server/handler.ts
+++ b/web/src/ee/features/in-app-agent/server/handler.ts
@@ -44,7 +44,7 @@ import {
isInAppAgentConversationWriteLocked,
maybeInferAndPersistConversationTitle,
getSandboxToolCallFiles,
- replaceRunEvents,
+ flushPendingRunEvents,
shouldFlushPersistedEvent,
toPersistableAgentEvent,
} from "@/src/ee/features/in-app-agent/server/persistence";
@@ -394,7 +394,7 @@ export default async function handler(request: Request) {
});
runCreated = true;
- const persistedEvents: AgUiEvent[] = [
+ const pendingPersistedEvents: AgUiEvent[] = [
{
type: EventType.RUN_STARTED,
threadId: sanitizedInput.threadId,
@@ -406,16 +406,16 @@ export default async function handler(request: Request) {
},
];
- const replacePersistedRunEvents = () =>
- replaceRunEvents({
+ const flushPersistedRunEvents = () =>
+ flushPendingRunEvents({
prisma,
projectId,
conversationId: conversation.id,
runId: sanitizedInput.runId,
- events: persistedEvents,
+ pendingEvents: pendingPersistedEvents,
});
- await replacePersistedRunEvents();
+ await flushPersistedRunEvents();
if (isResumeAgentInput(sanitizedInput)) {
await consumeAndValidatePendingToolApproval({
@@ -472,19 +472,19 @@ export default async function handler(request: Request) {
approvedToolResultPersisted = true;
}
- persistedEvents.push(persistedEvent);
+ pendingPersistedEvents.push(persistedEvent);
if (!shouldFlushPersistedEvent(persistedEvent)) {
return;
}
- return replacePersistedRunEvents();
+ return flushPersistedRunEvents();
},
onApprovedToolCallExecuted: () => {
approvedToolResultPersisted = true;
},
onComplete: () =>
- replacePersistedRunEvents()
+ flushPersistedRunEvents()
.finally(() => finishCurrentRun())
.finally(() => {
if (request.signal.aborted) {
@@ -502,7 +502,7 @@ export default async function handler(request: Request) {
});
}),
onAbort: () =>
- replacePersistedRunEvents()
+ flushPersistedRunEvents()
.then(() => restorePendingToolApprovalIfRetryable())
.finally(() =>
finishCurrentRun({
@@ -511,7 +511,7 @@ export default async function handler(request: Request) {
}),
),
onError: (error) =>
- replacePersistedRunEvents()
+ flushPersistedRunEvents()
.then(() => restorePendingToolApprovalIfRetryable())
.finally(() =>
finishCurrentRun({
diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.ts
index cbcdb1a3f2..70225f2626 100644
--- a/web/src/ee/features/in-app-agent/server/persistence.ts
+++ b/web/src/ee/features/in-app-agent/server/persistence.ts
@@ -33,7 +33,7 @@ import {
type AgUiEvent,
type AgUiMessage,
} from "@/src/ee/features/in-app-agent/schema";
-import { compactTextMessageChunks } from "@/src/ee/features/in-app-agent/server/eventCompaction";
+import { compactPersistedEventDeltas } from "@/src/ee/features/in-app-agent/server/eventCompaction";
import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";
import { safeJsonParse } from "@/src/utils/json";
import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "@/src/ee/features/in-app-agent/server/tools";
@@ -272,14 +272,14 @@ export async function finishRun(params: {
);
}
-export async function replaceRunEvents(params: {
+export async function appendRunEvents(params: {
prisma: PrismaClient;
projectId: string;
conversationId: string;
runId: string;
events: readonly AgUiEvent[];
-}) {
- await params.prisma.$transaction(async (tx) => {
+}): Promise<boolean> {
+ return params.prisma.$transaction(async (tx) => {
await lockConversation(tx, params.projectId, params.conversationId);
const activeRun = await tx.inAppAgentRun.findFirst({
@@ -287,23 +287,15 @@ export async function replaceRunEvents(params: {
id: params.runId,
projectId: params.projectId,
conversationId: params.conversationId,
- finishedAt: null,
+ status: InAppAgentRunStatus.RUNNING,
},
select: { id: true },
});
if (!activeRun) {
- return;
+ return false;
}
- await tx.inAppAgentEvent.deleteMany({
- where: {
- projectId: params.projectId,
- conversationId: params.conversationId,
- runId: params.runId,
- },
- });
-
const latestEvent = await tx.inAppAgentEvent.findFirst({
where: {
projectId: params.projectId,
@@ -339,6 +331,8 @@ export async function replaceRunEvents(params: {
},
data: { updatedAt: new Date() },
});
+
+ return true;
});
}
@@ -638,8 +632,12 @@ function getMessagesFromPersistedEvents(
function sanitizeConversationMessagesForReplay(
messages: readonly AgUiMessage[],
): readonly AgUiMessage[] {
- const messagesWithoutRedirectActions =
- dropRedirectActionToolResults(messages);
+ const messagesWithoutReasoning = messages.filter(
+ (message) => message.role !== "reasoning",
+ );
+ const messagesWithoutRedirectActions = dropRedirectActionToolResults(
+ messagesWithoutReasoning,
+ );
const messagesWithoutOrphanToolCalls = dropUnpairedAssistantToolCalls(
messagesWithoutRedirectActions,
);
@@ -654,11 +652,97 @@ export function shouldFlushPersistedEvent(event: AgUiEvent) {
event.type === EventType.TOOL_CALL_END ||
event.type === EventType.TOOL_CALL_RESULT ||
event.type === EventType.ACTIVITY_SNAPSHOT ||
+ event.type === EventType.REASONING_END ||
event.type === EventType.RUN_FINISHED ||
event.type === EventType.RUN_ERROR
);
}
+function partitionPendingRunEvents(events: readonly AgUiEvent[]): {
+ eventsToAppend: AgUiEvent[];
+ retainedEvents: AgUiEvent[];
+} {
+ const openRedirectToolCallIds = new Set<string>();
+
+ for (const pendingEvent of events) {
+ const toolCallId = getString(pendingEvent, "toolCallId");
+
+ if (
+ toolCallId &&
+ pendingEvent.type === EventType.TOOL_CALL_START &&
+ getString(pendingEvent, "toolCallName") ===
+ IN_APP_AGENT_REDIRECT_TOOL_NAME
+ ) {
+ openRedirectToolCallIds.add(toolCallId);
+ }
+
+ if (toolCallId && pendingEvent.type === EventType.TOOL_CALL_RESULT) {
+ openRedirectToolCallIds.delete(toolCallId);
+ }
+ }
+
+ if (openRedirectToolCallIds.size === 0) {
+ return { eventsToAppend: [...events], retainedEvents: [] };
+ }
+
+ const eventsToAppend: AgUiEvent[] = [];
+ const retainedEvents: AgUiEvent[] = [];
+
+ for (const event of events) {
+ const toolCallId = getString(event, "toolCallId");
+ const destination =
+ toolCallId && openRedirectToolCallIds.has(toolCallId)
+ ? retainedEvents
+ : eventsToAppend;
+ destination.push(event);
+ }
+
+ return { eventsToAppend, retainedEvents };
+}
+
+// Flushes a caller-owned pending-event buffer: appends every completed unit and
+// keeps only unfinished redirect lifecycles buffered. Only the events present
+// at call time are flushed, so events pushed onto the buffer while the append
+// awaits survive for the next flush.
+export async function flushPendingRunEvents(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+ pendingEvents: AgUiEvent[];
+}) {
+ const pendingEventCount = params.pendingEvents.length;
+
+ if (pendingEventCount === 0) {
+ return;
+ }
+
+ const { eventsToAppend, retainedEvents } = partitionPendingRunEvents(
+ params.pendingEvents.slice(0, pendingEventCount),
+ );
+
+ if (eventsToAppend.length > 0) {
+ const appended = await appendRunEvents({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.runId,
+ events: eventsToAppend,
+ });
+
+ if (!appended) {
+ logger.warn("In-app agent run event append fenced by terminal run", {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.runId,
+ droppedEventCount: eventsToAppend.length,
+ });
+ }
+ }
+
+ params.pendingEvents.splice(0, pendingEventCount, ...retainedEvents);
+}
+
export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {
if (event.type === EventType.RUN_STARTED) {
const input = isRecord(event.input)
@@ -771,6 +855,44 @@ export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {
});
}
+ if (event.type === EventType.REASONING_START) {
+ return compactObject({
+ type: event.type,
+ });
+ }
+
+ if (event.type === EventType.REASONING_MESSAGE_START) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ role: getString(event, "role"),
+ });
+ }
+
+ if (
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT
+ ) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ delta: getString(event, "delta") ?? "",
+ });
+ }
+
+ if (event.type === EventType.REASONING_MESSAGE_END) {
+ return compactObject({
+ type: event.type,
+ messageId: getString(event, "messageId"),
+ });
+ }
+
+ if (event.type === EventType.REASONING_END) {
+ return compactObject({
+ type: event.type,
+ });
+ }
+
if (event.type === EventType.RUN_FINISHED) {
return compactObject({
type: event.type,
@@ -798,14 +920,6 @@ export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {
event.type === EventType.STEP_STARTED ||
event.type === EventType.STEP_FINISHED ||
event.type === EventType.TOOL_CALL_CHUNK ||
- // Reasoning is a live responsiveness signal. Keep plaintext reasoning out
- // of persisted conversation history and replay.
- event.type === EventType.REASONING_START ||
- event.type === EventType.REASONING_MESSAGE_START ||
- event.type === EventType.REASONING_MESSAGE_CHUNK ||
- event.type === EventType.REASONING_MESSAGE_CONTENT ||
- event.type === EventType.REASONING_MESSAGE_END ||
- event.type === EventType.REASONING_END ||
event.type === EventType.REASONING_ENCRYPTED_VALUE ||
// eslint-disable-next-line @typescript-eslint/no-deprecated
event.type === EventType.THINKING_START ||
@@ -833,6 +947,7 @@ export function createConversationMessageAccumulator(
string,
{ id: string; content: string; runId?: string }
>();
+ const reasoningDrafts = new Map<string, { id: string; content: string }>();
const toolCallDrafts = new Map<
string,
{
@@ -869,6 +984,12 @@ export function createConversationMessageAccumulator(
}
const processEvent = (event: AgUiEvent, runId?: string): boolean => {
+ // Stored rows may come from a newer writer. Ignore unknown runtime values
+ // before entering the exhaustive handling for the current EventType union.
+ if (!isKnownEventType(event.type)) {
+ return false;
+ }
+
if (event.type === EventType.RUN_STARTED) {
if (!isRecord(event.input) || !Array.isArray(event.input.messages)) {
return false;
@@ -956,6 +1077,61 @@ export function createConversationMessageAccumulator(
return changed;
}
+ if (event.type === EventType.REASONING_MESSAGE_START) {
+ const messageId = getString(event, "messageId");
+
+ if (messageId) {
+ reasoningDrafts.set(messageId, { id: messageId, content: "" });
+ }
+ return false;
+ }
+
+ if (
+ event.type === EventType.REASONING_MESSAGE_CHUNK ||
+ event.type === EventType.REASONING_MESSAGE_CONTENT
+ ) {
+ const messageId = getString(event, "messageId");
+
+ if (!messageId) {
+ return false;
+ }
+
+ const existingIndex = messageIndexes.get(messageId);
+ const existingMessage =
+ existingIndex === undefined ? undefined : messages[existingIndex];
+ const draft = reasoningDrafts.get(messageId) ?? {
+ id: messageId,
+ content:
+ existingMessage?.role === "reasoning" ? existingMessage.content : "",
+ };
+
+ draft.content += getString(event, "delta") ?? "";
+ reasoningDrafts.set(messageId, draft);
+
+ return upsertMessage({
+ id: draft.id,
+ role: "reasoning",
+ content: draft.content,
+ });
+ }
+
+ if (event.type === EventType.REASONING_MESSAGE_END) {
+ const messageId = getString(event, "messageId");
+ const draft = messageId ? reasoningDrafts.get(messageId) : undefined;
+
+ if (!draft) {
+ return false;
+ }
+
+ const changed = upsertMessage({
+ id: draft.id,
+ role: "reasoning",
+ content: draft.content,
+ });
+ reasoningDrafts.delete(draft.id);
+ return changed;
+ }
+
if (event.type === EventType.TOOL_CALL_START) {
const toolCallId = getString(event, "toolCallId");
const parentMessageId = getString(event, "parentMessageId");
@@ -1055,12 +1231,7 @@ export function createConversationMessageAccumulator(
event.type === EventType.STEP_STARTED ||
event.type === EventType.STEP_FINISHED ||
event.type === EventType.TOOL_CALL_CHUNK ||
- // Reasoning is live-only; do not reconstruct it from persisted history.
event.type === EventType.REASONING_START ||
- event.type === EventType.REASONING_MESSAGE_START ||
- event.type === EventType.REASONING_MESSAGE_CHUNK ||
- event.type === EventType.REASONING_MESSAGE_CONTENT ||
- event.type === EventType.REASONING_MESSAGE_END ||
event.type === EventType.REASONING_END ||
event.type === EventType.REASONING_ENCRYPTED_VALUE ||
// eslint-disable-next-line @typescript-eslint/no-deprecated
@@ -1146,13 +1317,13 @@ function mergeMessages(existing: AgUiMessage, next: AgUiMessage): AgUiMessage {
function compactPersistedEvents(events: readonly AgUiEvent[]): AgUiEvent[] {
return dropRedirectToolCallEvents(
- compactEvents(compactTextMessageChunks(events)) as AgUiEvent[],
+ compactEvents(compactPersistedEventDeltas(events)) as AgUiEvent[],
);
}
-// Redirect actions are rendered from the server-generated href payload. Drop the
-// redirect tool call scaffolding and args so persisted history does not depend
-// on the redirect input schema, which may evolve over time.
+// Redirect actions are rendered from the server-generated href payload. Keep
+// only that successful result: call scaffolding depends on an evolving input
+// schema, and failed results should not leave a broken action in history.
function dropRedirectToolCallEvents(events: readonly AgUiEvent[]): AgUiEvent[] {
const redirectToolCallIds = new Set<string>();
@@ -1193,7 +1364,15 @@ function dropRedirectToolCallEvents(events: readonly AgUiEvent[]): AgUiEvent[] {
}
const toolCallId = getString(event, "toolCallId");
- return !toolCallId || !redirectToolCallIds.has(toolCallId);
+
+ if (!toolCallId || !redirectToolCallIds.has(toolCallId)) {
+ return true;
+ }
+
+ return (
+ event.type === EventType.TOOL_CALL_RESULT &&
+ isRedirectActionToolResult(getString(event, "content"))
+ );
});
}
@@ -1301,6 +1480,10 @@ function getString(event: unknown, key: string): string | undefined {
return typeof value === "string" ? value : undefined;
}
+function isKnownEventType(type: unknown): type is EventType {
+ return Object.values(EventType).some((eventType) => eventType === type);
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}