Skip to content

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

feat(agent): Worker path for background in-app-agent runs (#15525)

Lysander Kieself9a65d91c329
diff --git a/.env.dev.example b/.env.dev.example
index fdc4f2dfdf..81daa9ebf2 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -209,6 +209,10 @@ LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"
# Optional: overrides Lambda's default INTERNET_EGRESS connector.
# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EGRESS_NETWORK_CONNECTOR_ARN="arn:aws:lambda:us-east-1:123456789012:network-connector:langfuse-in-app-agent-sandbox-egress"
+# Background execution of in-app agent runs (worker queue consumer, off by default).
+# QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED="true"
+# LANGFUSE_IN_APP_AGENT_RUN_QUEUE_PROCESSING_CONCURRENCY=5
+
# V4 migration flags. Pinned to dual write mode to ensure we cover the tests;
# bare deployments get the flipped v4 code defaults (events_only / direct).
# Write target: `legacy` | `dual` | `events_only`.
diff --git a/packages/shared/src/features/inAppAgent/types.ts b/packages/shared/src/features/inAppAgent/types.ts
index ca753583d3..a80c2d78aa 100644
--- a/packages/shared/src/features/inAppAgent/types.ts
+++ b/packages/shared/src/features/inAppAgent/types.ts
@@ -1,4 +1,5 @@
import z from "zod";
+import { AgUiContextSchema } from "../../in-app-agent/schema";
/**
* Lifecycle states of an in-app agent run (`in_app_agent_runs.status`).
@@ -35,4 +36,37 @@ export enum InAppAgentRunErrorCode {
AGENT_ERROR = "agent_error",
/** Agent initialization failed before the loop started. */
INIT_FAILED = "init_failed",
+ /** Background worker aborted the run on SIGTERM (deploy). */
+ WORKER_SHUTDOWN = "worker_shutdown",
+ /**
+ * Background run died after an approved mutation may have started but
+ * before its result was persisted. Never generically retried: the next
+ * turn must verify whether the effect landed before proposing again.
+ */
+ OUTCOME_UNKNOWN = "outcome_unknown",
}
+
+/**
+ * Typed contents of `in_app_agent_runs.request` — the server-side trigger
+ * payload a background worker reads at claim. The BullMQ job carries only
+ * `{projectId, runId}`, so everything the run needs that is not already in
+ * the append-only event stream lives here. The user message itself is not
+ * duplicated: the submitting mutation appends it as a conversation event
+ * and the worker rebuilds model input from the event history.
+ */
+export const InAppAgentRunRequestSchema = z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("userMessage"),
+ /** Sanitized AG-UI context items (current page, resolved view filters). */
+ context: z.array(AgUiContextSchema),
+ }),
+ z.object({
+ kind: z.literal("approvalDecision"),
+ /** Provenance for debugging only; no code path queries lineage. */
+ parentRunId: z.string(),
+ toolCallId: z.string(),
+ approved: z.boolean(),
+ }),
+]);
+
+export type InAppAgentRunRequest = z.infer<typeof InAppAgentRunRequestSchema>;
diff --git a/packages/shared/src/in-app-agent/schema.ts b/packages/shared/src/in-app-agent/schema.ts
index 713b30c9ef..08fc28404f 100644
--- a/packages/shared/src/in-app-agent/schema.ts
+++ b/packages/shared/src/in-app-agent/schema.ts
@@ -194,7 +194,7 @@ const AgUiToolSchema = z.object({
metadata: z.record(z.string(), z.unknown()).optional(),
});
-const AgUiContextSchema = z.object({
+export const AgUiContextSchema = z.object({
description: z.string(),
value: z.string(),
});
diff --git a/packages/shared/src/in-app-agent/server/index.ts b/packages/shared/src/in-app-agent/server/index.ts
index de566f0af0..7a7ee056c3 100644
--- a/packages/shared/src/in-app-agent/server/index.ts
+++ b/packages/shared/src/in-app-agent/server/index.ts
@@ -7,6 +7,9 @@ export * from "./human-in-the-loop";
export * from "./instrumentation";
export * from "./eventCompaction";
export * from "./persistence";
+export * from "./runLifecycle";
+export * from "./tunables";
+export * from "./promptClient";
export * from "./skills";
export * from "./sandbox";
export * from "./prompts/in-app-agent-system-prompt";
diff --git a/packages/shared/src/in-app-agent/server/promptClient.ts b/packages/shared/src/in-app-agent/server/promptClient.ts
new file mode 100644
index 0000000000..b8b9a00aac
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/promptClient.ts
@@ -0,0 +1,25 @@
+import { Langfuse } from "langfuse";
+
+import { env } from "../../env";
+import { getProductBaseUrl } from "../../server/utils/baseUrl";
+
+let client: Langfuse | null = null;
+
+/**
+ * Client for fetching the agent system prompt from the Langfuse AI-features
+ * project. Prompt fetching only — tracing is disabled because the agent has
+ * its own instrumentation sink. Without LANGFUSE_AI_FEATURES_HOST the client
+ * targets this deployment itself (e.g. PR previews), never cloud.langfuse.com.
+ */
+export function getInAppAgentPromptClient(): Langfuse {
+ if (!client) {
+ client = new Langfuse({
+ publicKey: env.LANGFUSE_AI_FEATURES_PUBLIC_KEY ?? "",
+ secretKey: env.LANGFUSE_AI_FEATURES_SECRET_KEY ?? "",
+ baseUrl: env.LANGFUSE_AI_FEATURES_HOST ?? getProductBaseUrl().toString(),
+ enabled: false,
+ });
+ }
+
+ return client;
+}
diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.ts b/packages/shared/src/in-app-agent/server/runLifecycle.ts
new file mode 100644
index 0000000000..7fcad28193
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/runLifecycle.ts
@@ -0,0 +1,114 @@
+import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "../../index";
+import type { InAppAgentRun, PrismaClient } from "../../db";
+
+/**
+ * Compare-and-swap transitions for background in-app agent runs.
+ *
+ * Postgres owns run correctness: BullMQ is delivery-only (`attempts: 1`,
+ * duplicate deliveries expected), so every ownership change is a conditional
+ * update that either wins or observes that someone else did. Web (submit,
+ * cancel, decide, reconcile-on-read) and the worker share these helpers.
+ */
+
+export async function claimQueuedRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ runId: string;
+}): Promise<InAppAgentRun | null> {
+ const now = new Date();
+ const rows = await params.prisma.inAppAgentRun.updateManyAndReturn({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.QUEUED,
+ finishedAt: null,
+ },
+ data: {
+ status: InAppAgentRunStatus.RUNNING,
+ claimedAt: now,
+ heartbeatAt: now,
+ },
+ });
+
+ return rows[0] ?? null;
+}
+
+export type HeartbeatResult =
+ /** The run is no longer RUNNING (reconciled away or cancelled directly): stop writing, no terminal CAS. */
+ { fenced: true } | { fenced: false; cancelRequestedAt: Date | null };
+
+export async function heartbeatClaimedRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ runId: string;
+}): Promise<HeartbeatResult> {
+ const rows = await params.prisma.inAppAgentRun.updateManyAndReturn({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.RUNNING,
+ },
+ data: { heartbeatAt: new Date() },
+ select: { cancelRequestedAt: true },
+ });
+
+ const row = rows[0];
+
+ return row
+ ? { fenced: false, cancelRequestedAt: row.cancelRequestedAt }
+ : { fenced: true };
+}
+
+export type TerminalRunStatus =
+ | InAppAgentRunStatus.SUCCEEDED
+ | InAppAgentRunStatus.FAILED
+ | InAppAgentRunStatus.CANCELLED
+ | InAppAgentRunStatus.AWAITING_APPROVAL;
+
+/**
+ * Terminal CAS `RUNNING → status`. Returns whether this caller won; a loser
+ * (run already reconciled to FAILED, cancelled directly, …) must not
+ * overwrite the observed outcome. `AWAITING_APPROVAL` sets `finishedAt` like
+ * the true terminal states: the worker and conversation slot are freed while
+ * the approval waits.
+ */
+export async function finishClaimedRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ runId: string;
+ status: TerminalRunStatus;
+ errorCode?: InAppAgentRunErrorCode;
+ errorMessage?: string;
+}): Promise<boolean> {
+ const { count } = await params.prisma.inAppAgentRun.updateMany({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.RUNNING,
+ finishedAt: null,
+ },
+ data: {
+ status: params.status,
+ finishedAt: new Date(),
+ errorCode: params.errorCode ?? null,
+ errorMessage: params.errorMessage ?? null,
+ },
+ });
+
+ return count > 0;
+}
+
+/**
+ * Null the MCP-key pointer only after the key's deletion is confirmed. If the
+ * delete fails, the pointer stays set so reconciliation retries the cleanup.
+ */
+export async function clearRunMcpApiKeyPointer(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ runId: string;
+}): Promise<void> {
+ await params.prisma.inAppAgentRun.updateMany({
+ where: { id: params.runId, projectId: params.projectId },
+ data: { mcpApiKeyId: null },
+ });
+}
diff --git a/packages/shared/src/in-app-agent/server/tunables.ts b/packages/shared/src/in-app-agent/server/tunables.ts
new file mode 100644
index 0000000000..da6580bed0
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/tunables.ts
@@ -0,0 +1,46 @@
+/**
+ * Lifecycle tunables for background in-app agent runs, in one place so they
+ * can be tuned without hunting. Every value is env-overridable; the defaults
+ * are the RFC's v1 values. Read lazily via process.env (not the zod env
+ * schema) so a bad override degrades to the default instead of failing boot.
+ */
+
+function envMs(name: string, defaultMs: number): number {
+ const raw = process.env[name];
+ if (!raw) return defaultMs;
+ const parsed = Number(raw);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : defaultMs;
+}
+
+/** Worker lease renewal + cancel-signal pickup interval. */
+export const IN_APP_AGENT_HEARTBEAT_INTERVAL_MS = envMs(
+ "LANGFUSE_IN_APP_AGENT_HEARTBEAT_INTERVAL_MS",
+ 5_000,
+);
+
+/** RUNNING with a heartbeat older than this is failed (worker_lost) on read. */
+export const IN_APP_AGENT_HEARTBEAT_STALE_MS = envMs(
+ "LANGFUSE_IN_APP_AGENT_HEARTBEAT_STALE_MS",
+ 60_000,
+);
+
+/** QUEUED older than this is failed (queue_timeout) on read. */
+export const IN_APP_AGENT_QUEUE_TIMEOUT_MS = envMs(
+ "LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS",
+ 5 * 60_000,
+);
+
+/**
+ * RUNNING for longer than this since claim is failed (run_timeout) on read —
+ * the backstop against a hung tool renewing a healthy heartbeat forever.
+ */
+export const IN_APP_AGENT_RUN_MAX_DURATION_MS = envMs(
+ "LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS",
+ 15 * 60_000,
+);
+
+/** AWAITING_APPROVAL parked longer than this expires (approval_expired) on read. */
+export const IN_APP_AGENT_APPROVAL_TTL_MS = envMs(
+ "LANGFUSE_IN_APP_AGENT_APPROVAL_TTL_MS",
+ 24 * 60 * 60_000,
+);
diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.ts
index 2f9275e26b..be2c341707 100644
--- a/packages/shared/src/server/auth/apiKeys.ts
+++ b/packages/shared/src/server/auth/apiKeys.ts
@@ -1,4 +1,4 @@
-import { PrismaClient, ApiKeyScope } from "@prisma/client";
+import { PrismaClient, ApiKeyScope, type Prisma } from "@prisma/client";
import { compare, hash } from "bcryptjs";
import { randomUUID } from "crypto";
import * as crypto from "crypto";
@@ -39,7 +39,9 @@ export function createShaHash(privateKey: string, salt: string): string {
}
export async function createAndAddApiKeysToDb(p: {
- prisma: PrismaClient;
+ // Accepts a transaction client so callers can commit key creation
+ // atomically with linking the key to its owner (e.g. an agent run row).
+ prisma: PrismaClient | Prisma.TransactionClient;
entityId: string;
scope: ApiKeyScope;
note?: string;
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 1607857d5c..f30d34377e 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -81,6 +81,12 @@ export const BatchExportJobSchema = z.object({
projectId: z.string(),
batchExportId: z.string(),
});
+// Deliberately minimal: the run row (in_app_agent_runs.request) carries the
+// typed input; the queue is delivery-only and the claim CAS owns correctness.
+export const InAppAgentRunQueueEventSchema = z.object({
+ projectId: z.string(),
+ runId: z.string(),
+});
export const CloudSpendAlertJobSchema = z.object({
orgId: z.string(),
});
@@ -322,6 +328,9 @@ export type CreateEvalQueueEventType = z.infer<
typeof CreateEvalQueueEventSchema
>;
export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;
+export type InAppAgentRunQueueEventType = z.infer<
+ typeof InAppAgentRunQueueEventSchema
+>;
export type CloudSpendAlertJobType = z.infer<typeof CloudSpendAlertJobSchema>;
export type TraceQueueEventType = z.infer<typeof TraceQueueEventSchema>;
export type TracesQueueEventType = z.infer<typeof TracesQueueEventSchema>;
@@ -405,6 +414,7 @@ export enum QueueName {
EventPropagationQueue = "event-propagation-queue",
NotificationQueue = "notification-queue",
MonitorQueue = "monitor-queue",
+ InAppAgentRunQueue = "in-app-agent-run-queue",
}
export enum QueueJobs {
@@ -442,6 +452,7 @@ export enum QueueJobs {
EventPropagationJob = "event-propagation-job",
NotificationJob = "notification-job",
MonitorJob = "monitor-job",
+ InAppAgentRunJob = "in-app-agent-run-job",
}
export type TQueueJobTypes = {
@@ -629,4 +640,10 @@ export type TQueueJobTypes = {
payload: MonitorQueueEventInput;
name: QueueJobs.MonitorJob;
};
+ [QueueName.InAppAgentRunQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: InAppAgentRunQueueEventType;
+ name: QueueJobs.InAppAgentRunJob;
+ };
};
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 428a9f4751..c964be2eb7 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -28,6 +28,7 @@ import { DatasetDeleteQueue } from "./datasetDelete";
import { EventPropagationQueue } from "./eventPropagationQueue";
import { NotificationQueue } from "./notificationQueue";
import { MonitorQueue } from "./monitorQueue";
+import { InAppAgentRunQueue } from "./inAppAgentRunQueue";
// Sharded queues require a sharding key.
// Use the queue class directly, for example IngestionQueue.getInstance({ shardingKey }).
@@ -102,6 +103,8 @@ export function getQueue(
return NotificationQueue.getInstance();
case QueueName.MonitorQueue:
return MonitorQueue.getInstance();
+ case QueueName.InAppAgentRunQueue:
+ return InAppAgentRunQueue.getInstance();
default: {
const _exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/packages/shared/src/server/redis/inAppAgentRunQueue.ts b/packages/shared/src/server/redis/inAppAgentRunQueue.ts
new file mode 100644
index 0000000000..6f289142b3
--- /dev/null
+++ b/packages/shared/src/server/redis/inAppAgentRunQueue.ts
@@ -0,0 +1,48 @@
+import { Queue } from "bullmq";
+import { QueueName, type TQueueJobTypes } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class InAppAgentRunQueue {
+ private static instance: Queue<
+ TQueueJobTypes[QueueName.InAppAgentRunQueue]
+ > | null = null;
+
+ public static getInstance(): Queue<
+ TQueueJobTypes[QueueName.InAppAgentRunQueue]
+ > | null {
+ if (InAppAgentRunQueue.instance) return InAppAgentRunQueue.instance;
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ InAppAgentRunQueue.instance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.InAppAgentRunQueue]>(
+ QueueName.InAppAgentRunQueue,
+ {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.InAppAgentRunQueue),
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ // Postgres owns correctness (claim CAS + reconcile-on-read);
+ // BullMQ is delivery-only, so never redeliver on its own.
+ attempts: 1,
+ },
+ },
+ )
+ : null;
+
+ InAppAgentRunQueue.instance?.on("error", (err) => {
+ logger.error("InAppAgentRunQueue error", err);
+ });
+
+ return InAppAgentRunQueue.instance;
+ }
+}
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 791def7946..7b53d13d16 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -21,6 +21,7 @@ import { cloudUsageMeteringQueueProcessor } from "./queues/cloudUsageMeteringQue
import { cloudSpendAlertQueueProcessor } from "./queues/cloudSpendAlertQueue";
import { cloudFreeTierUsageThresholdQueueProcessor } from "./queues/cloudFreeTierUsageThresholdQueue";
import { monitorQueueProcessor } from "./queues/monitorQueue";
+import { inAppAgentRunQueueProcessor } from "./queues/inAppAgentRunQueue";
import { WorkerManager } from "./queues/workerManager";
import {
CoreDataS3ExportQueue,
@@ -46,6 +47,7 @@ import {
CodeEvalExecutionQueue,
} from "@langfuse/shared/src/server";
import { monitorProcessorTtl } from "@langfuse/shared/monitors/server";
+import { IN_APP_AGENT_RUN_MAX_DURATION_MS } from "@langfuse/shared/in-app-agent/server";
import { env, v4WritesToEventsTable } from "./env";
import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
import { BackgroundMigrationManager } from "./backgroundMigrations/backgroundMigrationManager";
@@ -421,6 +423,21 @@ if (env.QUEUE_CONSUMER_MONITOR_QUEUE_IS_ENABLED === "true") {
});
}
+if (env.QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED === "true") {
+ WorkerManager.register(
+ QueueName.InAppAgentRunQueue,
+ inAppAgentRunQueueProcessor,
+ {
+ concurrency: env.LANGFUSE_IN_APP_AGENT_RUN_QUEUE_PROCESSING_CONCURRENCY,
+ // Postgres owns run correctness (claim CAS, heartbeat, reconcile);
+ // BullMQ must never redeliver on its own, so stalled recovery is off
+ // and the lock outlives the run-duration backstop.
+ lockDuration: IN_APP_AGENT_RUN_MAX_DURATION_MS + 60_000,
+ maxStalledCount: 0,
+ },
+ );
+}
+
// Cloud Spend Alert Queue: Only enable in cloud environment with Stripe
if (
env.QUEUE_CONSUMER_CLOUD_SPEND_ALERT_QUEUE_IS_ENABLED === "true" &&
diff --git a/worker/src/env.ts b/worker/src/env.ts
index bfb8d8b901..f4c91fcb30 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -219,6 +219,11 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_MONITOR_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ // Off by default until the background-execution rollout: the consumer needs
+ // Bedrock/MCP/sandbox config the worker deployment may not carry yet.
+ QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
@@ -581,6 +586,10 @@ const EnvSchema = z.object({
.number()
.positive()
.default(10),
+ LANGFUSE_IN_APP_AGENT_RUN_QUEUE_PROCESSING_CONCURRENCY: z.coerce
+ .number()
+ .positive()
+ .default(5),
LANGFUSE_DELETE_BATCH_SIZE: z.coerce.number().positive().default(2000),
LANGFUSE_TOKEN_COUNT_WORKER_POOL_SIZE: z.coerce
.number()
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
new file mode 100644
index 0000000000..22c4dd9c36
--- /dev/null
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -0,0 +1,574 @@
+import { randomUUID } from "crypto";
+import { describe, expect, it, vi } from "vitest";
+
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createInAppAgentConversationId,
+ createInAppAgentRunId,
+} from "@langfuse/shared/in-app-agent";
+
+// Env knobs must be set before any import evaluates the shared env/tunables.
+vi.hoisted(() => {
+ process.env.LANGFUSE_IN_APP_AGENT_HEARTBEAT_INTERVAL_MS = "50";
+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ??= "DEV";
+ process.env.NEXTAUTH_URL ??= "http://localhost:3000";
+ process.env.LANGFUSE_AWS_BEDROCK_REGION ??= "eu-central-1";
+ process.env.LANGFUSE_AWS_BEDROCK_MODEL ??= "test-bedrock-model";
+});
+
+/**
+ * The agent loop contract is faked per test: a scenario drives the stream's
+ * option callbacks (events, complete/abort/error, finish) exactly like the
+ * real Mastra loop would, while everything else — claim CAS, heartbeat,
+ * MCP-key lifecycle, event persistence — runs against the real database.
+ */
+type AgentScenario = (ctx: {
+ input: { threadId: string; runId: string; forwardedProps: unknown };
+ signal: AbortSignal;
+ options: {
+ onEvent: (event: unknown) => Promise<void> | void;
+ onApprovedToolCallExecuted?: () => Promise<void> | void;
+ onComplete: () => Promise<void>;
+ onAbort: () => Promise<void>;
+ onError: (error: unknown) => Promise<void>;
+ onFinish: () => Promise<void>;
+ };
+}) => Promise<void>;
+
+const scenarioRef = vi.hoisted(() => ({
+ current: undefined as AgentScenario | undefined,
+ failApiKeyDelete: false,
+ apiKeyDeleteCalls: 0,
+}));
+
+vi.mock("@langfuse/shared/in-app-agent/server", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@langfuse/shared/in-app-agent/server")
+ >();
+
+ return {
+ ...actual,
+ createAgUiStream: async (params: {
+ input: never;
+ signal: AbortSignal;
+ options: never;
+ }) => {
+ const scenario = scenarioRef.current;
+ if (!scenario) throw new Error("No agent scenario configured");
+
+ return new ReadableStream({
+ async start(controller) {
+ try {
+ await scenario({
+ input: params.input,
+ signal: params.signal,
+ options: params.options,
+ });
+ controller.close();
+ } catch (error) {
+ // Mirrors the real loop's failStream: a scenario throw surfaces
+ // to the worker as an errored stream (rejected reader.read()).
+ controller.error(error);
+ }
+ },
+ });
+ },
+ };
+});
+
+vi.mock("@langfuse/shared/src/server/auth/apiKeys", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@langfuse/shared/src/server/auth/apiKeys")
+ >();
+
+ return {
+ ...actual,
+ deleteApiKeyFromDb: async (
+ ...args: Parameters<typeof actual.deleteApiKeyFromDb>
+ ) => {
+ scenarioRef.apiKeyDeleteCalls += 1;
+ if (scenarioRef.failApiKeyDelete) {
+ throw new Error("simulated api key delete failure");
+ }
+ return actual.deleteApiKeyFromDb(...args);
+ },
+ };
+});
+
+import {
+ executeInAppAgentRun,
+ abortActiveInAppAgentRuns,
+} from "./executeInAppAgentRun";
+
+const textChunk = (delta: string) => ({
+ type: "TEXT_MESSAGE_CHUNK",
+ messageId: "msg-1",
+ role: "assistant",
+ delta,
+});
+
+const interruptEvent = (parentRunId: string, toolCallId = "tc-1") => ({
+ type: "CUSTOM",
+ name: "on_interrupt",
+ value: {
+ type: "mastra_suspend",
+ toolCallId,
+ toolName: "langfuse_createTextPrompt",
+ args: { name: "p" },
+ runId: parentRunId,
+ },
+});
+
+const completingScenario: AgentScenario = async ({ options }) => {
+ await options.onEvent(textChunk("Hello "));
+ await options.onEvent(textChunk("world"));
+ await options.onComplete();
+ await options.onFinish();
+};
+
+async function seedBackgroundRun(opts?: {
+ request?: unknown;
+ status?: string;
+ aiFeaturesEnabled?: boolean;
+}) {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const project = await prisma.project.findUniqueOrThrow({
+ where: { id: projectId },
+ });
+ await prisma.organization.update({
+ where: { id: project.orgId },
+ data: {
+ aiFeaturesEnabled: opts?.aiFeaturesEnabled ?? true,
+ aiTelemetryEnabled: false,
+ },
+ });
+ const user = await prisma.user.create({
+ data: { email: `bg-${randomUUID()}@langfuse.com`, name: "bg-user" },
+ });
+ await prisma.organizationMembership.create({
+ data: { orgId: project.orgId, userId: user.id, role: "MEMBER" },
+ });
+ const conversation = await prisma.inAppAgentConversation.create({
+ data: {
+ id: createInAppAgentConversationId(),
+ projectId,
+ createdByUserId: user.id,
+ title: "background test",
+ },
+ });
+ const run = await prisma.inAppAgentRun.create({
+ data: {
+ id: createInAppAgentRunId(),
+ projectId,
+ conversationId: conversation.id,
+ triggeredByUserId: user.id,
+ model: "test-bedrock-model",
+ status: opts?.status ?? "QUEUED",
+ request: (opts?.request ?? { kind: "userMessage", context: [] }) as never,
+ },
+ });
+
+ return { projectId, orgId: project.orgId, user, conversation, run };
+}
+
+const getRun = (projectId: string, runId: string) =>
+ prisma.inAppAgentRun.findUniqueOrThrow({
+ where: { id_projectId: { id: runId, projectId } },
+ });
+
+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() {
+ const seeded = await seedBackgroundRun();
+ const { projectId, conversation, run, user } = seeded;
+ const parentRun = await prisma.inAppAgentRun.create({
+ data: {
+ id: createInAppAgentRunId(),
+ projectId,
+ conversationId: conversation.id,
+ triggeredByUserId: user.id,
+ status: "SUCCEEDED",
+ finishedAt: new Date(),
+ },
+ });
+ await prisma.inAppAgentEvent.create({
+ data: {
+ projectId,
+ conversationId: conversation.id,
+ runId: parentRun.id,
+ sequenceNumber: 1,
+ type: "CUSTOM",
+ event: interruptEvent(parentRun.id) as never,
+ },
+ });
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: {
+ request: {
+ kind: "approvalDecision",
+ parentRunId: parentRun.id,
+ toolCallId: "tc-1",
+ approved: true,
+ },
+ },
+ });
+
+ return seeded;
+}
+
+describe("executeInAppAgentRun", () => {
+ it("executes a queued run to SUCCEEDED with persisted events and full MCP-key lifecycle", async () => {
+ const { projectId, conversation, run } = await seedBackgroundRun();
+
+ let keysDuringRun = -1;
+ scenarioRef.current = async ({ options }) => {
+ keysDuringRun = (await getInAppAgentApiKeys(projectId)).length;
+ await options.onEvent({
+ type: "RUN_STARTED",
+ threadId: conversation.id,
+ runId: run.id,
+ });
+ await options.onEvent(textChunk("Hello "));
+ await options.onEvent(textChunk("world"));
+ await options.onComplete();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const finished = await getRun(projectId, run.id);
+ expect(finished.status).toBe("SUCCEEDED");
+ expect(finished.finishedAt).not.toBeNull();
+ expect(finished.claimedAt).not.toBeNull();
+ expect(finished.heartbeatAt).not.toBeNull();
+ expect(finished.errorCode).toBeNull();
+
+ // Key was minted and linked during the run, deleted and unlinked after.
+ expect(keysDuringRun).toBe(1);
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ expect(finished.mcpApiKeyId).toBeNull();
+
+ // Events persisted append-only; the stream's RUN_STARTED is skipped
+ // (the submitter persists it), text chunks are compacted.
+ const events = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id },
+ orderBy: { sequenceNumber: "asc" },
+ });
+ expect(events.length).toBeGreaterThan(0);
+ expect(events.every((e) => e.type !== "RUN_STARTED")).toBe(true);
+ const merged = events.find((e) => e.type === "TEXT_MESSAGE_CHUNK");
+ expect(merged).toBeDefined();
+ expect((merged!.event as { delta?: string }).delta).toBe("Hello world");
+ });
+
+ it("acknowledges duplicate delivery without executing (claim CAS returns no row)", async () => {
+ const { projectId, run } = await seedBackgroundRun({ status: "RUNNING" });
+
+ scenarioRef.current = async () => {
+ throw new Error("agent loop must not start on duplicate delivery");
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const untouched = await getRun(projectId, run.id);
+ expect(untouched.status).toBe("RUNNING");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("parks on an interrupt event: AWAITING_APPROVAL with the raw interrupt persisted", async () => {
+ const { projectId, conversation, run } = await seedBackgroundRun();
+
+ scenarioRef.current = async ({ options }) => {
+ await options.onEvent(textChunk("Proposing a mutation"));
+ await options.onEvent(interruptEvent(run.id));
+ await options.onComplete();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const parked = await getRun(projectId, run.id);
+ expect(parked.status).toBe("AWAITING_APPROVAL");
+ expect(parked.finishedAt).not.toBeNull();
+ expect(parked.errorCode).toBeNull();
+ expect(parked.mcpApiKeyId).toBeNull();
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+
+ const interruptRows = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id, type: "CUSTOM" },
+ });
+ expect(interruptRows).toHaveLength(1);
+ expect(
+ (interruptRows[0].event as { value?: { toolCallId?: string } }).value
+ ?.toolCallId,
+ ).toBe("tc-1");
+ });
+
+ it("finishes FAILED (agent_error) when the loop errors, keeping partial events", async () => {
+ const { projectId, conversation, run } = await seedBackgroundRun();
+
+ scenarioRef.current = async ({ options }) => {
+ await options.onEvent(textChunk("partial"));
+ await options.onError(new Error("model exploded"));
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("agent_error");
+ expect(failed.errorMessage).toBe("model exploded");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ expect(failed.mcpApiKeyId).toBeNull();
+
+ const events = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id },
+ });
+ expect(events.length).toBeGreaterThan(0);
+ });
+
+ it("cancels within a heartbeat when cancel_requested_at is set", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: { cancelRequestedAt: new Date() },
+ });
+
+ scenarioRef.current = async ({ signal, options }) => {
+ await options.onEvent(textChunk("working"));
+ await new Promise<void>((resolve) => {
+ if (signal.aborted) return resolve();
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ await options.onAbort();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const cancelled = await getRun(projectId, run.id);
+ expect(cancelled.status).toBe("CANCELLED");
+ expect(cancelled.errorCode).toBe("cancelled");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("stops writing when fenced: an externally reconciled run keeps its recorded outcome", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+
+ scenarioRef.current = async ({ signal, options }) => {
+ // Simulate read-side reconciliation flipping the run away mid-loop.
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: {
+ status: "FAILED",
+ finishedAt: new Date(),
+ errorCode: "worker_lost",
+ errorMessage: "The run was interrupted.",
+ },
+ });
+ await new Promise<void>((resolve) => {
+ if (signal.aborted) return resolve();
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ expect(signal.reason).toBe("fenced");
+ await options.onAbort();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const fenced = await getRun(projectId, run.id);
+ expect(fenced.status).toBe("FAILED");
+ expect(fenced.errorCode).toBe("worker_lost");
+ expect(fenced.errorMessage).toBe("The run was interrupted.");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("finishes an approved continuation without a persisted tool result as FAILED (outcome_unknown)", async () => {
+ const { projectId, run } = await seedApprovedContinuation();
+
+ scenarioRef.current = async ({ input, options }) => {
+ // Zero-trust resume: args come from the persisted interrupt event.
+ expect(
+ (
+ input.forwardedProps as {
+ command: { resume: { approvalRequest: { toolName: string } } };
+ }
+ ).command.resume.approvalRequest.toolName,
+ ).toBe("langfuse_createTextPrompt");
+ await options.onError(new Error("died mid-mutation"));
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("outcome_unknown");
+ });
+
+ it("records outcome_unknown, not CANCELLED, when a cancel interrupts an approved mutation before its result persists", async () => {
+ const { projectId, run } = await seedApprovedContinuation();
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: run.id, projectId } },
+ data: { cancelRequestedAt: new Date() },
+ });
+
+ scenarioRef.current = async ({ signal, options }) => {
+ // The approved tool is "in flight": no TOOL_CALL_RESULT is persisted
+ // before the heartbeat-picked-up cancel aborts the loop.
+ await new Promise<void>((resolve) => {
+ if (signal.aborted) return resolve();
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ await options.onAbort();
+ await options.onFinish();
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const finished = await getRun(projectId, run.id);
+ expect(finished.status).toBe("FAILED");
+ expect(finished.errorCode).toBe("outcome_unknown");
+ });
+
+ it("keeps outcome_unknown when the loop dies in the executed-but-unpersisted window (no execution-time flag)", async () => {
+ const { projectId, run } = await seedApprovedContinuation();
+
+ scenarioRef.current = async ({ options }) => {
+ // Mirrors human-in-the-loop.ts: the approved mutation completed and the
+ // execution callback fires (if wired), but the crash happens before the
+ // synthetic TOOL_CALL_RESULT ever reaches onEvent.
+ await options.onApprovedToolCallExecuted?.();
+ throw new Error("adapter teardown crashed");
+ };
+
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).rejects.toThrow("adapter teardown crashed");
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("outcome_unknown");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("classifies a loop-phase stream error as agent_error, not init_failed, in the outer catch", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+
+ scenarioRef.current = async ({ options }) => {
+ await options.onEvent(textChunk("partial"));
+ throw new Error("persistence blew up");
+ };
+
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).rejects.toThrow("persistence blew up");
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("agent_error");
+ expect(failed.errorMessage).toBe("persistence blew up");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("deletes the MCP key exactly once when the loop's onFinish races the outer catch", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+ scenarioRef.apiKeyDeleteCalls = 0;
+
+ scenarioRef.current = async ({ options }) => {
+ await options.onEvent(textChunk("partial"));
+ // Replicate failStream exactly: the terminal onError→onFinish chain is
+ // fired WITHOUT awaiting it, then the stream errors synchronously —
+ // so onFinish's cleanup races the outer catch's cleanup.
+ void (async () => {
+ await options.onError(new Error("persist failed"));
+ await options.onFinish();
+ })();
+ throw new Error("persist failed");
+ };
+
+ await expect(
+ executeInAppAgentRun({ projectId, runId: run.id }),
+ ).rejects.toThrow("persist failed");
+
+ await vi.waitFor(async () => {
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("agent_error");
+ expect(failed.mcpApiKeyId).toBeNull();
+ expect(scenarioRef.apiKeyDeleteCalls).toBe(1);
+ });
+
+ it("fails revalidation at claim as FAILED (init_failed) when AI features are disabled", async () => {
+ const { projectId, run } = await seedBackgroundRun({
+ aiFeaturesEnabled: false,
+ });
+
+ scenarioRef.current = async () => {
+ throw new Error("agent loop must not start when revalidation fails");
+ };
+
+ await executeInAppAgentRun({ projectId, runId: run.id });
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("init_failed");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+
+ it("keeps the MCP-key pointer when the delete fails, for reconciliation to retry", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+
+ scenarioRef.current = completingScenario;
+ scenarioRef.failApiKeyDelete = true;
+
+ try {
+ await executeInAppAgentRun({ projectId, runId: run.id });
+ } finally {
+ scenarioRef.failApiKeyDelete = false;
+ }
+
+ const finished = await getRun(projectId, run.id);
+ expect(finished.status).toBe("SUCCEEDED");
+ // Delete failed → pointer stays set and the key row still exists, so the
+ // run remains the discoverable owner of the orphaned key.
+ expect(finished.mcpApiKeyId).not.toBeNull();
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(1);
+ });
+
+ it("aborts active runs on shutdown as FAILED (worker_shutdown)", async () => {
+ const { projectId, run } = await seedBackgroundRun();
+
+ scenarioRef.current = async ({ signal, options }) => {
+ await options.onEvent(textChunk("long turn"));
+ await new Promise<void>((resolve) => {
+ if (signal.aborted) return resolve();
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ await options.onAbort();
+ await options.onFinish();
+ };
+
+ const execution = executeInAppAgentRun({ projectId, runId: run.id });
+
+ await vi.waitFor(async () => {
+ expect((await getRun(projectId, run.id)).status).toBe("RUNNING");
+ });
+ abortActiveInAppAgentRuns();
+ await execution;
+
+ const failed = await getRun(projectId, run.id);
+ expect(failed.status).toBe("FAILED");
+ expect(failed.errorCode).toBe("worker_shutdown");
+ expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
+ });
+});
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
new file mode 100644
index 0000000000..3ce2143785
--- /dev/null
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -0,0 +1,739 @@
+import {
+ InAppAgentRunErrorCode,
+ InAppAgentRunRequestSchema,
+ InAppAgentRunStatus,
+ Role,
+ type InAppAgentRunRequest,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { env as sharedEnv } from "@langfuse/shared/src/env";
+import {
+ getLangfuseAITraceSinkParams,
+ logger,
+ redis,
+} from "@langfuse/shared/src/server";
+import {
+ createAndAddApiKeysToDb,
+ deleteApiKeyFromDb,
+} from "@langfuse/shared/src/server/auth/apiKeys";
+import {
+ getInAppAgentInstrumentationTraceId,
+ type AgUiEvent,
+ type AgUiRunAgentInput,
+ type InAppAgentToolApprovalRequest,
+} from "@langfuse/shared/in-app-agent";
+import {
+ claimQueuedRun,
+ clearRunMcpApiKeyPointer,
+ createAgUiStream,
+ createInAppAgentMcpRunOverride,
+ createInAppAgentSandbox,
+ finishClaimedRun,
+ flushPendingRunEvents,
+ getConversationEvents,
+ getConversationMessagesForReplay,
+ getInAppAgentPromptClient,
+ getSandboxToolCallFiles,
+ heartbeatClaimedRun,
+ IN_APP_AGENT_HEARTBEAT_INTERVAL_MS,
+ isInAppAgentConversationWriteLocked,
+ isMcpToolName,
+ maybeInferAndPersistConversationTitle,
+ parseInAppAgentInterruptEvent,
+ shouldFlushPersistedEvent,
+ toPersistableAgentEvent,
+ type InAppAgentUserAccess,
+ type PersistedConversationEvent,
+} from "@langfuse/shared/in-app-agent/server";
+import {
+ createInAppAgentSandboxProvider,
+ getDefaultInAppAgentSandboxProviderType,
+} from "@langfuse/shared/in-app-agent/server/sandbox/config";
+
+import { env } from "../../env";
+
+const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";
+
+type AbortReason = "cancelled" | "fenced" | "worker_shutdown";
+
+// Active runs register their AbortController so SIGTERM can abort every loop
+// at its next step boundary before WorkerManager waits for jobs to drain.
+const activeRunAborts = new Set<AbortController>();
+
+export function abortActiveInAppAgentRuns(): void {
+ for (const controller of activeRunAborts) {
+ controller.abort("worker_shutdown" satisfies AbortReason);
+ }
+}
+
+/** Thrown for claim-time revalidation failures; maps to FAILED (init_failed). */
+class InAppAgentRunInitError extends Error {}
+
+export async function executeInAppAgentRun(params: {
+ projectId: string;
+ runId: string;
+}): Promise<void> {
+ const { projectId, runId } = params;
+
+ // Claim CAS: zero rows means duplicate delivery or a run reconciled away
+ // while queued — ack and exit, Postgres owns correctness.
+ const run = await claimQueuedRun({ prisma, projectId, runId });
+
+ if (!run) {
+ logger.info("In-app agent run not claimable, acknowledging delivery", {
+ projectId,
+ runId,
+ });
+ return;
+ }
+
+ const abortController = new AbortController();
+ activeRunAborts.add(abortController);
+
+ let heartbeatTimer: NodeJS.Timeout | undefined;
+ let mcpApiKey: { id: string; publicKey: string; secretKey: string } | null =
+ null;
+ let mcpApiKeyCleanup: Promise<void> | undefined;
+ let isApprovedContinuation = false;
+ let approvedToolResultPersisted = false;
+ // True once createAgUiStream returned: from here on, errors reaching the
+ // outer catch are loop failures surfaced through the errored stream, not
+ // initialization failures.
+ let agentLoopStarted = false;
+
+ // The uncovered durability window: an approved mutation may have started
+ // but its result never persisted. Never generically retried. Hoisted to
+ // function scope because both the loop callbacks and the outer catch can
+ // record the terminal state (failStream races the drain rejection).
+ const failureCode = () =>
+ isApprovedContinuation && !approvedToolResultPersisted
+ ? {
+ errorCode: InAppAgentRunErrorCode.OUTCOME_UNKNOWN,
+ errorMessage:
+ "The approved action may have completed. Verify before retrying.",
+ }
+ : undefined;
+
+ // Single-flight (same shape as web's withInAppAgentMcpApiKeyCleanup): the
+ // loop's onFinish and the outer catch can invoke this concurrently because
+ // failStream errors the stream without awaiting its onError/onFinish chain.
+ const cleanupMcpApiKey = (): Promise<void> => {
+ if (!mcpApiKey) return Promise.resolve();
+ const keyId = mcpApiKey.id;
+ mcpApiKeyCleanup ??= (async () => {
+ await deleteApiKeyFromDb({
+ prisma,
+ id: keyId,
+ entityId: projectId,
+ scope: "PROJECT",
+ redis,
+ });
+ // Pointer is nulled only after the delete is confirmed; if the delete
+ // failed above, the terminal run keeps the pointer so reconciliation
+ // retries the cleanup.
+ await clearRunMcpApiKeyPointer({ prisma, projectId, runId });
+ })().catch((error: unknown) => {
+ mcpApiKeyCleanup = undefined;
+ throw error;
+ });
+ return mcpApiKeyCleanup;
+ };
+
+ const cleanupMcpApiKeyLogged = () =>
+ cleanupMcpApiKey().catch((error) =>
+ logger.error("Failed to clean up in-app agent MCP API key", {
+ error,
+ projectId,
+ runId,
+ }),
+ );
+
+ try {
+ // ---- Revalidate at claim; nothing from enqueue time is trusted. ----
+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw new InAppAgentRunInitError(
+ "In-app agent is only available on Langfuse Cloud",
+ );
+ }
+
+ const bedrockModelId = run.model ?? sharedEnv.LANGFUSE_AWS_BEDROCK_MODEL;
+
+ if (!bedrockModelId || !sharedEnv.LANGFUSE_AWS_BEDROCK_REGION) {
+ throw new InAppAgentRunInitError(
+ "Assistant Bedrock model is not configured",
+ );
+ }
+
+ const conversation = await prisma.inAppAgentConversation.findFirst({
+ where: { id: run.conversationId, projectId, deletedAt: null },
+ });
+
+ // Owner-only v1: the run principal must own the conversation.
+ if (
+ !conversation ||
+ conversation.createdByUserId !== run.triggeredByUserId
+ ) {
+ throw new InAppAgentRunInitError("Agent conversation not found");
+ }
+
+ const project = await prisma.project.findFirst({
+ where: { id: projectId, deletedAt: null },
+ include: { organization: true },
+ });
+
+ if (!project) {
+ throw new InAppAgentRunInitError("Project not found");
+ }
+
+ if (!project.organization.aiFeaturesEnabled) {
+ throw new InAppAgentRunInitError(
+ "AI features are disabled for this organization",
+ );
+ }
+
+ if (!run.triggeredByUserId) {
+ // Pre-committed platform guardrail: a missing user must never
+ // implicitly mean "trusted system".
+ throw new InAppAgentRunInitError("Run has no triggering user");
+ }
+
+ const access = await resolveUserProjectAccess({
+ userId: run.triggeredByUserId,
+ projectId,
+ orgId: project.orgId,
+ });
+
+ if (!access) {
+ throw new InAppAgentRunInitError(
+ "User is no longer a member of this project",
+ );
+ }
+
+ const conversationEvents = await getConversationEvents({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ });
+
+ if (
+ isInAppAgentConversationWriteLocked({
+ conversation,
+ events: conversationEvents,
+ })
+ ) {
+ throw new InAppAgentRunInitError(
+ "Conversation is write-locked (sandbox session expired)",
+ );
+ }
+
+ // ---- Build the agent input from the run request + persisted history. ----
+ const parsedRequest = InAppAgentRunRequestSchema.safeParse(run.request);
+
+ if (!parsedRequest.success) {
+ throw new InAppAgentRunInitError("Run request payload is invalid");
+ }
+
+ const request = parsedRequest.data;
+ const replayMessages = await getConversationMessagesForReplay({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ });
+ const approvalRequest =
+ request.kind === "approvalDecision"
+ ? findPersistedApprovalRequest(conversationEvents, request)
+ : undefined;
+
+ if (request.kind === "approvalDecision" && !approvalRequest) {
+ throw new InAppAgentRunInitError(
+ "Approval request not found in conversation history",
+ );
+ }
+
+ // The submitter persisted the RUN_STARTED event (carrying the user
+ // message / decision) in the same transaction that inserted the run, so
+ // the replayed history is complete and the worker never writes
+ // RUN_STARTED itself.
+ const agentInput: AgUiRunAgentInput = {
+ threadId: conversation.id,
+ runId,
+ state: null,
+ messages: [...replayMessages],
+ tools: [],
+ context: request.kind === "userMessage" ? request.context : [],
+ forwardedProps:
+ request.kind === "approvalDecision" && approvalRequest
+ ? {
+ command: {
+ resume: {
+ approved: request.approved,
+ approvalRequest,
+ },
+ },
+ }
+ : {},
+ };
+
+ isApprovedContinuation =
+ request.kind === "approvalDecision" && request.approved;
+ const approvedRegistryToolName = isApprovedContinuation
+ ? getRegistryToolName(approvalRequest?.toolName)
+ : undefined;
+ const runOverride = approvedRegistryToolName
+ ? await createInAppAgentMcpRunOverride({
+ toolName: approvedRegistryToolName,
+ })
+ : undefined;
+
+ // ---- Sandbox (session created/resumed lazily per tool call). ----
+ const sandboxProviderType = getDefaultInAppAgentSandboxProviderType();
+ const sandboxProvider =
+ sandboxProviderType === null || env.NODE_ENV === "test"
+ ? undefined
+ : await createInAppAgentSandboxProvider(sandboxProviderType);
+
+ if (sandboxProviderType === "dangerous-docker" && sandboxProvider) {
+ logger.warn(
+ "Using dangerous-docker in-app agent sandbox provider. This is for local development only.",
+ );
+ }
+
+ const sandboxState = sandboxProvider
+ ? await createInAppAgentSandbox({
+ conversationId: conversation.id,
+ projectId,
+ providerSessionId: conversation.providerSessionId,
+ provider: sandboxProvider,
+ getToolCallFiles: async () =>
+ getSandboxToolCallFiles(conversationEvents),
+ saveState: async (state) => {
+ await prisma.inAppAgentConversation.update({
+ where: { id_projectId: { id: conversation.id, projectId } },
+ data: state,
+ });
+ },
+ })
+ : undefined;
+
+ // ---- Temp MCP key: mint + link to the run in one transaction, so no
+ // crash window can leave a key that is not discoverable from its run. ----
+ mcpApiKey = await prisma.$transaction(async (tx) => {
+ const key = await createAndAddApiKeysToDb({
+ prisma: tx,
+ entityId: projectId,
+ scope: "PROJECT",
+ note: IN_APP_AGENT_API_KEY_NOTE,
+ isInAppAgentKey: true,
+ createdByUserId: run.triggeredByUserId ?? undefined,
+ });
+
+ await tx.inAppAgentRun.updateMany({
+ where: { id: runId, projectId },
+ data: { mcpApiKeyId: key.id },
+ });
+
+ return { id: key.id, publicKey: key.publicKey, secretKey: key.secretKey };
+ });
+
+ // ---- Heartbeat: lease renewal out, cancel signal back, one query. ----
+ let heartbeatInFlight = false;
+ heartbeatTimer = setInterval(() => {
+ if (heartbeatInFlight || abortController.signal.aborted) return;
+ heartbeatInFlight = true;
+ heartbeatClaimedRun({ prisma, projectId, runId })
+ .then((result) => {
+ if (result.fenced) {
+ abortController.abort("fenced" satisfies AbortReason);
+ } else if (result.cancelRequestedAt) {
+ abortController.abort("cancelled" satisfies AbortReason);
+ }
+ })
+ .catch((error) =>
+ logger.error("In-app agent heartbeat failed", {
+ error,
+ projectId,
+ runId,
+ }),
+ )
+ .finally(() => {
+ heartbeatInFlight = false;
+ });
+ }, IN_APP_AGENT_HEARTBEAT_INTERVAL_MS);
+
+ // ---- Run the loop; persistence via onEvent, no consumer for the SSE text. ----
+ const pendingPersistedEvents: AgUiEvent[] = [];
+ const flushPersistedRunEvents = () =>
+ flushPendingRunEvents({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ runId,
+ pendingEvents: pendingPersistedEvents,
+ });
+
+ let interruptRequest: InAppAgentToolApprovalRequest | undefined;
+
+ const finishWith = async (params2: {
+ status: Parameters<typeof finishClaimedRun>[0]["status"];
+ errorCode?: InAppAgentRunErrorCode;
+ errorMessage?: string;
+ }) => {
+ await finishClaimedRun({
+ prisma,
+ projectId,
+ runId,
+ ...params2,
+ });
+ };
+
+ const userAccess: InAppAgentUserAccess = {
+ projectRole: access.projectRole,
+ isAdmin: access.isAdmin,
+ };
+
+ const stream = await createAgUiStream({
+ input: agentInput,
+ signal: abortController.signal,
+ options: {
+ onEvent: async (event) => {
+ const parsedInterrupt = parseInAppAgentInterruptEvent(event);
+
+ if (parsedInterrupt) {
+ // Background approvals live on the run row + this persisted raw
+ // interrupt event (no side table). toPersistableAgentEvent drops
+ // CUSTOM events, so the row is pushed directly; the message
+ // accumulators skip CUSTOM rows, so replay/display are unchanged.
+ interruptRequest = parsedInterrupt;
+ pendingPersistedEvents.push(event);
+ return;
+ }
+
+ const persistedEvent = toPersistableAgentEvent(event);
+
+ if (!persistedEvent || persistedEvent.type === "RUN_STARTED") {
+ return;
+ }
+
+ // The flag flips only when the result event is queued for
+ // persistence — deliberately NOT via onApprovedToolCallExecuted,
+ // which fires at execution time, before the adapter
+ // teardown/recreate window in which a crash would leave the
+ // executed mutation unrecorded.
+ if (
+ persistedEvent.type === "TOOL_CALL_RESULT" &&
+ persistedEvent.toolCallId === approvalRequest?.toolCallId
+ ) {
+ approvedToolResultPersisted = true;
+ }
+
+ pendingPersistedEvents.push(persistedEvent);
+
+ if (!shouldFlushPersistedEvent(persistedEvent)) {
+ return;
+ }
+
+ return flushPersistedRunEvents();
+ },
+ onComplete: async () => {
+ await flushPersistedRunEvents();
+ await finishWith(
+ interruptRequest
+ ? { status: InAppAgentRunStatus.AWAITING_APPROVAL }
+ : { status: InAppAgentRunStatus.SUCCEEDED },
+ );
+ await maybeInferAndPersistConversationTitle({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ userId: run.triggeredByUserId!,
+ aiTelemetryEnabled: project.organization.aiTelemetryEnabled,
+ }).catch((error) =>
+ logger.error("Failed to infer in-app agent conversation title", {
+ error,
+ projectId,
+ runId,
+ }),
+ );
+ },
+ onAbort: async () => {
+ await flushPersistedRunEvents();
+ const reason = abortController.signal.reason as AbortReason;
+
+ if (reason === "fenced") {
+ // The run was reconciled away; its outcome is already recorded
+ // and this worker lost ownership — no terminal CAS.
+ return;
+ }
+
+ if (reason === "cancelled") {
+ // The unrecorded-outcome window is cause-agnostic: a cancel can
+ // interrupt an approved mutation mid-flight just like a deploy,
+ // and recording plain CANCELLED would read as "nothing happened".
+ const unknownOutcome = failureCode();
+
+ await finishWith(
+ unknownOutcome
+ ? { status: InAppAgentRunStatus.FAILED, ...unknownOutcome }
+ : {
+ status: InAppAgentRunStatus.CANCELLED,
+ errorCode: InAppAgentRunErrorCode.CANCELLED,
+ errorMessage: "Run cancelled by user request",
+ },
+ );
+ return;
+ }
+
+ await finishWith({
+ status: InAppAgentRunStatus.FAILED,
+ ...(failureCode() ?? {
+ errorCode: InAppAgentRunErrorCode.WORKER_SHUTDOWN,
+ errorMessage: "The run was interrupted by a deploy",
+ }),
+ });
+ },
+ onError: async (error) => {
+ await flushPersistedRunEvents();
+ await finishWith({
+ status: InAppAgentRunStatus.FAILED,
+ ...(failureCode() ?? {
+ errorCode: InAppAgentRunErrorCode.AGENT_ERROR,
+ errorMessage:
+ error instanceof Error ? error.message : "Unknown agent error",
+ }),
+ });
+ },
+ onFinish: async () => {
+ await cleanupMcpApiKeyLogged();
+ await sandboxState?.onTurnEnded();
+ },
+ awsBedrock: {
+ region: sharedEnv.LANGFUSE_AWS_BEDROCK_REGION,
+ modelId: bedrockModelId,
+ ...(sharedEnv.LANGFUSE_IN_APP_AGENT_AWS_PROFILE
+ ? { profile: sharedEnv.LANGFUSE_IN_APP_AGENT_AWS_PROFILE }
+ : {}),
+ },
+ langfuseMcp: {
+ url: getLangfuseMcpUrl(),
+ publicKey: mcpApiKey.publicKey,
+ secretKey: mcpApiKey.secretKey,
+ userAccess,
+ runOverride,
+ },
+ redirectAction: {
+ projectId,
+ isV4Enabled: access.v4BetaEnabled,
+ },
+ langfuseClient: getInAppAgentPromptClient(),
+ useLocalPrompt: env.NODE_ENV === "development",
+ langfuseTracing: buildTracingConfig({
+ aiTelemetryEnabled: project.organization.aiTelemetryEnabled,
+ projectId,
+ conversationId: conversation.id,
+ runId,
+ user: {
+ id: run.triggeredByUserId,
+ email: access.email,
+ projectRole: userAccess.projectRole,
+ isAdmin: userAccess.isAdmin,
+ },
+ }),
+ sandbox: sandboxState?.sandbox,
+ },
+ });
+
+ agentLoopStarted = true;
+ await drainStream(stream);
+ } catch (error) {
+ // Two classes land here: pre-loop failures (revalidation, input build,
+ // key minting) and loop failures surfaced through the errored stream —
+ // failStream fires the loop's onError without awaiting it and errors the
+ // stream synchronously, so this catch can RACE that onError and win the
+ // terminal CAS. Both writers therefore classify identically: the
+ // durability check first, then agent_error for loop-phase failures and
+ // init_failed only before the loop existed.
+ await finishClaimedRun({
+ prisma,
+ projectId,
+ runId,
+ status: InAppAgentRunStatus.FAILED,
+ ...(failureCode() ?? {
+ errorCode: agentLoopStarted
+ ? InAppAgentRunErrorCode.AGENT_ERROR
+ : InAppAgentRunErrorCode.INIT_FAILED,
+ errorMessage:
+ error instanceof Error
+ ? error.message
+ : "Agent initialization failed",
+ }),
+ });
+ await cleanupMcpApiKeyLogged();
+
+ if (!(error instanceof InAppAgentRunInitError)) {
+ throw error;
+ }
+ } finally {
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
+ activeRunAborts.delete(abortController);
+ }
+}
+
+async function resolveUserProjectAccess(params: {
+ userId: string;
+ projectId: string;
+ orgId: string;
+}): Promise<{
+ projectRole?: Role;
+ isAdmin: boolean;
+ email: string | null;
+ v4BetaEnabled: boolean;
+} | null> {
+ const user = await prisma.user.findUnique({
+ where: { id: params.userId },
+ select: { id: true, email: true, admin: true, v4BetaEnabled: true },
+ });
+
+ if (!user) return null;
+
+ if (user.admin) {
+ return {
+ isAdmin: true,
+ email: user.email,
+ v4BetaEnabled: user.v4BetaEnabled,
+ };
+ }
+
+ const orgMembership = await prisma.organizationMembership.findFirst({
+ where: { userId: params.userId, orgId: params.orgId },
+ });
+
+ if (!orgMembership) return null;
+
+ const projectMembership = await prisma.projectMembership.findFirst({
+ where: {
+ userId: params.userId,
+ projectId: params.projectId,
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ const projectRole = projectMembership?.role ?? orgMembership.role;
+
+ if (projectRole === Role.NONE) return null;
+
+ return {
+ projectRole,
+ isAdmin: false,
+ email: user.email,
+ v4BetaEnabled: user.v4BetaEnabled,
+ };
+}
+
+function findPersistedApprovalRequest(
+ events: readonly PersistedConversationEvent[],
+ request: Extract<InAppAgentRunRequest, { kind: "approvalDecision" }>,
+): InAppAgentToolApprovalRequest | undefined {
+ // Zero-trust: the decision mutation stores only IDs; tool name and args are
+ // read back from the interrupt event the parent run persisted.
+ for (const { event, runId } of events) {
+ if (runId !== request.parentRunId) continue;
+
+ const approvalRequest = parseInAppAgentInterruptEvent(event);
+
+ if (approvalRequest?.toolCallId === request.toolCallId) {
+ return approvalRequest;
+ }
+ }
+
+ return undefined;
+}
+
+function getRegistryToolName(toolName: string | undefined) {
+ if (!toolName?.startsWith("langfuse_")) {
+ return undefined;
+ }
+
+ const registryToolName = toolName.slice("langfuse_".length);
+
+ return isMcpToolName(registryToolName) ? registryToolName : undefined;
+}
+
+function getLangfuseMcpUrl(): string {
+ if (!env.NEXTAUTH_URL) {
+ throw new InAppAgentRunInitError(
+ "NEXTAUTH_URL must be configured to derive the MCP endpoint",
+ );
+ }
+
+ const rawUrl = env.NEXTAUTH_URL.replace(/\/api\/auth\/?$/, "");
+ const baseUrl = new URL(rawUrl);
+
+ baseUrl.pathname = `${baseUrl.pathname.replace(/\/$/, "")}/api/public/mcp`;
+ baseUrl.search = "";
+ baseUrl.hash = "";
+
+ return baseUrl.toString();
+}
+
+function buildTracingConfig(params: {
+ aiTelemetryEnabled: boolean;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+ user: {
+ id: string;
+ email: string | null;
+ projectRole?: Role;
+ isAdmin: boolean;
+ };
+}) {
+ if (!params.aiTelemetryEnabled) {
+ return undefined;
+ }
+
+ const traceSinkParams = getLangfuseAITraceSinkParams({
+ environment: "langfuse-in-app-agent",
+ feature: "in-app-agent",
+ projectId: params.projectId,
+ traceId: getInAppAgentInstrumentationTraceId(params.runId),
+ traceName: "agent-turn",
+ userId: params.user.id,
+ metadata: {
+ langfuse_ai_feature: "in-app-agent",
+ langfuse_user_id: params.user.id,
+ langfuse_project_id: params.projectId,
+ conversation_id: params.conversationId,
+ run_id: params.runId,
+ cloud_region: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ execution_runtime: "worker",
+ },
+ });
+
+ return traceSinkParams
+ ? {
+ targetProjectId: traceSinkParams.targetProjectId,
+ environment: traceSinkParams.environment,
+ runId: params.runId,
+ user: {
+ id: params.user.id,
+ email: params.user.email,
+ projectRole: params.user.projectRole,
+ isAdmin: params.user.isAdmin,
+ },
+ metadata: traceSinkParams.metadata ?? {},
+ }
+ : undefined;
+}
+
+async function drainStream(stream: {
+ getReader: () => { read: () => Promise<{ done: boolean }> };
+}): Promise<void> {
+ const reader = stream.getReader();
+
+ // The SSE frames have no consumer on the background path; reading drives
+ // the loop to completion and the onEvent callbacks persist everything.
+ for (;;) {
+ const { done } = await reader.read();
+ if (done) return;
+ }
+}
diff --git a/worker/src/queues/inAppAgentRunQueue.ts b/worker/src/queues/inAppAgentRunQueue.ts
new file mode 100644
index 0000000000..aaf57a30cf
--- /dev/null
+++ b/worker/src/queues/inAppAgentRunQueue.ts
@@ -0,0 +1,24 @@
+import { Processor } from "bullmq";
+import {
+ instrumentAsync,
+ InAppAgentRunQueueEventSchema,
+ QueueJobs,
+} from "@langfuse/shared/src/server";
+import { SpanKind } from "@opentelemetry/api";
+
+import { executeInAppAgentRun } from "../features/in-app-agent/executeInAppAgentRun";
+
+export const inAppAgentRunQueueProcessor: Processor = async (job) => {
+ if (job.name !== QueueJobs.InAppAgentRunJob) return;
+ return await instrumentAsync(
+ {
+ name: "process in-app-agent run",
+ startNewTrace: true,
+ spanKind: SpanKind.CONSUMER,
+ },
+ async () => {
+ const payload = InAppAgentRunQueueEventSchema.parse(job.data.payload);
+ await executeInAppAgentRun(payload);
+ },
+ );
+};
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index 95c7e2b480..acc5ea6589 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -8,6 +8,7 @@ import { freeAllTokenizers } from "../features/tokenisation/usage";
import { getTokenCountWorkerManager } from "../features/tokenisation/async-usage";
import { WorkerManager } from "../queues/workerManager";
import { logInFlightBlobExportsOnShutdown } from "../features/blobstorage/inFlightExports";
+import { abortActiveInAppAgentRuns } from "../features/in-app-agent/executeInAppAgentRun";
import { prisma } from "@langfuse/shared/src/db";
import { BackgroundMigrationManager } from "../backgroundMigrations/backgroundMigrationManager";
import {
@@ -70,6 +71,11 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
// Before closeWorkers(), while the registry is still populated (LFE-10388).
logInFlightBlobExportsOnShutdown();
+ // Abort in-flight agent loops at their next step boundary so closeWorkers()
+ // does not wait out a full agent turn; each run finishes FAILED
+ // (worker_shutdown) with its events flushed.
+ abortActiveInAppAgentRuns();
+
// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)
await WorkerManager.closeWorkers();