Skip to content

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

fix(in-app-agent): preserve context across approval continuations (#15799)

Lysander Kieselc32eb8a67591
diff --git a/packages/shared/src/features/inAppAgent/types.ts b/packages/shared/src/features/inAppAgent/types.ts
index e25f9f12d4..3c012ec2a7 100644
--- a/packages/shared/src/features/inAppAgent/types.ts
+++ b/packages/shared/src/features/inAppAgent/types.ts
@@ -83,6 +83,8 @@ export const InAppAgentRunRequestSchema = z.discriminatedUnion("kind", [
parentRunId: z.string(),
toolCallId: z.string(),
approved: z.boolean(),
+ /** Inherited sanitized context; defaults for legacy continuation rows. */
+ context: z.array(AgUiContextSchema).default([]),
}),
]);
diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.ts b/packages/shared/src/in-app-agent/server/runLifecycle.ts
index 385e6ab85a..fd189f8d3c 100644
--- a/packages/shared/src/in-app-agent/server/runLifecycle.ts
+++ b/packages/shared/src/in-app-agent/server/runLifecycle.ts
@@ -9,7 +9,10 @@ import type { InAppAgentRun, PrismaClient } from "../../db";
import { logger } from "../../server";
import { buildInAppAgentApprovalDecisionEvent } from "../backgroundWatch";
import type { AgUiEvent } from "../schema";
-import type { InAppAgentRunRequest } from "../../features/inAppAgent/types";
+import {
+ InAppAgentRunRequestSchema,
+ type InAppAgentRunRequest,
+} from "../../features/inAppAgent/types";
import {
ACTIVE_RUN_CONFLICT_MESSAGE,
FOREGROUND_RUN_STALE_AFTER_MS,
@@ -212,7 +215,7 @@ export async function decideToolApproval(params: {
projectId: params.projectId,
conversationId: params.conversationId,
},
- select: { status: true, finishedAt: true },
+ select: { status: true, finishedAt: true, request: true },
});
if (
@@ -261,6 +264,10 @@ export async function decideToolApproval(params: {
);
}
+ const parentRequest = InAppAgentRunRequestSchema.safeParse(
+ parentRun.request,
+ );
+
await appendConversationEventInTransaction({
tx,
projectId: params.projectId,
@@ -286,6 +293,7 @@ export async function decideToolApproval(params: {
parentRunId: params.parentRunId,
toolCallId: params.toolCallId,
approved: params.approved,
+ context: parentRequest.success ? parentRequest.data.context : [],
},
}),
};
diff --git a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
index ff99f66256..54e09b749f 100644
--- a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
@@ -168,6 +168,7 @@ describe("in-app agent background runs", () => {
conversationId: string;
userId: string;
toolCallId: string;
+ context?: Array<{ description: string; value: string }>;
parkedAt?: Date;
}) => {
const runId = createInAppAgentRunId();
@@ -180,7 +181,10 @@ describe("in-app agent background runs", () => {
triggeredByUserId: params.userId,
status: InAppAgentRunStatus.AWAITING_APPROVAL,
finishedAt: params.parkedAt ?? new Date(),
- request: { kind: "userMessage", context: [] },
+ request: {
+ kind: "userMessage",
+ context: params.context ?? [],
+ },
},
});
@@ -320,11 +324,19 @@ describe("in-app agent background runs", () => {
it("decides an approval exactly once and reads the tool args server-side", async () => {
const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
+ const context = [
+ {
+ description: "current_url",
+ value: '{"pathname":"/project/project-1/traces"}',
+ },
+ { description: "user_name", value: "Agent User" },
+ ];
const parkedRunId = await parkRunForApproval({
projectId,
conversationId: conversation.id,
userId,
toolCallId: "tool-call-1",
+ context,
});
const { runId: continuationRunId } = await caller.decideToolApproval({
@@ -351,6 +363,7 @@ describe("in-app agent background runs", () => {
parentRunId: parkedRunId,
toolCallId: "tool-call-1",
approved: true,
+ context,
});
const decisionEvent = await prisma.inAppAgentEvent.findFirstOrThrow({
@@ -387,6 +400,83 @@ describe("in-app agent background runs", () => {
).toBe(1);
});
+ it("preserves context through an approved then rejected chained continuation", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const context = [
+ {
+ description: "current_url",
+ value:
+ '{"pathname":"/project/project-1/traces","search":"?filter=error"}',
+ },
+ { description: "current_timezone", value: "Europe/Berlin" },
+ ];
+ const initialRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-1",
+ context,
+ });
+
+ const { runId: approvedContinuationId } = await caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: initialRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ });
+
+ await prisma.inAppAgentRun.update({
+ where: {
+ id_projectId: { id: approvedContinuationId, projectId },
+ },
+ data: {
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ finishedAt: new Date(),
+ },
+ });
+ await prisma.inAppAgentEvent.create({
+ data: {
+ projectId,
+ conversationId: conversation.id,
+ runId: approvedContinuationId,
+ sequenceNumber: 2,
+ type: EventType.CUSTOM,
+ event: {
+ type: EventType.CUSTOM,
+ name: "on_interrupt",
+ value: {
+ type: "mastra_suspend",
+ toolCallId: "tool-call-2",
+ toolName: "langfuse_createTextPrompt",
+ args: { name: "second-tool" },
+ runId: approvedContinuationId,
+ },
+ },
+ },
+ });
+
+ const { runId: rejectedContinuationId } = await caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: approvedContinuationId,
+ toolCallId: "tool-call-2",
+ approved: false,
+ });
+
+ const rejectedContinuation = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: rejectedContinuationId, projectId },
+ });
+ expect(rejectedContinuation.request).toMatchObject({
+ kind: "approvalDecision",
+ parentRunId: approvedContinuationId,
+ toolCallId: "tool-call-2",
+ approved: false,
+ context,
+ });
+ });
+
it("rate-limits approval continuations before persisting or enqueueing them", async () => {
const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
index 1b93558422..4550cfa4d5 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -22,7 +22,12 @@ vi.hoisted(() => {
* MCP-key lifecycle, event persistence — runs against the real database.
*/
type AgentScenario = (ctx: {
- input: { threadId: string; runId: string; forwardedProps: unknown };
+ input: {
+ threadId: string;
+ runId: string;
+ context: Array<{ description: string; value: string }>;
+ forwardedProps: unknown;
+ };
signal: AbortSignal;
options: {
onEvent: (event: unknown) => Promise<void> | void;
@@ -182,7 +187,9 @@ const getInAppAgentApiKeys = (projectId: string) =>
prisma.apiKey.findMany({ where: { projectId, isInAppAgentKey: true } });
/** A run resuming an approved tool call whose interrupt event is persisted on a parked parent run. */
-async function seedApprovedContinuation() {
+async function seedApprovedContinuation(opts?: {
+ context?: Array<{ description: string; value: string }>;
+}) {
const seeded = await seedBackgroundRun();
const { projectId, conversation, run, user } = seeded;
const parentRun = await prisma.inAppAgentRun.create({
@@ -213,6 +220,7 @@ async function seedApprovedContinuation() {
parentRunId: parentRun.id,
toolCallId: "tc-1",
approved: true,
+ ...(opts?.context ? { context: opts.context } : {}),
},
},
});
@@ -221,6 +229,38 @@ async function seedApprovedContinuation() {
}
describe("executeInAppAgentRun", () => {
+ it("passes persisted continuation context to the agent input", async () => {
+ const context = [
+ {
+ description: "current_url",
+ value: '{"pathname":"/project/project-1/traces"}',
+ },
+ { description: "browser_languages", value: '["de-DE"]' },
+ ];
+ const { projectId, run } = await seedApprovedContinuation({ context });
+
+ scenarioRef.current = async ({ input, options }) => {
+ expect(input.context).toEqual(context);
+ await options.onComplete();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+ });
+
+ it("defaults legacy continuation context to an empty array", async () => {
+ const { projectId, run } = await seedApprovedContinuation();
+
+ scenarioRef.current = async ({ input, options }) => {
+ expect(input.context).toEqual([]);
+ await options.onComplete();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+ expect((await getRun(projectId, run.id)).status).toBe("SUCCEEDED");
+ });
+
it("executes a queued run to SUCCEEDED with persisted events and full MCP-key lifecycle", async () => {
const { projectId, conversation, run } = await seedBackgroundRun();
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index 017d595b2e..fc21170d55 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -260,7 +260,7 @@ export async function executeInAppAgentRun(params: {
state: null,
messages: [...replayMessages],
tools: [],
- context: request.kind === "userMessage" ? request.context : [],
+ context: request.context,
forwardedProps:
request.kind === "approvalDecision" && approvalRequest
? {