Skip to content

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

feat(agent): Extract & extend background execution for in-app-agent (LFE-14373) (#15594)

Lysander Kiesel1cdaa99b2561
diff --git a/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts b/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts
index dc11878ce1..c408c8b0df 100644
--- a/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts
+++ b/packages/shared/scripts/seeder/utils/in-app-agent-seed.ts
@@ -1,4 +1,5 @@
import {
+ InAppAgentRunStatus,
type Prisma,
type PrismaClient,
type Prompt,
@@ -328,6 +329,7 @@ export async function seedInAppAgentDemoConversation({
conversationId,
triggeredByUserId: userId,
model: "claude-haiku-4-5",
+ status: InAppAgentRunStatus.SUCCEEDED,
finishedAt: firstRunFinishedAt,
createdAt: firstRunCreatedAt,
updatedAt: firstRunFinishedAt,
@@ -338,6 +340,7 @@ export async function seedInAppAgentDemoConversation({
conversationId,
triggeredByUserId: userId,
model: "claude-haiku-4-5",
+ status: InAppAgentRunStatus.SUCCEEDED,
finishedAt: secondRunFinishedAt,
createdAt: secondRunCreatedAt,
updatedAt: secondRunFinishedAt,
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 2e72cbb67f..1ff0010998 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -507,6 +507,51 @@ const EnvSchema = z.object({
LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION: z
.string()
.optional(),
+ LANGFUSE_IN_APP_AGENT_HEARTBEAT_INTERVAL_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(5_000),
+ LANGFUSE_IN_APP_AGENT_HEARTBEAT_STALE_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(60_000),
+ LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(5 * 60_000),
+ LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(15 * 60_000),
+ LANGFUSE_IN_APP_AGENT_APPROVAL_TTL_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(24 * 60 * 60_000),
+ LANGFUSE_IN_APP_AGENT_WATCH_TAIL_POLL_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(1_000),
+ LANGFUSE_IN_APP_AGENT_WATCH_KEEPALIVE_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(15_000),
+ LANGFUSE_IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(5_000),
+ LANGFUSE_IN_APP_AGENT_WATCH_MAX_CONNECTION_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(90_000),
// API Performance Flags
// Whether to add a `FINAL` modifier to the observations CTE in GET /api/public/traces.
diff --git a/packages/shared/src/features/inAppAgent/types.ts b/packages/shared/src/features/inAppAgent/types.ts
index a80c2d78aa..e25f9f12d4 100644
--- a/packages/shared/src/features/inAppAgent/types.ts
+++ b/packages/shared/src/features/inAppAgent/types.ts
@@ -6,8 +6,8 @@ import { AgUiContextSchema } from "../../in-app-agent/schema";
*
* Stored as a plain string column (not a PG enum) so states can be added
* without `ALTER TYPE`, following BatchExportStatus/BatchActionStatus.
- * The column is nullable until the first status reader ships: NULL means
- * the row was written by code that predates the column.
+ * Legacy rows may still be null, while every current writer sets it
+ * explicitly. Readers therefore keep handling a missing status.
*/
export enum InAppAgentRunStatus {
QUEUED = "QUEUED",
@@ -44,6 +44,23 @@ export enum InAppAgentRunErrorCode {
* turn must verify whether the effect landed before proposing again.
*/
OUTCOME_UNKNOWN = "outcome_unknown",
+ /** Run committed as QUEUED but the BullMQ enqueue failed right after. */
+ ENQUEUE_FAILED = "enqueue_failed",
+ /** QUEUED past `QUEUE_TIMEOUT`: no worker ever picked the run up. */
+ QUEUE_TIMEOUT = "queue_timeout",
+ /** RUNNING with a heartbeat older than `HEARTBEAT_STALE`: worker died. */
+ WORKER_LOST = "worker_lost",
+ /**
+ * RUNNING for longer than `RUN_MAX_DURATION` since claim — the backstop
+ * against a hung tool renewing an otherwise healthy heartbeat forever.
+ */
+ RUN_TIMEOUT = "run_timeout",
+ /** Approval parked longer than `APPROVAL_TTL` without a decision. */
+ APPROVAL_EXPIRED = "approval_expired",
+ /** Pending approval replaced by a newer user message (recorded on CANCELLED). */
+ APPROVAL_SUPERSEDED = "approval_superseded",
+ /** Pending approval cancelled by the user (recorded on CANCELLED). */
+ APPROVAL_CANCELLED = "approval_cancelled",
}
/**
diff --git a/packages/shared/src/in-app-agent/backgroundWatch.ts b/packages/shared/src/in-app-agent/backgroundWatch.ts
new file mode 100644
index 0000000000..f1c7180fd8
--- /dev/null
+++ b/packages/shared/src/in-app-agent/backgroundWatch.ts
@@ -0,0 +1,95 @@
+// Browser-safe approval and watch contracts shared by web and worker code.
+
+import { EventType } from "@ag-ui/core";
+import { z } from "zod";
+
+import {
+ InAppAgentRunStatus,
+ InAppAgentRunStatusSchema,
+} from "../features/inAppAgent/types";
+import type { AgUiCustomEvent, AgUiEvent } from "./schema";
+
+/** Render-only approval history stored in the append-only event stream. */
+export const IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME =
+ "langfuse_approval_decision";
+
+export const InAppAgentApprovalDecisionSchema = z.object({
+ toolCallId: z.string().min(1),
+ approved: z.boolean(),
+ decidedByUserId: z.string().min(1),
+});
+
+export type InAppAgentApprovalDecision = z.infer<
+ typeof InAppAgentApprovalDecisionSchema
+>;
+
+export function buildInAppAgentApprovalDecisionEvent(
+ decision: InAppAgentApprovalDecision,
+): AgUiCustomEvent {
+ return {
+ type: EventType.CUSTOM,
+ name: IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME,
+ value: decision,
+ };
+}
+
+export function parseInAppAgentApprovalDecisionEvent(
+ event: AgUiEvent,
+): InAppAgentApprovalDecision | undefined {
+ if (
+ event.type !== EventType.CUSTOM ||
+ event.name !== IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME
+ ) {
+ return undefined;
+ }
+
+ const parsed = InAppAgentApprovalDecisionSchema.safeParse(event.value);
+
+ return parsed.success ? parsed.data : undefined;
+}
+
+/** Conversation-scoped watch frames keyed by persisted sequence number. */
+export const InAppAgentWatchStatusFrameSchema = z.object({
+ type: z.literal("status"),
+ runId: z.string(),
+ status: InAppAgentRunStatusSchema,
+ errorCode: z.string().nullable().optional(),
+ /** Cancellation is cooperative, so this may be true while status is RUNNING. */
+ cancelRequested: z.boolean().optional(),
+});
+
+export const InAppAgentWatchEventFrameSchema = z.object({
+ type: z.literal("event"),
+ sequenceNumber: z.number().int(),
+ event: z.record(z.string(), z.unknown()),
+});
+
+export const InAppAgentWatchErrorFrameSchema = z.object({
+ type: z.literal("error"),
+ code: z.string(),
+ message: z.string(),
+});
+
+/** Only this frame tells clients to stop reconnecting. */
+export const InAppAgentWatchDoneFrameSchema = z.object({
+ type: z.literal("done"),
+});
+
+export const InAppAgentWatchFrameSchema = z.discriminatedUnion("type", [
+ InAppAgentWatchStatusFrameSchema,
+ InAppAgentWatchEventFrameSchema,
+ InAppAgentWatchErrorFrameSchema,
+ InAppAgentWatchDoneFrameSchema,
+]);
+
+export type InAppAgentWatchFrame = z.infer<typeof InAppAgentWatchFrameSchema>;
+
+/** A parked approval occupies neither a worker nor the conversation slot. */
+export const IN_APP_AGENT_ACTIVE_RUN_STATUSES: readonly InAppAgentRunStatus[] =
+ [InAppAgentRunStatus.QUEUED, InAppAgentRunStatus.RUNNING];
+
+export function isActiveInAppAgentRunStatus(
+ status: InAppAgentRunStatus,
+): boolean {
+ return IN_APP_AGENT_ACTIVE_RUN_STATUSES.includes(status);
+}
diff --git a/packages/shared/src/in-app-agent/index.ts b/packages/shared/src/in-app-agent/index.ts
index fe5a4bc660..df8453dc7c 100644
--- a/packages/shared/src/in-app-agent/index.ts
+++ b/packages/shared/src/in-app-agent/index.ts
@@ -2,5 +2,6 @@
// re-exported here — this barrel is imported by web client components and is
// covered by the client-bundle scan.
export * from "./schema";
+export * from "./backgroundWatch";
export * from "./constants";
export * from "./ids";
diff --git a/packages/shared/src/in-app-agent/server/access.ts b/packages/shared/src/in-app-agent/server/access.ts
new file mode 100644
index 0000000000..113cb42237
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/access.ts
@@ -0,0 +1,17 @@
+import { LangfuseNotFoundError } from "../../index";
+import type { InAppAgentConversation } from "../../db";
+
+/** Owner-only authorization with a non-enumerating failure. */
+export function assertConversationAccess(params: {
+ conversation: Pick<InAppAgentConversation, "createdByUserId" | "deletedAt">;
+ userId: string;
+}): void {
+ const { conversation } = params;
+
+ if (
+ conversation.deletedAt ||
+ conversation.createdByUserId !== params.userId
+ ) {
+ throw new LangfuseNotFoundError("Agent conversation not found");
+ }
+}
diff --git a/packages/shared/src/in-app-agent/server/index.ts b/packages/shared/src/in-app-agent/server/index.ts
index 7a7ee056c3..ed707db769 100644
--- a/packages/shared/src/in-app-agent/server/index.ts
+++ b/packages/shared/src/in-app-agent/server/index.ts
@@ -1,6 +1,7 @@
// Server entry of the in-app-agent runtime, consumed by web's foreground
// adapter (handler/router) and, once background execution ships, the worker
// queue processor.
+export * from "./access";
export * from "./agent";
export * from "./tools";
export * from "./human-in-the-loop";
@@ -9,6 +10,7 @@ export * from "./eventCompaction";
export * from "./persistence";
export * from "./runLifecycle";
export * from "./tunables";
+export * from "./watch";
export * from "./promptClient";
export * from "./skills";
export * from "./sandbox";
diff --git a/packages/shared/src/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.ts
index f6e620f99d..740e3bb267 100644
--- a/packages/shared/src/in-app-agent/server/persistence.ts
+++ b/packages/shared/src/in-app-agent/server/persistence.ts
@@ -30,6 +30,7 @@ import {
type AgUiEvent,
type AgUiMessage,
} from "../schema";
+import { assertConversationAccess } from "./access";
import { compactPersistedEventDeltas } from "./eventCompaction";
import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "../constants";
import { safeJsonParse } from "../../utils/json";
@@ -37,10 +38,10 @@ import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "./tools";
// Keep this close to the route maxDuration (120s) so a killed foreground stream
// does not block the conversation long after the route can no longer respond.
-const ACTIVE_RUN_STALE_AFTER_MS = 150 * 1000;
-const ACTIVE_RUN_CONFLICT_MESSAGE =
+export const FOREGROUND_RUN_STALE_AFTER_MS = 150 * 1000;
+export const ACTIVE_RUN_CONFLICT_MESSAGE =
"Assistant is already responding in this conversation";
-const STALE_RUN_ERROR_MESSAGE =
+export const FOREGROUND_RUN_STALE_ERROR_MESSAGE =
"Run was marked stale before starting a new run";
const SANDBOX_CONVERSATION_WRITE_WINDOW_MS = 8 * 60 * 60 * 1000;
@@ -56,6 +57,13 @@ export type PersistedConversationEvent = {
event: AgUiEvent;
runId: string;
createdAt: Date;
+ /**
+ * Per-conversation monotonic position. This is the watch cursor: the
+ * hydration snapshot's high-water mark is definitionally the maximum over
+ * the events it returned, so attaching the tail with `> cursor` is
+ * gap-free and duplicate-free by construction.
+ */
+ sequenceNumber: number;
};
export function serializeConversation(
@@ -76,7 +84,7 @@ export function serializeConversation(
export function isInAppAgentConversationWriteLocked(params: {
conversation: Pick<InAppAgentConversation, "createdAt">;
- events: readonly PersistedConversationEvent[];
+ events: readonly Pick<PersistedConversationEvent, "event">[];
now?: Date;
}) {
const now = params.now ?? new Date();
@@ -110,8 +118,6 @@ export async function getOwnedConversationOrThrow(params: {
where: {
id: params.conversationId,
projectId: params.projectId,
- createdByUserId: params.userId,
- deletedAt: null,
},
});
@@ -119,6 +125,11 @@ export async function getOwnedConversationOrThrow(params: {
throw new LangfuseNotFoundError("Agent conversation not found");
}
+ assertConversationAccess({
+ conversation,
+ userId: params.userId,
+ });
+
return conversation;
}
@@ -138,9 +149,10 @@ export async function ensureOwnedConversation(params: {
});
if (existing) {
- if (existing.createdByUserId !== params.userId || existing.deletedAt) {
- throw new LangfuseNotFoundError("Agent conversation not found");
- }
+ assertConversationAccess({
+ conversation: existing,
+ userId: params.userId,
+ });
return existing;
}
@@ -165,25 +177,35 @@ export async function createRun(params: {
mcpApiKeyId?: string;
}) {
const now = new Date();
- const staleBefore = new Date(now.getTime() - ACTIVE_RUN_STALE_AFTER_MS);
+ const staleBefore = new Date(now.getTime() - FOREGROUND_RUN_STALE_AFTER_MS);
return params.prisma.$transaction(async (tx) => {
await lockConversation(tx, params.projectId, params.conversationId);
- // The v1 agent is foreground-only. If a stream dies before finishRun runs,
- // lazily mark the old run stale so it does not block the conversation forever.
+ // If a foreground stream dies before finishRun runs, lazily mark the old
+ // run stale so it does not block the conversation forever.
+ //
+ // `claimedAt`/`heartbeatAt` must stay NULL here: only the background
+ // worker sets them, and a background run legitimately runs for up to
+ // RUN_MAX_DURATION. Without this guard a foreground submit (flag off)
+ // would stale-close a healthy background run at 150s and fence its
+ // worker — execution mode is not sticky per conversation, so that mix is
+ // a normal state. An unclaimed QUEUED run stays sweepable, which is what
+ // we want: it unblocks the conversation and reconcile-on-read agrees.
await tx.inAppAgentRun.updateMany({
where: {
projectId: params.projectId,
conversationId: params.conversationId,
finishedAt: null,
createdAt: { lt: staleBefore },
+ claimedAt: null,
+ heartbeatAt: null,
},
data: {
status: InAppAgentRunStatus.FAILED,
finishedAt: now,
errorCode: InAppAgentRunErrorCode.STALE,
- errorMessage: STALE_RUN_ERROR_MESSAGE,
+ errorMessage: FOREGROUND_RUN_STALE_ERROR_MESSAGE,
},
});
@@ -275,22 +297,53 @@ export async function appendRunEvents(params: {
conversationId: string;
runId: string;
events: readonly AgUiEvent[];
+ finish?: {
+ status:
+ | InAppAgentRunStatus.SUCCEEDED
+ | InAppAgentRunStatus.FAILED
+ | InAppAgentRunStatus.CANCELLED
+ | InAppAgentRunStatus.AWAITING_APPROVAL;
+ errorCode?: InAppAgentRunErrorCode;
+ errorMessage?: string;
+ };
}): Promise<boolean> {
return params.prisma.$transaction(async (tx) => {
await lockConversation(tx, params.projectId, params.conversationId);
- const activeRun = await tx.inAppAgentRun.findFirst({
- where: {
- id: params.runId,
- projectId: params.projectId,
- conversationId: params.conversationId,
- status: InAppAgentRunStatus.RUNNING,
- },
- select: { id: true },
- });
+ if (params.finish) {
+ const finished = await tx.inAppAgentRun.updateMany({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ status: InAppAgentRunStatus.RUNNING,
+ finishedAt: null,
+ },
+ data: {
+ status: params.finish.status,
+ finishedAt: new Date(),
+ errorCode: params.finish.errorCode ?? null,
+ errorMessage: params.finish.errorMessage ?? null,
+ },
+ });
- if (!activeRun) {
- return false;
+ if (finished.count === 0) {
+ return false;
+ }
+ } else {
+ const activeRun = await tx.inAppAgentRun.findFirst({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ status: InAppAgentRunStatus.RUNNING,
+ },
+ select: { id: true },
+ });
+
+ if (!activeRun) {
+ return false;
+ }
}
const latestEvent = await tx.inAppAgentEvent.findFirst({
@@ -344,13 +397,19 @@ export async function getConversationEvents(params: {
conversationId: params.conversationId,
},
orderBy: { sequenceNumber: "asc" },
- select: { event: true, runId: true, createdAt: true },
+ select: {
+ event: true,
+ runId: true,
+ createdAt: true,
+ sequenceNumber: true,
+ },
});
- return events.map(({ event, runId, createdAt }) => ({
+ return events.map(({ event, runId, createdAt, sequenceNumber }) => ({
event: event as unknown as AgUiEvent,
runId,
createdAt,
+ sequenceNumber,
}));
}
@@ -359,7 +418,7 @@ export async function getConversationEvents(params: {
* calls so each sandbox session can mount the same context.
*/
export function getSandboxToolCallFiles(
- events: readonly PersistedConversationEvent[],
+ events: readonly Omit<PersistedConversationEvent, "sequenceNumber">[],
) {
const drafts = new Map<
string,
@@ -442,7 +501,15 @@ export async function getConversationMessagesForDisplay(params: {
projectId: string;
conversationId: string;
}) {
- const messages = await getConversationMessages(params);
+ return getConversationMessagesForDisplayFromEvents(
+ await getConversationEvents(params),
+ );
+}
+
+export function getConversationMessagesForDisplayFromEvents(
+ events: readonly PersistedConversationEvent[],
+) {
+ const messages = getMessagesFromPersistedEvents(events);
return dropEmptyAssistantMessages(dropUnpairedAssistantToolCalls(messages));
}
@@ -707,10 +774,11 @@ export async function flushPendingRunEvents(params: {
conversationId: string;
runId: string;
pendingEvents: AgUiEvent[];
+ finish?: Parameters<typeof appendRunEvents>[0]["finish"];
}) {
const pendingEventCount = params.pendingEvents.length;
- if (pendingEventCount === 0) {
+ if (pendingEventCount === 0 && !params.finish) {
return;
}
@@ -718,13 +786,14 @@ export async function flushPendingRunEvents(params: {
params.pendingEvents.slice(0, pendingEventCount),
);
- if (eventsToAppend.length > 0) {
+ if (eventsToAppend.length > 0 || params.finish) {
const appended = await appendRunEvents({
prisma: params.prisma,
projectId: params.projectId,
conversationId: params.conversationId,
runId: params.runId,
events: eventsToAppend,
+ finish: params.finish,
});
if (!appended) {
@@ -1272,9 +1341,14 @@ function stripAssistantRunIds(messages: readonly AgUiMessage[]) {
return changed ? sanitizedMessages : messages;
}
-type InAppAgentTx = Prisma.TransactionClient;
+export type InAppAgentTx = Prisma.TransactionClient;
-async function lockConversation(
+/**
+ * Serializes every run-creating and approval-consuming mutation on one row.
+ * The partial unique index on active runs is only the backstop; this lock is
+ * what turns a race into a clean conflict error instead of a 500.
+ */
+export async function lockConversation(
tx: InAppAgentTx,
projectId: string,
conversationId: string,
diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.test.ts b/packages/shared/src/in-app-agent/server/runLifecycle.test.ts
new file mode 100644
index 0000000000..037269cd11
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/runLifecycle.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { InAppAgentRunStatus } from "../../index";
+import type { PrismaClient } from "../../db";
+import {
+ reconcileConversationRuns,
+ requestRunCancellation,
+} from "./runLifecycle";
+
+describe("in-app agent run lifecycle races", () => {
+ it("preserves cancellation when a worker claims the queued run concurrently", async () => {
+ let status: InAppAgentRunStatus = InAppAgentRunStatus.QUEUED;
+ let cancelRequestedAt: Date | null = null;
+
+ const tx = {
+ $queryRaw: vi.fn().mockResolvedValue([]),
+ inAppAgentRun: {
+ findFirst: vi.fn(async () => ({ status })),
+ updateMany: vi.fn(
+ async ({
+ where,
+ data,
+ }: {
+ where: { status: InAppAgentRunStatus };
+ data: {
+ status?: InAppAgentRunStatus;
+ cancelRequestedAt?: Date;
+ };
+ }) => {
+ if (where.status === InAppAgentRunStatus.QUEUED) {
+ status = InAppAgentRunStatus.RUNNING;
+ return { count: 0 };
+ }
+
+ if (
+ where.status === InAppAgentRunStatus.RUNNING &&
+ status === InAppAgentRunStatus.RUNNING
+ ) {
+ cancelRequestedAt = data.cancelRequestedAt ?? null;
+ return { count: 1 };
+ }
+
+ return { count: 0 };
+ },
+ ),
+ },
+ };
+ const prisma = {
+ $transaction: async (callback: (transaction: typeof tx) => unknown) =>
+ callback(tx),
+ } as unknown as PrismaClient;
+
+ await expect(
+ requestRunCancellation({
+ prisma,
+ projectId: "project-1",
+ conversationId: "conversation-1",
+ runId: "run-1",
+ }),
+ ).resolves.toEqual({
+ cancelledImmediately: false,
+ status: InAppAgentRunStatus.RUNNING,
+ });
+ expect(cancelRequestedAt).toBeInstanceOf(Date);
+ });
+
+ it("does not reconcile a worker-lost candidate after its heartbeat renews", async () => {
+ const observedHeartbeat = new Date(Date.now() - 90_000);
+ const renewedHeartbeat = new Date();
+ const updateMany = vi.fn(
+ async ({ where }: { where: { heartbeatAt?: Date | null } }) => ({
+ count:
+ where.heartbeatAt?.getTime() === renewedHeartbeat.getTime() ? 1 : 0,
+ }),
+ );
+ const tx = {
+ inAppAgentRun: {
+ findMany: vi.fn().mockResolvedValue([
+ {
+ id: "run-1",
+ status: InAppAgentRunStatus.RUNNING,
+ createdAt: new Date(Date.now() - 120_000),
+ claimedAt: new Date(Date.now() - 120_000),
+ heartbeatAt: observedHeartbeat,
+ finishedAt: null,
+ },
+ ]),
+ updateMany,
+ },
+ };
+ const prisma = {
+ $transaction: async (callback: (transaction: typeof tx) => unknown) =>
+ callback(tx),
+ } as unknown as PrismaClient;
+
+ await expect(
+ reconcileConversationRuns({
+ prisma,
+ projectId: "project-1",
+ conversationId: "conversation-1",
+ }),
+ ).resolves.toEqual([]);
+ expect(updateMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({ heartbeatAt: observedHeartbeat }),
+ }),
+ );
+ });
+});
diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.ts b/packages/shared/src/in-app-agent/server/runLifecycle.ts
index 7fcad28193..385e6ab85a 100644
--- a/packages/shared/src/in-app-agent/server/runLifecycle.ts
+++ b/packages/shared/src/in-app-agent/server/runLifecycle.ts
@@ -1,14 +1,30 @@
-import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "../../index";
+import {
+ InAppAgentRunErrorCode,
+ InAppAgentRunStatus,
+ InAppAgentRunStatusSchema,
+ LangfuseConflictError,
+} from "../../index";
+import { Prisma } from "../../db";
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 {
+ ACTIVE_RUN_CONFLICT_MESSAGE,
+ FOREGROUND_RUN_STALE_AFTER_MS,
+ FOREGROUND_RUN_STALE_ERROR_MESSAGE,
+ lockConversation,
+ type InAppAgentTx,
+} from "./persistence";
+import {
+ IN_APP_AGENT_APPROVAL_TTL_MS,
+ IN_APP_AGENT_HEARTBEAT_STALE_MS,
+ IN_APP_AGENT_QUEUE_TIMEOUT_MS,
+ IN_APP_AGENT_RUN_MAX_DURATION_MS,
+} from "./tunables";
-/**
- * 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.
- */
+/** Postgres-owned CAS transitions shared by web and worker execution. */
export async function claimQueuedRun(params: {
prisma: PrismaClient;
@@ -34,7 +50,7 @@ export async function claimQueuedRun(params: {
}
export type HeartbeatResult =
- /** The run is no longer RUNNING (reconciled away or cancelled directly): stop writing, no terminal CAS. */
+ /** The caller lost ownership and must stop writing. */
{ fenced: true } | { fenced: false; cancelRequestedAt: Date | null };
export async function heartbeatClaimedRun(params: {
@@ -65,13 +81,7 @@ export type TerminalRunStatus =
| 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.
- */
+/** Terminal CAS; a false result fences a worker that lost ownership. */
export async function finishClaimedRun(params: {
prisma: PrismaClient;
projectId: string;
@@ -98,10 +108,7 @@ export async function finishClaimedRun(params: {
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.
- */
+/** Clear the MCP-key pointer only after deletion succeeds. */
export async function clearRunMcpApiKeyPointer(params: {
prisma: PrismaClient;
projectId: string;
@@ -112,3 +119,563 @@ export async function clearRunMcpApiKeyPointer(params: {
data: { mcpApiKeyId: null },
});
}
+
+/**
+ * Atomically reconcile, enforce one active run, create QUEUED, and append its
+ * input event. A retry after a lost response observes the active-run conflict.
+ */
+export async function createQueuedRun(params: {
+ prisma: PrismaClient;
+ runId: string;
+ projectId: string;
+ conversationId: string;
+ triggeredByUserId: string;
+ model?: string;
+ request: InAppAgentRunRequest;
+ runStartedEvent: AgUiEvent;
+}): Promise<InAppAgentRun> {
+ return params.prisma.$transaction(async (tx) => {
+ await lockConversation(tx, params.projectId, params.conversationId);
+
+ await reconcileConversationRunsInTransaction({
+ tx,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+
+ // New input supersedes a parked approval.
+ await tx.inAppAgentRun.updateMany({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ },
+ data: {
+ status: InAppAgentRunStatus.CANCELLED,
+ errorCode: InAppAgentRunErrorCode.APPROVAL_SUPERSEDED,
+ errorMessage: "Replaced by a newer message",
+ },
+ });
+
+ const activeRun = await tx.inAppAgentRun.findFirst({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ finishedAt: null,
+ },
+ select: { id: true },
+ });
+
+ if (activeRun) {
+ throw new LangfuseConflictError(ACTIVE_RUN_CONFLICT_MESSAGE);
+ }
+
+ const run = await createRunRow(tx, {
+ runId: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ triggeredByUserId: params.triggeredByUserId,
+ model: params.model,
+ request: params.request,
+ });
+
+ await appendConversationEventInTransaction({
+ tx,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.runId,
+ event: params.runStartedEvent,
+ });
+
+ return run;
+ });
+}
+
+/** Record one approval decision and create its continuation under the lock. */
+export async function decideToolApproval(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ parentRunId: string;
+ continuationRunId: string;
+ toolCallId: string;
+ approved: boolean;
+ decidedByUserId: string;
+ model?: string;
+}): Promise<InAppAgentRun> {
+ const outcome = await params.prisma.$transaction(async (tx) => {
+ await lockConversation(tx, params.projectId, params.conversationId);
+
+ const parentRun = await tx.inAppAgentRun.findFirst({
+ where: {
+ id: params.parentRunId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ select: { status: true, finishedAt: true },
+ });
+
+ if (
+ !parentRun ||
+ parentRun.status !== InAppAgentRunStatus.AWAITING_APPROVAL
+ ) {
+ throw new LangfuseConflictError(
+ "This approval is no longer pending. Reload the conversation.",
+ );
+ }
+
+ const parkedAt = parentRun.finishedAt;
+ if (
+ parkedAt &&
+ Date.now() - parkedAt.getTime() > IN_APP_AGENT_APPROVAL_TTL_MS
+ ) {
+ await tx.inAppAgentRun.updateMany({
+ where: {
+ id: params.parentRunId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ },
+ data: {
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: InAppAgentRunErrorCode.APPROVAL_EXPIRED,
+ errorMessage: "The approval request expired",
+ },
+ });
+
+ return { type: "expired" as const };
+ }
+
+ // The parent CAS is the exactly-once decision guarantee.
+ const { count } = await tx.inAppAgentRun.updateMany({
+ where: {
+ id: params.parentRunId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ },
+ data: { status: InAppAgentRunStatus.SUCCEEDED },
+ });
+
+ if (count === 0) {
+ throw new LangfuseConflictError(
+ "This approval was already decided. Reload the conversation.",
+ );
+ }
+
+ await appendConversationEventInTransaction({
+ tx,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.parentRunId,
+ event: buildInAppAgentApprovalDecisionEvent({
+ toolCallId: params.toolCallId,
+ approved: params.approved,
+ decidedByUserId: params.decidedByUserId,
+ }),
+ });
+
+ return {
+ type: "continued" as const,
+ run: await createRunRow(tx, {
+ runId: params.continuationRunId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ triggeredByUserId: params.decidedByUserId,
+ model: params.model,
+ request: {
+ kind: "approvalDecision",
+ parentRunId: params.parentRunId,
+ toolCallId: params.toolCallId,
+ approved: params.approved,
+ },
+ }),
+ };
+ });
+
+ if (outcome.type === "expired") {
+ throw new LangfuseConflictError("The approval request expired.");
+ }
+
+ return outcome.run;
+}
+
+export type CancelRunResult = {
+ cancelledImmediately: boolean;
+ status: InAppAgentRunStatus | null;
+};
+
+/** Cancel idle states immediately; signal RUNNING workers cooperatively. */
+export async function requestRunCancellation(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+}): Promise<CancelRunResult> {
+ return params.prisma.$transaction(async (tx) => {
+ await lockConversation(tx, params.projectId, params.conversationId);
+
+ const run = await tx.inAppAgentRun.findFirst({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ select: { status: true },
+ });
+
+ const parsedStatus = InAppAgentRunStatusSchema.safeParse(run?.status);
+ if (!parsedStatus.success) {
+ return { cancelledImmediately: false, status: null };
+ }
+ const runStatus = parsedStatus.data;
+
+ const immediateCancel =
+ runStatus === InAppAgentRunStatus.QUEUED
+ ? {
+ errorCode: InAppAgentRunErrorCode.CANCELLED,
+ errorMessage: "Cancelled before a worker picked the run up",
+ }
+ : runStatus === InAppAgentRunStatus.AWAITING_APPROVAL
+ ? {
+ errorCode: InAppAgentRunErrorCode.APPROVAL_CANCELLED,
+ errorMessage: "Approval cancelled",
+ }
+ : null;
+
+ if (immediateCancel) {
+ const { count } = await tx.inAppAgentRun.updateMany({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: runStatus,
+ },
+ data: {
+ status: InAppAgentRunStatus.CANCELLED,
+ finishedAt: new Date(),
+ cancelRequestedAt: new Date(),
+ ...immediateCancel,
+ },
+ });
+
+ if (count > 0) {
+ return {
+ cancelledImmediately: true,
+ status: InAppAgentRunStatus.CANCELLED,
+ };
+ }
+ } else if (runStatus !== InAppAgentRunStatus.RUNNING) {
+ return {
+ cancelledImmediately: false,
+ status: runStatus,
+ };
+ }
+
+ // A worker can claim QUEUED between the read and immediate-cancel CAS.
+ // Signal the newly RUNNING worker instead of losing that cancel request.
+ const signalled = await tx.inAppAgentRun.updateMany({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.RUNNING,
+ },
+ data: { cancelRequestedAt: new Date() },
+ });
+
+ if (signalled.count > 0) {
+ return {
+ cancelledImmediately: false,
+ status: InAppAgentRunStatus.RUNNING,
+ };
+ }
+
+ const current = await tx.inAppAgentRun.findFirst({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ select: { status: true },
+ });
+
+ const parsedCurrentStatus = InAppAgentRunStatusSchema.safeParse(
+ current?.status,
+ );
+
+ return {
+ cancelledImmediately: false,
+ status: parsedCurrentStatus.success ? parsedCurrentStatus.data : null,
+ };
+ });
+}
+
+export type ReconciledRun = {
+ runId: string;
+ errorCode: InAppAgentRunErrorCode;
+};
+
+/** Reconcile stale lifecycle states on conversation reads (dispatch option C). */
+export async function reconcileConversationRuns(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+}): Promise<ReconciledRun[]> {
+ const reconciled = await params.prisma.$transaction((tx) =>
+ reconcileConversationRunsInTransaction({
+ tx,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ }),
+ );
+
+ return reconciled;
+}
+
+async function reconcileConversationRunsInTransaction(params: {
+ tx: InAppAgentTx;
+ projectId: string;
+ conversationId: string;
+}): Promise<ReconciledRun[]> {
+ const { tx, projectId, conversationId } = params;
+ const now = Date.now();
+
+ const candidates = await tx.inAppAgentRun.findMany({
+ where: {
+ projectId,
+ conversationId,
+ status: {
+ in: [
+ InAppAgentRunStatus.QUEUED,
+ InAppAgentRunStatus.RUNNING,
+ InAppAgentRunStatus.AWAITING_APPROVAL,
+ ],
+ },
+ },
+ select: {
+ id: true,
+ status: true,
+ createdAt: true,
+ claimedAt: true,
+ heartbeatAt: true,
+ finishedAt: true,
+ },
+ });
+
+ const reconciled: ReconciledRun[] = [];
+
+ for (const run of candidates) {
+ const failure = classifyStaleRun(run, now);
+ if (!failure) continue;
+
+ const { count } = await tx.inAppAgentRun.updateMany({
+ where: {
+ id: run.id,
+ projectId,
+ status: run.status,
+ ...(failure.errorCode === InAppAgentRunErrorCode.WORKER_LOST
+ ? {
+ claimedAt: run.claimedAt,
+ heartbeatAt: run.heartbeatAt,
+ }
+ : {}),
+ },
+ data: {
+ status: InAppAgentRunStatus.FAILED,
+ finishedAt: new Date(),
+ errorCode: failure.errorCode,
+ errorMessage: failure.errorMessage,
+ },
+ });
+
+ if (count > 0) {
+ reconciled.push({ runId: run.id, errorCode: failure.errorCode });
+ }
+ }
+
+ return reconciled;
+}
+
+function classifyStaleRun(
+ run: {
+ status: string | null;
+ createdAt: Date;
+ claimedAt: Date | null;
+ heartbeatAt: Date | null;
+ finishedAt: Date | null;
+ },
+ now: number,
+): { errorCode: InAppAgentRunErrorCode; errorMessage: string } | null {
+ if (run.status === InAppAgentRunStatus.QUEUED) {
+ return now - run.createdAt.getTime() > IN_APP_AGENT_QUEUE_TIMEOUT_MS
+ ? {
+ errorCode: InAppAgentRunErrorCode.QUEUE_TIMEOUT,
+ errorMessage: "No worker picked this run up",
+ }
+ : null;
+ }
+
+ if (run.status === InAppAgentRunStatus.RUNNING) {
+ if (
+ !run.claimedAt &&
+ !run.heartbeatAt &&
+ now - run.createdAt.getTime() > FOREGROUND_RUN_STALE_AFTER_MS
+ ) {
+ return {
+ errorCode: InAppAgentRunErrorCode.STALE,
+ errorMessage: FOREGROUND_RUN_STALE_ERROR_MESSAGE,
+ };
+ }
+
+ // Duration wins because a hung tool may keep renewing its heartbeat.
+ if (
+ run.claimedAt &&
+ now - run.claimedAt.getTime() > IN_APP_AGENT_RUN_MAX_DURATION_MS
+ ) {
+ return {
+ errorCode: InAppAgentRunErrorCode.RUN_TIMEOUT,
+ errorMessage: "The run exceeded the maximum duration",
+ };
+ }
+
+ const lastSign = run.heartbeatAt ?? run.claimedAt;
+ return lastSign &&
+ now - lastSign.getTime() > IN_APP_AGENT_HEARTBEAT_STALE_MS
+ ? {
+ errorCode: InAppAgentRunErrorCode.WORKER_LOST,
+ errorMessage: "The run was interrupted",
+ }
+ : null;
+ }
+
+ if (run.status === InAppAgentRunStatus.AWAITING_APPROVAL) {
+ const parkedAt = run.finishedAt;
+ return parkedAt && now - parkedAt.getTime() > IN_APP_AGENT_APPROVAL_TTL_MS
+ ? {
+ errorCode: InAppAgentRunErrorCode.APPROVAL_EXPIRED,
+ errorMessage: "The approval request expired",
+ }
+ : null;
+ }
+
+ return null;
+}
+
+/** Retry terminal-run MCP-key cleanup outside the lifecycle transaction. */
+export async function cleanupTerminalRunMcpApiKeys(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ deleteApiKey: (apiKeyId: string) => Promise<void>;
+}): Promise<number> {
+ const staleKeyRuns = await params.prisma.inAppAgentRun.findMany({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ finishedAt: { not: null },
+ mcpApiKeyId: { not: null },
+ },
+ select: { id: true, mcpApiKeyId: true },
+ });
+
+ let cleaned = 0;
+
+ for (const run of staleKeyRuns) {
+ if (!run.mcpApiKeyId) continue;
+
+ try {
+ await params.deleteApiKey(run.mcpApiKeyId);
+ await clearRunMcpApiKeyPointer({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ runId: run.id,
+ });
+ cleaned += 1;
+ } catch (error) {
+ logger.error("Failed to clean up in-app agent MCP key on reconcile", {
+ projectId: params.projectId,
+ runId: run.id,
+ error,
+ });
+ }
+ }
+
+ return cleaned;
+}
+
+async function createRunRow(
+ tx: InAppAgentTx,
+ params: {
+ runId: string;
+ projectId: string;
+ conversationId: string;
+ triggeredByUserId: string;
+ model?: string;
+ request: InAppAgentRunRequest;
+ },
+): Promise<InAppAgentRun> {
+ try {
+ return await tx.inAppAgentRun.create({
+ data: {
+ id: params.runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ triggeredByUserId: params.triggeredByUserId,
+ model: params.model,
+ status: InAppAgentRunStatus.QUEUED,
+ request: params.request,
+ },
+ });
+ } catch (error) {
+ // Map only the active-run unique index; a replayed run ID remains a 500.
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002" &&
+ Array.isArray(error.meta?.target) &&
+ error.meta.target.includes("conversation_id")
+ ) {
+ throw new LangfuseConflictError(ACTIVE_RUN_CONFLICT_MESSAGE);
+ }
+ throw error;
+ }
+}
+
+/** Append a web-authored event while holding the conversation lock. */
+async function appendConversationEventInTransaction(params: {
+ tx: InAppAgentTx;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+ event: AgUiEvent;
+}): Promise<number> {
+ const latestEvent = await params.tx.inAppAgentEvent.findFirst({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ orderBy: { sequenceNumber: "desc" },
+ select: { sequenceNumber: true },
+ });
+
+ const sequenceNumber = (latestEvent?.sequenceNumber ?? -1) + 1;
+
+ await params.tx.inAppAgentEvent.create({
+ data: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.runId,
+ sequenceNumber,
+ type: String(params.event.type),
+ event: params.event as unknown as Prisma.InputJsonValue,
+ },
+ });
+
+ await params.tx.inAppAgentConversation.update({
+ where: {
+ id_projectId: {
+ id: params.conversationId,
+ projectId: params.projectId,
+ },
+ },
+ data: { updatedAt: new Date() },
+ });
+
+ return sequenceNumber;
+}
diff --git a/packages/shared/src/in-app-agent/server/tunables.ts b/packages/shared/src/in-app-agent/server/tunables.ts
index da6580bed0..b689310cc6 100644
--- a/packages/shared/src/in-app-agent/server/tunables.ts
+++ b/packages/shared/src/in-app-agent/server/tunables.ts
@@ -1,46 +1,44 @@
-/**
- * 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;
-}
+import { env } from "../../env";
/** 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,
-);
+export const IN_APP_AGENT_HEARTBEAT_INTERVAL_MS =
+ env.LANGFUSE_IN_APP_AGENT_HEARTBEAT_INTERVAL_MS;
/** 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,
-);
+export const IN_APP_AGENT_HEARTBEAT_STALE_MS =
+ env.LANGFUSE_IN_APP_AGENT_HEARTBEAT_STALE_MS;
/** 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,
-);
+export const IN_APP_AGENT_QUEUE_TIMEOUT_MS =
+ env.LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS;
/**
* 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,
-);
+export const IN_APP_AGENT_RUN_MAX_DURATION_MS =
+ env.LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS;
/** 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,
-);
+export const IN_APP_AGENT_APPROVAL_TTL_MS =
+ env.LANGFUSE_IN_APP_AGENT_APPROVAL_TTL_MS;
+
+/** Interval at which the watch stream re-reads run status + new events. */
+export const IN_APP_AGENT_WATCH_TAIL_POLL_MS =
+ env.LANGFUSE_IN_APP_AGENT_WATCH_TAIL_POLL_MS;
+
+/** SSE comment interval, so load-balancer idle timeouts never fire. */
+export const IN_APP_AGENT_WATCH_KEEPALIVE_MS =
+ env.LANGFUSE_IN_APP_AGENT_WATCH_KEEPALIVE_MS;
+
+/** Reconcile on attach, then independently from the event polling cadence. */
+export const IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS =
+ env.LANGFUSE_IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS;
+
+/**
+ * Deliberate stream end; the client reconnects with its cursor through the
+ * same path as a fresh page load, so route/LB duration limits are never hit
+ * unpredictably. Kept well inside the watch route's 120s `maxDuration`.
+ */
+export const IN_APP_AGENT_WATCH_MAX_CONNECTION_MS =
+ env.LANGFUSE_IN_APP_AGENT_WATCH_MAX_CONNECTION_MS;
diff --git a/packages/shared/src/in-app-agent/server/watch.test.ts b/packages/shared/src/in-app-agent/server/watch.test.ts
new file mode 100644
index 0000000000..ba6edada0c
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/watch.test.ts
@@ -0,0 +1,328 @@
+import { EventType } from "@ag-ui/core";
+import { describe, expect, it } from "vitest";
+
+import { InAppAgentRunStatus } from "../../index";
+import type { PrismaClient } from "../../db";
+import type { InAppAgentWatchFrame } from "../backgroundWatch";
+import { watchConversationFrames } from "./watch";
+
+/**
+ * The framing rules are what these tests protect, so the data source is a
+ * fake: `@ag-ui/client` rejects a stream whose first event is not
+ * `RUN_STARTED` and rejects events after `RUN_FINISHED`, and getting that
+ * wrong is a runtime throw in the drawer that no type check can catch.
+ */
+type EventRow = {
+ sequenceNumber: number;
+ runId: string;
+ event: Record<string, unknown>;
+};
+
+type RunRow = {
+ id: string;
+ status: InAppAgentRunStatus;
+ errorCode: string | null;
+ cancelRequestedAt?: Date | null;
+};
+
+function fakePrisma(polls: Array<{ events: EventRow[]; run: RunRow | null }>) {
+ let pollIndex = 0;
+ const inAppAgentRun = {
+ findMany: async () => [],
+ updateMany: async () => ({ count: 0 }),
+ findFirst: async () =>
+ polls[Math.min(pollIndex, polls.length - 1)]?.run ?? null,
+ };
+ const inAppAgentEvent = {
+ findMany: async ({
+ where,
+ }: {
+ where: { sequenceNumber: { gt: number } };
+ }) => {
+ const poll = polls[Math.min(pollIndex, polls.length - 1)];
+ pollIndex += 1;
+
+ return (poll?.events ?? []).filter(
+ (row) => row.sequenceNumber > where.sequenceNumber.gt,
+ );
+ },
+ };
+ return {
+ $transaction: async (fn: (tx: unknown) => Promise<unknown>) =>
+ fn({
+ inAppAgentRun,
+ inAppAgentEvent,
+ }),
+ inAppAgentRun,
+ inAppAgentEvent,
+ } as unknown as PrismaClient;
+}
+
+async function collect(
+ prisma: PrismaClient,
+ cursor: number,
+): Promise<InAppAgentWatchFrame[]> {
+ const frames: InAppAgentWatchFrame[] = [];
+
+ for await (const frame of watchConversationFrames({
+ prisma,
+ projectId: "project-1",
+ conversationId: "conversation-1",
+ cursor,
+ now: () => 0,
+ sleep: async () => undefined,
+ })) {
+ if (frame !== null) {
+ frames.push(frame);
+ }
+ }
+
+ return frames;
+}
+
+const eventFrames = (frames: InAppAgentWatchFrame[]) =>
+ frames.filter(
+ (frame): frame is Extract<InAppAgentWatchFrame, { type: "event" }> =>
+ frame.type === "event",
+ );
+
+const eventTypes = (frames: InAppAgentWatchFrame[]) =>
+ eventFrames(frames).map((frame) => frame.event.type);
+
+describe("watchConversationFrames", () => {
+ const runStarted = (runId: string, sequenceNumber: number): EventRow => ({
+ sequenceNumber,
+ runId,
+ event: {
+ type: EventType.RUN_STARTED,
+ runId,
+ threadId: "conversation-1",
+ // The persisted row carries the turn's input; the worker's replay reads
+ // the user message out of it.
+ input: {
+ runId,
+ messages: [{ id: "server-minted-id", role: "user", content: "hi" }],
+ },
+ },
+ });
+
+ const textMessage = (runId: string, sequenceNumber: number): EventRow => ({
+ sequenceNumber,
+ runId,
+ event: {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId: `m-${sequenceNumber}`,
+ },
+ });
+
+ const runFinished = (runId: string, sequenceNumber: number): EventRow => ({
+ sequenceNumber,
+ runId,
+ event: { type: EventType.RUN_FINISHED, runId, threadId: "conversation-1" },
+ });
+
+ const succeeded: RunRow = {
+ id: "run-1",
+ status: InAppAgentRunStatus.SUCCEEDED,
+ errorCode: null,
+ cancelRequestedAt: null,
+ };
+
+ it("relays a finished run verbatim and closes with a done frame", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [
+ runStarted("run-1", 0),
+ textMessage("run-1", 1),
+ runFinished("run-1", 2),
+ ],
+ run: succeeded,
+ },
+ ]),
+ -1,
+ );
+
+ // No synthetic twin for the boundaries the worker already persisted.
+ expect(eventTypes(frames)).toEqual([
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.RUN_FINISHED,
+ ]);
+ expect(frames.at(-1)).toEqual({ type: "done" });
+ expect(frames.filter((frame) => frame.type === "status")).toEqual([
+ {
+ type: "status",
+ runId: "run-1",
+ status: InAppAgentRunStatus.SUCCEEDED,
+ errorCode: null,
+ cancelRequested: false,
+ },
+ ]);
+ });
+
+ it("opens the run synthetically when attaching mid-run, without skipping the event it frames", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [textMessage("run-1", 1), runFinished("run-1", 2)],
+ run: succeeded,
+ },
+ ]),
+ // The client hydrated through the persisted RUN_STARTED at 0.
+ 0,
+ );
+
+ expect(eventTypes(frames)).toEqual([
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.RUN_FINISHED,
+ ]);
+
+ // A drop right after the synthetic frame must re-read event 1, not skip it.
+ expect(eventFrames(frames)[0]?.sequenceNumber).toBe(0);
+ });
+
+ it("hands off from cursor to tail with no duplicated and no missed event", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [textMessage("run-1", 1)],
+ run: { ...succeeded, status: InAppAgentRunStatus.RUNNING },
+ },
+ {
+ events: [
+ textMessage("run-1", 1),
+ textMessage("run-1", 2),
+ runFinished("run-1", 3),
+ ],
+ run: succeeded,
+ },
+ ]),
+ 0,
+ );
+
+ const sequences = eventFrames(frames).map((frame) => frame.sequenceNumber);
+
+ // 0 is the synthetic open; 1, 2, 3 are each relayed exactly once even
+ // though poll two re-reported event 1 as still present.
+ expect(sequences).toEqual([0, 1, 2, 3]);
+ });
+
+ it("closes a terminal run whose stream never persisted its own RUN_FINISHED", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [runStarted("run-1", 0), textMessage("run-1", 1)],
+ run: {
+ id: "run-1",
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: "worker_lost",
+ },
+ },
+ ]),
+ -1,
+ );
+
+ // Without the synthetic close, the client's verifier would reject the next
+ // run's RUN_STARTED on this stream.
+ expect(eventTypes(frames)).toEqual([
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.RUN_FINISHED,
+ ]);
+ expect(frames.at(-1)).toEqual({ type: "done" });
+ });
+
+ it("re-emits status when a cancel is requested while the run is still RUNNING", async () => {
+ const running: RunRow = {
+ ...succeeded,
+ status: InAppAgentRunStatus.RUNNING,
+ };
+
+ const frames = await collect(
+ fakePrisma([
+ { events: [runStarted("run-1", 0)], run: running },
+ {
+ events: [],
+ run: { ...running, cancelRequestedAt: new Date(1) },
+ },
+ { events: [runFinished("run-1", 1)], run: { ...succeeded } },
+ ]),
+ -1,
+ );
+
+ const statuses = frames.filter((frame) => frame.type === "status");
+
+ // Status is deduplicated by key, so the cancel flag has to be part of that
+ // key: it flips while the status is still RUNNING, and if that frame is
+ // swallowed the drawer shows no sign that a stop is in flight.
+ expect(statuses).toMatchObject([
+ { status: InAppAgentRunStatus.RUNNING, cancelRequested: false },
+ { status: InAppAgentRunStatus.RUNNING, cancelRequested: true },
+ { status: InAppAgentRunStatus.SUCCEEDED, cancelRequested: false },
+ ]);
+ });
+
+ it("strips RUN_STARTED input so the submitted message is not rendered twice", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [runStarted("run-1", 0), runFinished("run-1", 1)],
+ run: succeeded,
+ },
+ ]),
+ -1,
+ );
+
+ // @ag-ui/client seeds agent.messages from RUN_STARTED.input.messages and
+ // dedupes by id only. The submitting client already added the message under
+ // its own id, so relaying the server's id renders the turn twice.
+ const relayedRunStarted = eventFrames(frames).find(
+ (frame) => frame.event.type === EventType.RUN_STARTED,
+ );
+
+ expect(relayedRunStarted?.event).not.toHaveProperty("input");
+ expect(relayedRunStarted?.event).toMatchObject({
+ type: EventType.RUN_STARTED,
+ runId: "run-1",
+ });
+ });
+
+ it("closes immediately when the conversation has no run with a readable status", async () => {
+ // Legacy rows predate the status column, and the column is deliberately
+ // still nullable. Polling such a conversation forever would reconnect in a
+ // loop for a run that is not executing.
+ const frames = await collect(fakePrisma([{ events: [], run: null }]), -1);
+
+ expect(frames).toEqual([{ type: "done" }]);
+ });
+
+ it("closes one run and opens the next when a continuation follows", async () => {
+ const frames = await collect(
+ fakePrisma([
+ {
+ events: [
+ runStarted("run-1", 0),
+ textMessage("run-1", 1),
+ // The parked parent never wrote RUN_FINISHED; the continuation's
+ // first row is a plain event, not a RUN_STARTED.
+ textMessage("run-2", 2),
+ runFinished("run-2", 3),
+ ],
+ run: { ...succeeded, id: "run-2" },
+ },
+ ]),
+ -1,
+ );
+
+ expect(eventTypes(frames)).toEqual([
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.RUN_FINISHED,
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.RUN_FINISHED,
+ ]);
+ });
+});
diff --git a/packages/shared/src/in-app-agent/server/watch.ts b/packages/shared/src/in-app-agent/server/watch.ts
new file mode 100644
index 0000000000..ab83b7d8bd
--- /dev/null
+++ b/packages/shared/src/in-app-agent/server/watch.ts
@@ -0,0 +1,201 @@
+import { EventType } from "@ag-ui/core";
+
+import { InAppAgentRunStatusSchema } from "../../index";
+import { Prisma, type PrismaClient } from "../../db";
+import {
+ isActiveInAppAgentRunStatus,
+ type InAppAgentWatchFrame,
+} from "../backgroundWatch";
+import type { AgUiEvent } from "../schema";
+import { reconcileConversationRuns } from "./runLifecycle";
+import {
+ IN_APP_AGENT_WATCH_KEEPALIVE_MS,
+ IN_APP_AGENT_WATCH_MAX_CONNECTION_MS,
+ IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS,
+ IN_APP_AGENT_WATCH_TAIL_POLL_MS,
+} from "./tunables";
+
+/**
+ * Tail persisted events while preserving AG-UI run framing. Synthetic frames
+ * never advance beyond the event they frame, so reconnect cannot skip a row.
+ * `null` asks the SSE transport to emit a keep-alive comment.
+ */
+export async function* watchConversationFrames(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ cursor: number;
+ signal?: AbortSignal;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+}): AsyncGenerator<InAppAgentWatchFrame | null> {
+ const now = params.now ?? (() => Date.now());
+ const sleep =
+ params.sleep ??
+ ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
+
+ const startedAt = now();
+ let cursor = params.cursor;
+ let lastKeepaliveAt = startedAt;
+ let lastReconciledAt: number | null = null;
+ let openRunId: string | null = null;
+ let lastStatusKey: string | null = null;
+
+ while (!params.signal?.aborted) {
+ if (
+ lastReconciledAt === null ||
+ now() - lastReconciledAt >= IN_APP_AGENT_WATCH_RECONCILE_INTERVAL_MS
+ ) {
+ await reconcileConversationRuns({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+ lastReconciledAt = now();
+ }
+
+ // Read status first: terminal CAS happens after the worker appends events.
+ const { latestRun, events } = await params.prisma.$transaction(
+ async (tx) => ({
+ latestRun: await tx.inAppAgentRun.findFirst({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ orderBy: { createdAt: "desc" },
+ select: {
+ id: true,
+ status: true,
+ errorCode: true,
+ cancelRequestedAt: true,
+ },
+ }),
+ events: await tx.inAppAgentEvent.findMany({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ sequenceNumber: { gt: cursor },
+ },
+ orderBy: { sequenceNumber: "asc" },
+ select: { sequenceNumber: true, runId: true, event: true },
+ }),
+ }),
+ { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
+ );
+
+ for (const row of events) {
+ const event = row.event as unknown as AgUiEvent;
+
+ if (openRunId !== row.runId) {
+ if (openRunId) {
+ yield syntheticFrame(row.sequenceNumber - 1, {
+ type: EventType.RUN_FINISHED,
+ threadId: params.conversationId,
+ runId: openRunId,
+ });
+ }
+
+ if (event.type !== EventType.RUN_STARTED) {
+ yield syntheticFrame(row.sequenceNumber - 1, {
+ type: EventType.RUN_STARTED,
+ threadId: params.conversationId,
+ runId: row.runId,
+ });
+ }
+
+ openRunId = row.runId;
+ }
+
+ yield {
+ type: "event",
+ sequenceNumber: row.sequenceNumber,
+ event: toPublicEvent(event),
+ };
+
+ if (
+ event.type === EventType.RUN_FINISHED ||
+ event.type === EventType.RUN_ERROR
+ ) {
+ openRunId = null;
+ }
+
+ cursor = row.sequenceNumber;
+ }
+
+ // Legacy rows may have no status and cannot be watched as active runs.
+ if (!latestRun) {
+ yield { type: "done" };
+ return;
+ }
+
+ const parsedStatus = InAppAgentRunStatusSchema.safeParse(latestRun.status);
+ if (!parsedStatus.success) {
+ yield { type: "done" };
+ return;
+ }
+
+ const status = parsedStatus.data;
+ const cancelRequested = Boolean(latestRun.cancelRequestedAt);
+ const statusKey = `${latestRun.id}:${status}:${cancelRequested}`;
+
+ if (statusKey !== lastStatusKey) {
+ lastStatusKey = statusKey;
+ yield {
+ type: "status",
+ runId: latestRun.id,
+ status,
+ errorCode: latestRun.errorCode,
+ cancelRequested,
+ };
+ }
+
+ if (!isActiveInAppAgentRunStatus(status)) {
+ // Close runs that terminated without persisting RUN_FINISHED.
+ if (openRunId) {
+ yield syntheticFrame(cursor, {
+ type: EventType.RUN_FINISHED,
+ threadId: params.conversationId,
+ runId: openRunId,
+ });
+ openRunId = null;
+ }
+
+ yield { type: "done" };
+ return;
+ }
+
+ if (now() - startedAt >= IN_APP_AGENT_WATCH_MAX_CONNECTION_MS) {
+ return;
+ }
+
+ if (now() - lastKeepaliveAt >= IN_APP_AGENT_WATCH_KEEPALIVE_MS) {
+ lastKeepaliveAt = now();
+ yield null;
+ }
+
+ await sleep(IN_APP_AGENT_WATCH_TAIL_POLL_MS);
+ }
+}
+
+/** Match foreground streaming by withholding persisted replay input. */
+function toPublicEvent(event: AgUiEvent): AgUiEvent {
+ if (event.type !== EventType.RUN_STARTED || event.input === undefined) {
+ return event;
+ }
+
+ const publicEvent = { ...event };
+ delete publicEvent.input;
+
+ return publicEvent;
+}
+
+function syntheticFrame(
+ cursor: number,
+ event: AgUiEvent,
+): InAppAgentWatchFrame {
+ return {
+ type: "event",
+ sequenceNumber: cursor,
+ event,
+ };
+}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index fe588d7e7e..814d0232af 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -92,6 +92,7 @@ export * from "./redis/cloudFreeTierUsageThresholdQueue";
export * from "./redis/getQueue";
export * from "./redis/webhookQueue";
export * from "./redis/monitorQueue";
+export * from "./redis/inAppAgentRunQueue";
export * from "./redis/traceDelete";
export * from "./redis/projectDelete";
export * from "./redis/scoreDelete";
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 9cdfc7099b..0f6e9d5235 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
@@ -93,6 +93,7 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({
describe("in-app agent public API route auth", () => {
beforeEach(() => {
vi.clearAllMocks();
+ entitlementMocks.hasEntitlement.mockReturnValue(true);
agentMocks.createAgUiStream.mockResolvedValue(new ReadableStream());
langfuseClientMocks.getLangfuseClient.mockReturnValue({});
rateLimitMocks.rateLimitRequest.mockResolvedValue({
@@ -344,6 +345,209 @@ describe("in-app agent public API route auth", () => {
});
});
+ describe("background watch route authorization", () => {
+ async function setupWatchConversation() {
+ const { org, project } = await createOrgProjectAndApiKey();
+ const userId = `watch-owner-${randomUUID()}`;
+ const conversationId = `conversation-${randomUUID()}`;
+
+ await prisma.organization.update({
+ where: { id: org.id },
+ data: { aiFeaturesEnabled: true },
+ });
+ await prisma.user.create({
+ data: {
+ id: userId,
+ email: `${userId}@example.com`,
+ },
+ });
+ await prisma.inAppAgentConversation.create({
+ data: {
+ id: conversationId,
+ projectId: project.id,
+ createdByUserId: userId,
+ title: "Watch authorization test",
+ },
+ });
+
+ return { conversationId, org, project, userId };
+ }
+
+ async function callWatchRoute(params: {
+ projectId: string;
+ conversationId: string;
+ }) {
+ const { default: watchHandler } =
+ await import("@/src/features/in-app-agent/server/watchHandler");
+
+ return watchHandler(
+ new Request(
+ `http://localhost/api/in-app-agent/watch?projectId=${params.projectId}&conversationId=${params.conversationId}&cursor=-1`,
+ ),
+ );
+ }
+
+ it("allows the owner to watch the project-scoped conversation", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, org, project, userId } =
+ await setupWatchConversation();
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ userId,
+ }),
+ );
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-type")).toContain(
+ "text/event-stream",
+ );
+ await expect(response.text()).resolves.toContain("event: done");
+ });
+ });
+
+ it("rejects an unauthenticated watch", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, project } = await setupWatchConversation();
+ authMocks.getServerSession.mockResolvedValue(null);
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(401);
+ });
+ });
+
+ it("rejects a watcher without project membership", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, org, project, userId } =
+ await setupWatchConversation();
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ userId,
+ includeProjectMembership: false,
+ }),
+ );
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(403);
+ });
+ });
+
+ it("rejects a watcher without the in-app-agent entitlement", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, org, project, userId } =
+ await setupWatchConversation();
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ userId,
+ }),
+ );
+ entitlementMocks.hasEntitlement.mockReturnValue(false);
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(403);
+ });
+ });
+
+ it("rejects a watch when organization AI features are disabled", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, org, project, userId } =
+ await setupWatchConversation();
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ userId,
+ }),
+ );
+ await prisma.organization.update({
+ where: { id: org.id },
+ data: { aiFeaturesEnabled: false },
+ });
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(403);
+ });
+ });
+
+ it("does not reveal a conversation to another project member", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, org, project } = await setupWatchConversation();
+ const otherUserId = `watch-member-${randomUUID()}`;
+ await prisma.user.create({
+ data: {
+ id: otherUserId,
+ email: `${otherUserId}@example.com`,
+ },
+ });
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: org.id,
+ projectId: project.id,
+ userId: otherUserId,
+ }),
+ );
+
+ const response = await callWatchRoute({
+ projectId: project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ it("does not resolve a conversation through another project", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { conversationId, userId } = await setupWatchConversation();
+ const other = await createOrgProjectAndApiKey();
+ await prisma.organization.update({
+ where: { id: other.org.id },
+ data: { aiFeaturesEnabled: true },
+ });
+ authMocks.getServerSession.mockResolvedValue(
+ createInAppAgentSession({
+ orgId: other.org.id,
+ projectId: other.project.id,
+ userId,
+ }),
+ );
+
+ const response = await callWatchRoute({
+ projectId: other.project.id,
+ conversationId,
+ });
+
+ expect(response.status).toBe(404);
+ });
+ });
+ });
+
it("does not create a mutating tool override for rejected approvals", async () => {
await withInAppAgentCloudEnv(async () => {
const { project, userId } = await setupInAppAgentProjectSession();
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
new file mode 100644
index 0000000000..ff99f66256
--- /dev/null
+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
@@ -0,0 +1,858 @@
+/**
+ * Behavioral coverage for the background execution surface: submit, cancel,
+ * decide, and reconcile-on-read. These go through the tRPC callers rather than
+ * the lifecycle helpers directly, because the contracts worth protecting are
+ * the ones a browser can actually reach.
+ */
+import type { Session } from "next-auth";
+import type { Flags } from "@/src/features/feature-flags/types";
+import { EventType } from "@ag-ui/core";
+import { randomUUID } from "crypto";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ InAppAgentRunErrorCode,
+ InAppAgentRunStatus,
+ type Plan,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import {
+ createInAppAgentConversationId,
+ createInAppAgentRunId,
+ IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME,
+} from "@langfuse/shared/in-app-agent";
+import { ensureOwnedConversation } from "@langfuse/shared/in-app-agent/server/persistence";
+import { env } from "@/src/env.mjs";
+import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+
+import type * as SharedServerModule from "@langfuse/shared/src/server";
+
+const enqueuedJobs: Array<{ name: string; payload: unknown; jobId?: string }> =
+ [];
+let enqueueShouldFail = false;
+
+const rateLimitMocks = vi.hoisted(() => ({
+ rateLimitRequest: vi.fn(),
+}));
+
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual<typeof SharedServerModule>(
+ "@langfuse/shared/src/server",
+ );
+
+ return {
+ ...actual,
+ InAppAgentRunQueue: {
+ getInstance: () => ({
+ add: (name: string, payload: unknown, options?: { jobId?: string }) => {
+ if (enqueueShouldFail) {
+ throw new Error("queue unavailable");
+ }
+ enqueuedJobs.push({ name, payload, jobId: options?.jobId });
+ return Promise.resolve();
+ },
+ remove: () => Promise.resolve(),
+ }),
+ },
+ };
+});
+
+vi.mock("@/src/features/public-api/server/RateLimitService", () => ({
+ RateLimitService: {
+ getInstance: () => ({
+ rateLimitRequest: rateLimitMocks.rateLimitRequest,
+ }),
+ },
+}));
+
+vi.mock("@/src/server/auth", () => ({
+ getServerAuthSession: vi.fn(),
+}));
+
+describe("in-app agent background runs", () => {
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
+
+ beforeEach(() => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";
+ enqueuedJobs.length = 0;
+ enqueueShouldFail = false;
+ rateLimitMocks.rateLimitRequest.mockResolvedValue({
+ isRateLimited: () => false,
+ res: undefined,
+ });
+ });
+
+ afterEach(() => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;
+ });
+
+ const createCaller = async (
+ userId = `user-${randomUUID()}`,
+ plan: Plan = "cloud:hobby",
+ ) => {
+ const setup = await createOrgProjectAndApiKey();
+
+ await prisma.organization.update({
+ where: { id: setup.orgId },
+ data: { aiFeaturesEnabled: true },
+ });
+
+ await prisma.user.create({
+ data: { id: userId, email: `${userId}@example.com` },
+ });
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: userId,
+ name: "Agent User",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: setup.orgId,
+ role: "OWNER",
+ plan,
+ cloudConfig: undefined,
+ name: "Test Organization",
+ metadata: {},
+ aiFeaturesEnabled: true,
+ aiTelemetryEnabled: false,
+ projects: [
+ {
+ id: setup.projectId,
+ role: "ADMIN",
+ name: "Test Project",
+ deletedAt: null,
+ retentionDays: null,
+ hasTraces: false,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {} as Flags,
+ admin: false,
+ },
+ environment: {} as any,
+ };
+
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+
+ return {
+ ...setup,
+ userId,
+ caller: inAppAgentRouter.createCaller({ ...ctx, prisma }),
+ };
+ };
+
+ const createConversation = async (params: {
+ projectId: string;
+ userId: string;
+ }) =>
+ ensureOwnedConversation({
+ prisma,
+ projectId: params.projectId,
+ conversationId: createInAppAgentConversationId(),
+ userId: params.userId,
+ });
+
+ /** Park a run for approval the way the worker does: interrupt event, then CAS. */
+ const parkRunForApproval = async (params: {
+ projectId: string;
+ conversationId: string;
+ userId: string;
+ toolCallId: string;
+ parkedAt?: Date;
+ }) => {
+ const runId = createInAppAgentRunId();
+
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: runId,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ triggeredByUserId: params.userId,
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ finishedAt: params.parkedAt ?? new Date(),
+ request: { kind: "userMessage", context: [] },
+ },
+ });
+
+ await prisma.inAppAgentEvent.create({
+ data: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId,
+ sequenceNumber: 0,
+ type: EventType.CUSTOM,
+ event: {
+ type: EventType.CUSTOM,
+ name: "on_interrupt",
+ value: {
+ type: "mastra_suspend",
+ toolCallId: params.toolCallId,
+ toolName: "langfuse_createTextPrompt",
+ args: { name: "from-persisted-event" },
+ runId,
+ },
+ },
+ },
+ });
+
+ return runId;
+ };
+
+ it("commits a queued run with its user message and enqueues it by run id", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ const { runId } = await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "why did these traces fail?",
+ context: [{ description: "current_url", value: "/project/x/traces" }],
+ });
+
+ const run = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: runId, projectId },
+ });
+
+ expect(run.status).toBe(InAppAgentRunStatus.QUEUED);
+ expect(run.finishedAt).toBeNull();
+ expect(run.request).toMatchObject({ kind: "userMessage" });
+
+ // The worker never writes RUN_STARTED and reads the turn's input from it,
+ // so a missing or misshaped row silently yields an empty replay history.
+ const events = await prisma.inAppAgentEvent.findMany({
+ where: { projectId, conversationId: conversation.id },
+ orderBy: { sequenceNumber: "asc" },
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({
+ runId,
+ sequenceNumber: 0,
+ type: EventType.RUN_STARTED,
+ });
+ expect(events[0]?.event).toMatchObject({
+ type: EventType.RUN_STARTED,
+ runId,
+ input: {
+ messages: [{ role: "user", content: "why did these traces fail?" }],
+ },
+ });
+
+ expect(enqueuedJobs).toEqual([
+ expect.objectContaining({
+ jobId: runId,
+ payload: expect.objectContaining({
+ payload: { projectId, runId },
+ }),
+ }),
+ ]);
+ });
+
+ it("rejects a second submit while a run is active without duplicating anything", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "first",
+ });
+
+ // The lost-response idempotency contract: a retry hits this clean conflict,
+ // then the client rehydrates and finds the committed run plus its message.
+ await expect(
+ caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "first",
+ }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+
+ expect(
+ await prisma.inAppAgentRun.count({
+ where: { projectId, conversationId: conversation.id },
+ }),
+ ).toBe(1);
+ expect(
+ await prisma.inAppAgentEvent.count({
+ where: { projectId, conversationId: conversation.id },
+ }),
+ ).toBe(1);
+ });
+
+ it("supersedes a pending approval when a new message is submitted", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-1",
+ });
+
+ const { runId } = await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "never mind, do this instead",
+ });
+
+ const parkedRun = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ });
+
+ expect(parkedRun.status).toBe(InAppAgentRunStatus.CANCELLED);
+ expect(parkedRun.errorCode).toBe(
+ InAppAgentRunErrorCode.APPROVAL_SUPERSEDED,
+ );
+ expect(runId).not.toBe(parkedRunId);
+ });
+
+ 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 parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-1",
+ });
+
+ const { runId: continuationRunId } = await caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ });
+
+ const parkedRun = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ });
+ // A parent that parked and was decided completed its job; the handoff is
+ // the success.
+ expect(parkedRun.status).toBe(InAppAgentRunStatus.SUCCEEDED);
+
+ const continuation = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: continuationRunId, projectId },
+ });
+ expect(continuation.status).toBe(InAppAgentRunStatus.QUEUED);
+ expect(continuation.request).toMatchObject({
+ kind: "approvalDecision",
+ parentRunId: parkedRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ });
+
+ const decisionEvent = await prisma.inAppAgentEvent.findFirstOrThrow({
+ where: { projectId, conversationId: conversation.id, runId: parkedRunId },
+ orderBy: { sequenceNumber: "desc" },
+ });
+ expect(decisionEvent.event).toMatchObject({
+ name: IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME,
+ value: {
+ toolCallId: "tool-call-1",
+ approved: true,
+ decidedByUserId: userId,
+ },
+ });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+
+ expect(
+ await prisma.inAppAgentRun.count({
+ where: {
+ projectId,
+ conversationId: conversation.id,
+ status: InAppAgentRunStatus.QUEUED,
+ },
+ }),
+ ).toBe(1);
+ });
+
+ it("rate-limits approval continuations before persisting or enqueueing them", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "rate-limited-tool-call",
+ });
+
+ enqueuedJobs.length = 0;
+ rateLimitMocks.rateLimitRequest.mockResolvedValue({
+ isRateLimited: () => true,
+ res: { msBeforeNext: 60_000 },
+ });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "rate-limited-tool-call",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
+
+ await expect(
+ prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ }),
+ ).resolves.toMatchObject({
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ });
+ expect(enqueuedJobs).toEqual([]);
+ });
+
+ it("rejects approval continuations for write-locked conversations before mutating", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "write-locked-tool-call",
+ });
+
+ await prisma.inAppAgentConversation.update({
+ where: {
+ id_projectId: { id: conversation.id, projectId },
+ },
+ data: { createdAt: new Date(Date.now() - 9 * 60 * 60 * 1000) },
+ });
+ await prisma.inAppAgentEvent.create({
+ data: {
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ sequenceNumber: 1,
+ type: EventType.TOOL_CALL_START,
+ event: {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "sandbox-tool-call",
+ toolCallName: "bash",
+ },
+ },
+ });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "write-locked-tool-call",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.",
+ });
+
+ await expect(
+ prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ }),
+ ).resolves.toMatchObject({
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ });
+ await expect(
+ prisma.inAppAgentRun.count({
+ where: { projectId, conversationId: conversation.id },
+ }),
+ ).resolves.toBe(1);
+ expect(enqueuedJobs).toEqual([]);
+ });
+
+ it("persists approval expiry before rejecting a late decision", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "expired-tool-call",
+ });
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: parkedRunId, projectId } },
+ data: { finishedAt: new Date(Date.now() - 25 * 60 * 60_000) },
+ });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "expired-tool-call",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+
+ await expect(
+ prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ }),
+ ).resolves.toMatchObject({
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: InAppAgentRunErrorCode.APPROVAL_EXPIRED,
+ });
+ });
+
+ it("cancels a queued run immediately and a pending approval directly", async () => {
+ const { caller, projectId, userId } = await createCaller();
+
+ const queuedConversation = await createConversation({ projectId, userId });
+ const { runId: queuedRunId } = await caller.startRun({
+ projectId,
+ conversationId: queuedConversation.id,
+ message: "stop me",
+ });
+
+ const queuedResult = await caller.cancelRun({
+ projectId,
+ conversationId: queuedConversation.id,
+ runId: queuedRunId,
+ });
+
+ expect(queuedResult.cancelledImmediately).toBe(true);
+ const cancelledQueuedRun = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: queuedRunId, projectId },
+ });
+ expect(cancelledQueuedRun.status).toBe(InAppAgentRunStatus.CANCELLED);
+ expect(cancelledQueuedRun.errorCode).toBe(InAppAgentRunErrorCode.CANCELLED);
+ expect(cancelledQueuedRun.cancelRequestedAt).not.toBeNull();
+
+ const parkedConversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: parkedConversation.id,
+ userId,
+ toolCallId: "tool-call-2",
+ });
+
+ await caller.cancelRun({
+ projectId,
+ conversationId: parkedConversation.id,
+ runId: parkedRunId,
+ });
+
+ const cancelledParkedRun = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ });
+ expect(cancelledParkedRun.status).toBe(InAppAgentRunStatus.CANCELLED);
+ expect(cancelledParkedRun.errorCode).toBe(
+ InAppAgentRunErrorCode.APPROVAL_CANCELLED,
+ );
+
+ // Cancel writes no decision event, so the card can only stop being
+ // actionable by deriving from the parked run's status.
+ const afterCancel = await caller.getConversation({
+ projectId,
+ conversationId: parkedConversation.id,
+ });
+ expect(afterCancel.pendingToolApprovals).toEqual([]);
+
+ const terminalConversation = await createConversation({
+ projectId,
+ userId,
+ });
+ const terminalRunId = createInAppAgentRunId();
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: terminalRunId,
+ projectId,
+ conversationId: terminalConversation.id,
+ triggeredByUserId: userId,
+ status: InAppAgentRunStatus.SUCCEEDED,
+ finishedAt: new Date(),
+ request: { kind: "userMessage", context: [] },
+ },
+ });
+
+ await caller.cancelRun({
+ projectId,
+ conversationId: terminalConversation.id,
+ runId: terminalRunId,
+ });
+
+ await expect(
+ prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: terminalRunId, projectId },
+ }),
+ ).resolves.toMatchObject({
+ status: InAppAgentRunStatus.SUCCEEDED,
+ cancelRequestedAt: null,
+ });
+ });
+
+ it("stops surfacing an approval that a newer message superseded", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-3",
+ });
+
+ const beforeSupersede = await caller.getConversation({
+ projectId,
+ conversationId: conversation.id,
+ });
+ expect(beforeSupersede.pendingToolApprovals).toHaveLength(1);
+
+ await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "never mind",
+ });
+
+ // Supersede also writes no decision event; the interrupt event is still
+ // there, so only the parent's status can retire the card.
+ const afterSupersede = await caller.getConversation({
+ projectId,
+ conversationId: conversation.id,
+ });
+ expect(afterSupersede.pendingToolApprovals).toEqual([]);
+ });
+
+ it.each([
+ {
+ name: "worker_lost",
+ expected: InAppAgentRunErrorCode.WORKER_LOST,
+ data: {
+ status: InAppAgentRunStatus.RUNNING,
+ claimedAt: new Date(Date.now() - 120_000),
+ heartbeatAt: new Date(Date.now() - 90_000),
+ },
+ },
+ {
+ name: "run_timeout",
+ expected: InAppAgentRunErrorCode.RUN_TIMEOUT,
+ data: {
+ status: InAppAgentRunStatus.RUNNING,
+ claimedAt: new Date(Date.now() - 16 * 60_000),
+ heartbeatAt: new Date(),
+ },
+ },
+ {
+ name: "foreground_stale",
+ expected: InAppAgentRunErrorCode.STALE,
+ data: { status: InAppAgentRunStatus.RUNNING },
+ createdAt: new Date(Date.now() - 3 * 60_000),
+ },
+ {
+ name: "queue_timeout",
+ expected: InAppAgentRunErrorCode.QUEUE_TIMEOUT,
+ data: { status: InAppAgentRunStatus.QUEUED },
+ createdAt: new Date(Date.now() - 6 * 60_000),
+ },
+ {
+ name: "approval_expired",
+ expected: InAppAgentRunErrorCode.APPROVAL_EXPIRED,
+ data: {
+ status: InAppAgentRunStatus.AWAITING_APPROVAL,
+ finishedAt: new Date(Date.now() - 25 * 60 * 60_000),
+ },
+ },
+ ])("reconciles $name on read with its typed error code", async (testCase) => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const runId = createInAppAgentRunId();
+
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: runId,
+ projectId,
+ conversationId: conversation.id,
+ triggeredByUserId: userId,
+ request: { kind: "userMessage", context: [] },
+ ...testCase.data,
+ },
+ });
+
+ if (testCase.createdAt) {
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: runId, projectId } },
+ data: { createdAt: testCase.createdAt },
+ });
+ }
+
+ const result = await caller.getConversation({
+ projectId,
+ conversationId: conversation.id,
+ });
+
+ expect(result.latestRun).toMatchObject({
+ id: runId,
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: testCase.expected,
+ });
+ });
+
+ it("fails the committed run when the enqueue fails", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ enqueueShouldFail = true;
+
+ await expect(
+ caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "will not reach a worker",
+ }),
+ ).rejects.toThrow();
+
+ const run = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { projectId, conversationId: conversation.id },
+ });
+
+ // Never leave a committed QUEUED run that nobody will execute.
+ expect(run.status).toBe(InAppAgentRunStatus.FAILED);
+ expect(run.errorCode).toBe(InAppAgentRunErrorCode.ENQUEUE_FAILED);
+ expect(run.finishedAt).not.toBeNull();
+ });
+
+ it("denies every background mutation to a non-owner", async () => {
+ const owner = await createCaller();
+ const conversation = await createConversation({
+ projectId: owner.projectId,
+ userId: owner.userId,
+ });
+ const { runId } = await owner.caller.startRun({
+ projectId: owner.projectId,
+ conversationId: conversation.id,
+ message: "mine",
+ });
+
+ const intruderId = `user-${randomUUID()}`;
+ await prisma.user.create({
+ data: { id: intruderId, email: `${intruderId}@example.com` },
+ });
+
+ const intruderSession: Session = {
+ expires: "1",
+ user: {
+ id: intruderId,
+ name: "Intruder",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: owner.orgId,
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ name: "Test Organization",
+ metadata: {},
+ aiFeaturesEnabled: true,
+ aiTelemetryEnabled: false,
+ projects: [
+ {
+ id: owner.projectId,
+ role: "ADMIN",
+ name: "Test Project",
+ deletedAt: null,
+ retentionDays: null,
+ hasTraces: false,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {} as Flags,
+ admin: false,
+ },
+ environment: {} as any,
+ };
+
+ const intruder = inAppAgentRouter.createCaller({
+ ...createInnerTRPCContext({ session: intruderSession, headers: {} }),
+ prisma,
+ });
+
+ // Project membership is not enough: conversations are owner-only in v1.
+ await expect(
+ intruder.startRun({
+ projectId: owner.projectId,
+ conversationId: conversation.id,
+ message: "not mine",
+ }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+
+ await expect(
+ intruder.cancelRun({
+ projectId: owner.projectId,
+ conversationId: conversation.id,
+ runId,
+ }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+
+ await expect(
+ intruder.decideToolApproval({
+ projectId: owner.projectId,
+ conversationId: conversation.id,
+ runId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("denies every background mutation when organization AI features are disabled", async () => {
+ const { caller, orgId, projectId } = await createCaller();
+
+ await prisma.organization.update({
+ where: { id: orgId },
+ data: { aiFeaturesEnabled: false },
+ });
+
+ await expect(
+ caller.startRun({
+ projectId,
+ conversationId: createInAppAgentConversationId(),
+ message: "do not enqueue",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ await expect(
+ caller.cancelRun({
+ projectId,
+ conversationId: createInAppAgentConversationId(),
+ runId: createInAppAgentRunId(),
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: createInAppAgentConversationId(),
+ runId: createInAppAgentRunId(),
+ toolCallId: "tool-call-disabled",
+ approved: true,
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ expect(enqueuedJobs).toHaveLength(0);
+ });
+});
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 ecaef3a262..46ee0c8b48 100644
--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
@@ -12,7 +12,11 @@ import { EventType } from "@ag-ui/core";
import { randomUUID } from "crypto";
import { vi } from "vitest";
-import { InAppAgentRunErrorCode, type Plan } from "@langfuse/shared";
+import {
+ InAppAgentRunErrorCode,
+ InAppAgentRunStatus,
+ type Plan,
+} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import type { Prisma } from "@langfuse/shared/src/db";
import {
@@ -2047,6 +2051,50 @@ describe("in-app agent persistence", () => {
expect(newRun.finishedAt).toBeNull();
});
+ it("leaves a claimed background run alone when a foreground run starts", async () => {
+ const { projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const backgroundRun = await createConversationRun({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ });
+
+ // A background run legitimately runs for up to RUN_MAX_DURATION, far past
+ // the 150s foreground staleness window. Execution mode is not sticky per
+ // conversation, so a foreground submit landing here is a normal state — and
+ // it must not fence a healthy worker, which stale-closing would (both
+ // finishRun and the event append guard on the run still being open).
+ await prisma.inAppAgentRun.update({
+ where: { id_projectId: { id: backgroundRun.id, projectId } },
+ data: {
+ createdAt: new Date("2026-05-20T10:00:00.000Z"),
+ claimedAt: new Date("2026-05-20T10:00:01.000Z"),
+ heartbeatAt: new Date(),
+ },
+ });
+
+ await expect(
+ createConversationRun({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ }),
+ ).rejects.toMatchObject({
+ message: "Assistant is already responding in this conversation",
+ });
+
+ await expect(
+ prisma.inAppAgentRun.findUniqueOrThrow({
+ where: { id_projectId: { id: backgroundRun.id, projectId } },
+ }),
+ ).resolves.toMatchObject({
+ status: "RUNNING",
+ finishedAt: null,
+ errorCode: null,
+ });
+ });
+
it("writes run lifecycle status on the foreground path", async () => {
const { projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
@@ -2119,6 +2167,7 @@ describe("in-app agent persistence", () => {
id: createInAppAgentRunId(),
projectId,
conversationId: conversation.id,
+ status: InAppAgentRunStatus.RUNNING,
},
}),
).rejects.toMatchObject({
diff --git a/web/src/app/api/in-app-agent/watch/route.ts b/web/src/app/api/in-app-agent/watch/route.ts
new file mode 100644
index 0000000000..24b92b4531
--- /dev/null
+++ b/web/src/app/api/in-app-agent/watch/route.ts
@@ -0,0 +1,9 @@
+import watchHandler from "@/src/features/in-app-agent/server/watchHandler";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+// The generator ends every stream at WATCH_MAX_CONNECTION (90s), well inside
+// this limit, so the client's reconnect is always the deliberate path.
+export const maxDuration = 120;
+
+export const GET = watchHandler;
diff --git a/web/src/features/in-app-agent/server/availability.ts b/web/src/features/in-app-agent/server/availability.ts
new file mode 100644
index 0000000000..9544b74949
--- /dev/null
+++ b/web/src/features/in-app-agent/server/availability.ts
@@ -0,0 +1,59 @@
+import type { Session } from "next-auth";
+
+import { BaseError, ForbiddenError } from "@langfuse/shared";
+import type { PrismaClient } from "@langfuse/shared/src/db";
+
+import { env } from "@/src/env.mjs";
+import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+
+export async function assertInAppAgentAvailable({
+ prisma,
+ projectId,
+ user,
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ user: NonNullable<Session["user"]>;
+}) {
+ // TODO(LFE-14555): Remove this guard once the OSS release strategy is ready.
+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw new BaseError(
+ "PreconditionFailedError",
+ 412,
+ "In-app agent is not available in this environment yet.",
+ true,
+ );
+ }
+
+ if (
+ !hasEntitlement({
+ entitlement: "in-app-agent",
+ sessionUser: user,
+ projectId,
+ })
+ ) {
+ throw new ForbiddenError(
+ "Unauthorized, user does not have access to entitlement: in-app-agent",
+ );
+ }
+
+ const project = await prisma.project.findUnique({
+ where: { id: projectId },
+ select: {
+ organization: {
+ select: {
+ id: true,
+ cloudConfig: true,
+ aiFeaturesEnabled: true,
+ aiTelemetryEnabled: true,
+ },
+ },
+ },
+ });
+
+ if (!project?.organization.aiFeaturesEnabled) {
+ throw new ForbiddenError("Assistant is not enabled for this organization");
+ }
+
+ return project.organization;
+}
diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.ts
new file mode 100644
index 0000000000..23bf5a50eb
--- /dev/null
+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts
@@ -0,0 +1,408 @@
+import { EventType } from "@ag-ui/core";
+import { randomUUID } from "crypto";
+
+import {
+ BaseError,
+ InAppAgentRunErrorCode,
+ InAppAgentRunStatus,
+ LangfuseNotFoundError,
+} from "@langfuse/shared";
+import type { PrismaClient } from "@langfuse/shared/src/db";
+import {
+ InAppAgentRunQueue,
+ logger,
+ QueueJobs,
+ redis,
+} from "@langfuse/shared/src/server";
+import { deleteApiKeyFromDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import {
+ createInAppAgentMessageId,
+ createInAppAgentRunId,
+ parseInAppAgentApprovalDecisionEvent,
+ type AgUiRunAgentInput,
+} from "@langfuse/shared/in-app-agent";
+import { parseInAppAgentInterruptEvent } from "@langfuse/shared/in-app-agent/server/human-in-the-loop";
+import {
+ ensureOwnedConversation,
+ getConversationEvents,
+ getConversationMessagesForDisplayFromEvents,
+ getOwnedConversationOrThrow,
+ isInAppAgentConversationWriteLocked,
+ maybeInferAndPersistConversationTitle,
+ serializeConversation,
+ type PersistedConversationEvent,
+} from "@langfuse/shared/in-app-agent/server/persistence";
+import {
+ cleanupTerminalRunMcpApiKeys,
+ createQueuedRun,
+ decideToolApproval,
+ reconcileConversationRuns,
+ requestRunCancellation,
+} from "@langfuse/shared/in-app-agent/server/runLifecycle";
+
+import { resolveInAppAgentRunContext } from "@/src/features/in-app-agent/server/runContext";
+
+const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
+
+export async function getBackgroundConversationSnapshot(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ userId: string;
+}) {
+ const conversation = await getOwnedConversationOrThrow({
+ ...params,
+ });
+
+ await reconcileConversationRuns({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+
+ await cleanupTerminalRunMcpApiKeys({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ deleteApiKey: async (apiKeyId) => {
+ await deleteApiKeyFromDb({
+ prisma: params.prisma,
+ id: apiKeyId,
+ entityId: params.projectId,
+ scope: "PROJECT",
+ redis,
+ });
+ },
+ });
+
+ const [events, runs] = await Promise.all([
+ getConversationEvents({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ }),
+ params.prisma.inAppAgentRun.findMany({
+ where: {
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ orderBy: { createdAt: "asc" },
+ select: {
+ id: true,
+ status: true,
+ errorCode: true,
+ cancelRequestedAt: true,
+ },
+ }),
+ ]);
+ const messages = getConversationMessagesForDisplayFromEvents(events);
+
+ const latestRun = runs.at(-1) ?? null;
+
+ return {
+ conversation: serializeConversation(conversation, {
+ isWriteLocked: isInAppAgentConversationWriteLocked({
+ conversation,
+ events,
+ }),
+ }),
+ messages,
+ eventCursor: events.reduce(
+ (max, event) => Math.max(max, event.sequenceNumber),
+ -1,
+ ),
+ latestRun:
+ latestRun && latestRun.status
+ ? {
+ id: latestRun.id,
+ status: latestRun.status as InAppAgentRunStatus,
+ errorCode: latestRun.errorCode,
+ cancelRequested: Boolean(latestRun.cancelRequestedAt),
+ }
+ : null,
+ pendingToolApprovals: getPendingToolApprovals(
+ events,
+ new Set(
+ runs
+ .filter((run) => run.status === InAppAgentRunStatus.AWAITING_APPROVAL)
+ .map((run) => run.id),
+ ),
+ ),
+ state: {
+ type: "existingConversation" as const,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ },
+ };
+}
+
+export async function startBackgroundRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ userId: string;
+ message: string;
+ context: AgUiRunAgentInput["context"];
+ isV4Enabled: boolean;
+ model: string | undefined;
+ aiTelemetryEnabled: boolean;
+}) {
+ const conversation = await ensureOwnedConversation({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ userId: params.userId,
+ });
+ const events = await getConversationEvents({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+
+ if (isInAppAgentConversationWriteLocked({ conversation, events })) {
+ throw new BaseError(
+ "PreconditionFailedError",
+ 412,
+ SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ true,
+ );
+ }
+
+ if (!params.model) {
+ throw new BaseError(
+ "PreconditionFailedError",
+ 412,
+ "Assistant model is not configured.",
+ true,
+ );
+ }
+
+ const context = await resolveInAppAgentRunContext({
+ context: params.context,
+ projectId: params.projectId,
+ isV4Enabled: params.isV4Enabled,
+ });
+ const runId = createInAppAgentRunId();
+ const userMessage = {
+ id: createInAppAgentMessageId(),
+ role: "user" as const,
+ content: params.message,
+ };
+ const run = await createQueuedRun({
+ prisma: params.prisma,
+ runId,
+ projectId: params.projectId,
+ conversationId: conversation.id,
+ triggeredByUserId: params.userId,
+ model: params.model,
+ request: { kind: "userMessage", context },
+ runStartedEvent: {
+ type: EventType.RUN_STARTED,
+ threadId: conversation.id,
+ runId,
+ input: {
+ threadId: conversation.id,
+ runId,
+ state: null,
+ messages: [userMessage],
+ tools: [],
+ context,
+ forwardedProps: {},
+ },
+ },
+ });
+
+ await enqueueInAppAgentRun({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ runId: run.id,
+ });
+
+ maybeInferAndPersistConversationTitle({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: conversation.id,
+ userId: params.userId,
+ aiTelemetryEnabled: params.aiTelemetryEnabled,
+ });
+
+ return { runId: run.id };
+}
+
+export async function cancelBackgroundRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+ userId: string;
+}) {
+ await getOwnedConversationOrThrow({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ userId: params.userId,
+ });
+
+ const result = await requestRunCancellation({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ runId: params.runId,
+ });
+
+ if (result.cancelledImmediately) {
+ await removeInAppAgentRunJob(params.runId);
+ }
+
+ return result;
+}
+
+export async function decideBackgroundApproval(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ conversationId: string;
+ runId: string;
+ toolCallId: string;
+ approved: boolean;
+ userId: string;
+ model: string | undefined;
+}) {
+ const conversation = await getOwnedConversationOrThrow({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ userId: params.userId,
+ });
+
+ const events = await getConversationEvents({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+
+ if (isInAppAgentConversationWriteLocked({ conversation, events })) {
+ throw new BaseError(
+ "PreconditionFailedError",
+ 412,
+ SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ true,
+ );
+ }
+
+ const approvalRequest = events.find(
+ (persisted) =>
+ persisted.runId === params.runId &&
+ parseInAppAgentInterruptEvent(persisted.event)?.toolCallId ===
+ params.toolCallId,
+ );
+
+ if (!approvalRequest) {
+ throw new LangfuseNotFoundError("Approval request not found");
+ }
+
+ const continuationRun = await decideToolApproval({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ parentRunId: params.runId,
+ continuationRunId: createInAppAgentRunId(),
+ toolCallId: params.toolCallId,
+ approved: params.approved,
+ decidedByUserId: params.userId,
+ model: params.model,
+ });
+
+ await enqueueInAppAgentRun({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ runId: continuationRun.id,
+ });
+
+ return { runId: continuationRun.id };
+}
+
+function getPendingToolApprovals(
+ events: readonly PersistedConversationEvent[],
+ parkedRunIds: ReadonlySet<string>,
+) {
+ const decidedToolCallIds = new Set(
+ events.flatMap((persisted) => {
+ const decision = parseInAppAgentApprovalDecisionEvent(persisted.event);
+ return decision ? [decision.toolCallId] : [];
+ }),
+ );
+
+ return events.flatMap((persisted) => {
+ const approvalRequest = parseInAppAgentInterruptEvent(persisted.event);
+
+ return approvalRequest &&
+ parkedRunIds.has(persisted.runId) &&
+ !decidedToolCallIds.has(approvalRequest.toolCallId)
+ ? [{ runId: persisted.runId, approvalRequest }]
+ : [];
+ });
+}
+
+async function enqueueInAppAgentRun(params: {
+ prisma: PrismaClient;
+ projectId: string;
+ runId: string;
+}) {
+ try {
+ const queue = InAppAgentRunQueue.getInstance();
+
+ if (!queue) {
+ throw new Error("In-app agent run queue is unavailable");
+ }
+
+ await queue.add(
+ QueueJobs.InAppAgentRunJob,
+ {
+ timestamp: new Date(),
+ id: randomUUID(),
+ name: QueueJobs.InAppAgentRunJob,
+ payload: { projectId: params.projectId, runId: params.runId },
+ },
+ { jobId: params.runId },
+ );
+ } catch (error) {
+ logger.error("Failed to enqueue in-app agent run", {
+ error,
+ projectId: params.projectId,
+ runId: params.runId,
+ });
+
+ await params.prisma.inAppAgentRun.updateMany({
+ where: {
+ id: params.runId,
+ projectId: params.projectId,
+ status: InAppAgentRunStatus.QUEUED,
+ },
+ data: {
+ status: InAppAgentRunStatus.FAILED,
+ finishedAt: new Date(),
+ errorCode: InAppAgentRunErrorCode.ENQUEUE_FAILED,
+ errorMessage: "Couldn't start the run",
+ },
+ });
+
+ throw new BaseError(
+ "InternalServerError",
+ 500,
+ "Couldn't start the run. Try again.",
+ true,
+ );
+ }
+}
+
+async function removeInAppAgentRunJob(runId: string) {
+ try {
+ await InAppAgentRunQueue.getInstance()?.remove(runId);
+ } catch (error) {
+ logger.info("Failed to remove cancelled in-app agent run job", {
+ error,
+ runId,
+ });
+ }
+}
diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.ts
index b1820785f6..122a8a3041 100644
--- a/web/src/features/in-app-agent/server/handler.ts
+++ b/web/src/features/in-app-agent/server/handler.ts
@@ -10,8 +10,12 @@ import {
import {
getInAppAgentMessageEntryPointTraceMetadata,
getInAppAgentQuickActionTraceMetadata,
- sanitizeInAppAgentContext,
} from "@/src/features/in-app-agent/context";
+import { resolveInAppAgentRunContext } from "@/src/features/in-app-agent/server/runContext";
+import {
+ checkInAppAgentRateLimit,
+ getInAppAgentApiAccessScope,
+} from "@/src/features/in-app-agent/server/rateLimit";
import { getInAppAgentInstrumentationTraceId } from "@langfuse/shared/in-app-agent";
import {
AgUiRunAgentInputSchema,
@@ -57,19 +61,14 @@ import {
} from "@langfuse/shared/in-app-agent/server/sandbox/config";
import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";
import { getAuthOptions } from "@/src/server/auth";
-import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
-import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
-import {
- createHttpHeaderFromRateLimit,
- RateLimitService,
-} from "@/src/features/public-api/server/RateLimitService";
+import { assertInAppAgentAvailable } from "@/src/features/in-app-agent/server/availability";
+import { createHttpHeaderFromRateLimit } from "@/src/features/public-api/server/RateLimitService";
+import type { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
import {
getLangfuseAITraceSinkParams,
- parseSavedViewFromURL,
addUserToSpan,
logger,
redis,
- TableViewService,
type ApiAccessScope,
} from "@langfuse/shared/src/server";
import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
@@ -78,14 +77,10 @@ import { assertUnreachable } from "@/src/utils/types";
import {
BaseError,
ForbiddenError,
- type FilterState,
InAppAgentRunErrorCode,
InvalidRequestError,
- LangfuseNotFoundError,
type RateLimitResult,
- TableViewPresetTableName,
UnauthorizedError,
- CloudConfigSchema,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -124,15 +119,6 @@ export default async function handler(request: Request) {
email: user.email ?? undefined,
});
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- throw new BaseError(
- "PreconditionFailedError",
- 412,
- "Assistant is not available in self-hosted deployments.",
- true,
- );
- }
-
const bodyResult = await readBoundedJsonBody(
request,
MAX_IN_APP_AGENT_INPUT_BYTES,
@@ -190,36 +176,12 @@ export default async function handler(request: Request) {
throw new ForbiddenError("User is not a member of this project");
}
- if (
- !hasEntitlement({
- entitlement: "in-app-agent",
- sessionUser: user,
- projectId,
- })
- ) {
- throw new ForbiddenError("Assistant is not enabled for this plan");
- }
-
- const project = await prisma.project.findUnique({
- where: { id: projectId },
- select: {
- organization: {
- select: {
- id: true,
- cloudConfig: true,
- aiFeaturesEnabled: true,
- aiTelemetryEnabled: true,
- },
- },
- },
+ const organization = await assertInAppAgentAvailable({
+ prisma,
+ projectId,
+ user,
});
- if (!project?.organization.aiFeaturesEnabled) {
- throw new ForbiddenError(
- "Assistant is not enabled for this organization",
- );
- }
-
const sanitizedInput = await prepareAgentInput(
input,
projectId,
@@ -264,7 +226,7 @@ export default async function handler(request: Request) {
const rateLimitScope = getInAppAgentApiAccessScope(
user,
projectId,
- project.organization,
+ organization,
);
addUserToSpan({
@@ -508,8 +470,7 @@ export default async function handler(request: Request) {
projectId,
conversationId: conversation.id,
userId,
- aiTelemetryEnabled:
- project.organization.aiTelemetryEnabled,
+ aiTelemetryEnabled: organization.aiTelemetryEnabled,
});
}),
onAbort: () =>
@@ -557,7 +518,7 @@ export default async function handler(request: Request) {
langfuseClient,
useLocalPrompt,
langfuseTracing: (() => {
- if (!project.organization.aiTelemetryEnabled) {
+ if (!organization.aiTelemetryEnabled) {
return undefined;
}
@@ -690,65 +651,15 @@ function getInAppAgentUserAccess(
};
}
-function getInAppAgentApiAccessScope(
- user: SessionUser,
- projectId: string,
- projectOrganization: {
- id: string;
- cloudConfig: unknown;
- },
-): ApiAccessScope {
- const organization = user.organizations.find((org) =>
- org.projects.some((project) => project.id === projectId),
- );
-
- if (!organization) {
- if (user.admin === true) {
- const cloudConfig = projectOrganization.cloudConfig
- ? CloudConfigSchema.parse(projectOrganization.cloudConfig)
- : undefined;
-
- return {
- orgId: projectOrganization.id,
- plan: getOrganizationPlanServerSide(cloudConfig),
- projectId,
- accessLevel: "project",
- rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],
- apiKeyId: "in-app-agent-session",
- publicKey: "in-app-agent-session",
- isIngestionSuspended: false,
- };
- }
-
- throw new ForbiddenError("User is not a member of this project");
- }
-
- return {
- orgId: organization.id,
- plan: organization.plan,
- projectId,
- accessLevel: "project",
- rateLimitOverrides: organization.cloudConfig?.rateLimitOverrides ?? [],
- apiKeyId: "in-app-agent-session",
- publicKey: "in-app-agent-session",
- isIngestionSuspended: false,
- };
-}
-
async function rateLimitInAppAgentRequest(
scope: ApiAccessScope,
resource: Parameters<RateLimitService["rateLimitRequest"]>[1],
): Promise<Response | undefined> {
- const rateLimit = await RateLimitService.getInstance().rateLimitRequest(
- scope,
- resource,
- );
-
- if (!rateLimit.isRateLimited() || !rateLimit.res) {
- return undefined;
- }
+ const rateLimitRes = await checkInAppAgentRateLimit(scope, resource);
- return createInAppAgentRateLimitResponse(rateLimit.res);
+ return rateLimitRes
+ ? createInAppAgentRateLimitResponse(rateLimitRes)
+ : undefined;
}
function createInAppAgentRateLimitResponse(rateLimitRes: RateLimitResult) {
@@ -910,47 +821,11 @@ async function prepareAgentInput(
throw new InvalidRequestError("Invalid forwarded props");
}
- const currentUrlContext = input.context.find(
- (item) => item.description === "current_url",
- );
- const selectedSavedView = currentUrlContext
- ? parseSavedViewFromURL(currentUrlContext.value, isV4Enabled)
- : undefined;
- let viewFilters: FilterState | undefined;
-
- if (selectedSavedView) {
- try {
- const { filters, tableName } =
- await TableViewService.getTableViewPresetsById(
- selectedSavedView.viewId,
- projectId,
- );
-
- if (
- tableName === selectedSavedView.tableName ||
- (selectedSavedView.tableName ===
- TableViewPresetTableName.ObservationsEvents &&
- tableName === TableViewPresetTableName.Observations)
- ) {
- viewFilters = filters;
- }
- } catch (error) {
- // Saved views can be deleted while their URLs remain open or shared.
- if (!(error instanceof LangfuseNotFoundError)) {
- logger.warn("Failed to resolve saved view for in-app agent context", {
- error,
- projectId,
- savedViewId: selectedSavedView.viewId,
- });
- }
- }
- }
-
- const context = sanitizeInAppAgentContext(
- input.context,
+ const context = await resolveInAppAgentRunContext({
+ context: input.context,
projectId,
- viewFilters,
- );
+ isV4Enabled,
+ });
if (forwardedProps && "command" in forwardedProps) {
const resumeForwardedProps =
diff --git a/web/src/features/in-app-agent/server/rateLimit.ts b/web/src/features/in-app-agent/server/rateLimit.ts
new file mode 100644
index 0000000000..7e261102a3
--- /dev/null
+++ b/web/src/features/in-app-agent/server/rateLimit.ts
@@ -0,0 +1,100 @@
+import { type Session } from "next-auth";
+
+import {
+ BaseError,
+ CloudConfigSchema,
+ ForbiddenError,
+ type RateLimitResult,
+} from "@langfuse/shared";
+import type { ApiAccessScope } from "@langfuse/shared/src/server";
+
+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
+
+type SessionUser = NonNullable<Session["user"]>;
+
+/**
+ * Build the org-scoped rate-limit scope for an in-app agent request.
+ *
+ * Shared by the foreground route and the background `startRun` mutation so a
+ * user cannot bypass the cap by submitting through the other path.
+ *
+ * TODO: this is org-scoped only; there is no per-user cap yet.
+ */
+export function getInAppAgentApiAccessScope(
+ user: SessionUser,
+ projectId: string,
+ projectOrganization: {
+ id: string;
+ cloudConfig: unknown;
+ },
+): ApiAccessScope {
+ const organization = user.organizations.find((org) =>
+ org.projects.some((project) => project.id === projectId),
+ );
+
+ if (!organization) {
+ if (user.admin === true) {
+ const cloudConfig = projectOrganization.cloudConfig
+ ? CloudConfigSchema.parse(projectOrganization.cloudConfig)
+ : undefined;
+
+ return {
+ orgId: projectOrganization.id,
+ plan: getOrganizationPlanServerSide(cloudConfig),
+ projectId,
+ accessLevel: "project",
+ rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],
+ apiKeyId: "in-app-agent-session",
+ publicKey: "in-app-agent-session",
+ isIngestionSuspended: false,
+ };
+ }
+
+ throw new ForbiddenError("User is not a member of this project");
+ }
+
+ return {
+ orgId: organization.id,
+ plan: organization.plan,
+ projectId,
+ accessLevel: "project",
+ rateLimitOverrides: organization.cloudConfig?.rateLimitOverrides ?? [],
+ apiKeyId: "in-app-agent-session",
+ publicKey: "in-app-agent-session",
+ isIngestionSuspended: false,
+ };
+}
+
+export async function checkInAppAgentRateLimit(
+ scope: ApiAccessScope,
+ resource: Parameters<RateLimitService["rateLimitRequest"]>[1],
+): Promise<RateLimitResult | undefined> {
+ const rateLimit = await RateLimitService.getInstance().rateLimitRequest(
+ scope,
+ resource,
+ );
+
+ return rateLimit.isRateLimited() ? (rateLimit.res ?? undefined) : undefined;
+}
+
+/** tRPC-shaped variant; BaseErrors bubble to the tRPC error middleware. */
+export async function assertInAppAgentRateLimit(
+ scope: ApiAccessScope,
+ resource: Parameters<RateLimitService["rateLimitRequest"]>[1],
+): Promise<void> {
+ const rateLimitRes = await checkInAppAgentRateLimit(scope, resource);
+
+ if (!rateLimitRes) {
+ return;
+ }
+
+ throw new BaseError(
+ "TooManyRequestsError",
+ 429,
+ `Too many assistant requests. Please retry in ${Math.ceil(
+ rateLimitRes.msBeforeNext / 1_000,
+ )} seconds.`,
+ true,
+ );
+}
diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.ts
index df4d5d5daa..8abaf45d4f 100644
--- a/web/src/features/in-app-agent/server/router.ts
+++ b/web/src/features/in-app-agent/server/router.ts
@@ -1,41 +1,46 @@
import { z } from "zod";
-import type { Session } from "next-auth";
import {
- BaseError,
- ForbiddenError,
InvalidRequestError,
ScoreDataTypeEnum,
ScoreSourceEnum,
TEXT_SCORE_MAX_LENGTH,
} from "@langfuse/shared";
-import type { PrismaClient } from "@langfuse/shared/src/db";
import {
convertDateToClickhouseDateTime,
upsertScore,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import {
+ AgUiContextSchema,
getInAppAgentInstrumentationObservationId,
getInAppAgentInstrumentationTraceId,
} from "@langfuse/shared/in-app-agent";
import { InAppAgentMessageFeedbackValueSchema } from "@langfuse/shared/in-app-agent";
-import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { assertInAppAgentAvailable } from "@/src/features/in-app-agent/server/availability";
import {
createTRPCRouter,
protectedProjectProcedure,
protectedProjectProcedureWithoutTracing,
} from "@/src/server/api/trpc";
import {
- getConversationEvents,
- getConversationMessagesForDisplay,
getConversationMessages,
getOwnedConversationOrThrow,
- isInAppAgentConversationWriteLocked,
serializeConversation,
} from "@langfuse/shared/in-app-agent/server/persistence";
+import {
+ assertInAppAgentRateLimit,
+ getInAppAgentApiAccessScope,
+} from "@/src/features/in-app-agent/server/rateLimit";
+import {
+ cancelBackgroundRun,
+ decideBackgroundApproval,
+ getBackgroundConversationSnapshot,
+ startBackgroundRun,
+} from "@/src/features/in-app-agent/server/backgroundRunService";
const CONVERSATION_LIST_LIMIT = 50;
+const MAX_IN_APP_AGENT_MESSAGE_LENGTH = 32_000;
const ConversationListCursorSchema = z.object({
updatedAt: z.date(),
@@ -51,6 +56,26 @@ const RenameConversationInput = ConversationIdInput.extend({
title: z.string().trim().min(1).max(80),
});
+const StartRunInput = ConversationIdInput.extend({
+ message: z.string().trim().min(1).max(MAX_IN_APP_AGENT_MESSAGE_LENGTH),
+ /**
+ * The same AG-UI context array the foreground path sends (current page, the
+ * quick action and entry point that triggered the turn); resolved and
+ * sanitized server-side, then stored on the run for the worker to replay.
+ */
+ context: z.array(AgUiContextSchema).default([]),
+});
+
+const CancelRunInput = ConversationIdInput.extend({
+ runId: z.string(),
+});
+
+const DecideToolApprovalInput = ConversationIdInput.extend({
+ runId: z.string(),
+ toolCallId: z.string(),
+ approved: z.boolean(),
+});
+
const SubmitFeedbackInput = ConversationIdInput.extend({
messageId: z.string(),
runId: z.string(),
@@ -71,7 +96,11 @@ export const inAppAgentRouter = createTRPCRouter({
}),
)
.query(async ({ ctx, input }) => {
- await assertInAppAgentAvailable({ ctx, projectId: input.projectId });
+ await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
const conversations = await ctx.prisma.inAppAgentConversation.findMany({
where: {
@@ -114,48 +143,124 @@ export const inAppAgentRouter = createTRPCRouter({
getConversation: protectedProjectProcedureWithoutTracing
.input(ConversationIdInput)
.query(async ({ ctx, input }) => {
- await assertInAppAgentAvailable({ ctx, projectId: input.projectId });
+ await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
- const conversation = await getOwnedConversationOrThrow({
+ return getBackgroundConversationSnapshot({
prisma: ctx.prisma,
projectId: input.projectId,
conversationId: input.conversationId,
userId: ctx.session.user.id,
});
+ }),
- const [messages, events] = await Promise.all([
- getConversationMessagesForDisplay({
- prisma: ctx.prisma,
- projectId: input.projectId,
- conversationId: input.conversationId,
- }),
- getConversationEvents({
- prisma: ctx.prisma,
- projectId: input.projectId,
- conversationId: input.conversationId,
- }),
- ]);
+ /**
+ * Submit a turn for background execution.
+ *
+ * Runs the same validation chain as the foreground route, then commits the
+ * run as QUEUED with its user message already appended — the events table is
+ * the render source from the instant of submit, so there is no optimistic UI
+ * state to survive a refresh. The BullMQ enqueue happens after commit; a
+ * failure there marks the run FAILED immediately rather than leaving a
+ * committed run nobody will execute.
+ */
+ startRun: protectedProjectProcedureWithoutTracing
+ .input(StartRunInput)
+ .mutation(async ({ ctx, input }) => {
+ const projectAvailability = await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
- return {
- conversation: serializeConversation(conversation, {
- isWriteLocked: isInAppAgentConversationWriteLocked({
- conversation,
- events,
- }),
- }),
- messages,
- state: {
- type: "existingConversation" as const,
- projectId: input.projectId,
- conversationId: input.conversationId,
- },
- };
+ await assertInAppAgentRateLimit(
+ getInAppAgentApiAccessScope(
+ ctx.session.user,
+ input.projectId,
+ projectAvailability,
+ ),
+ "in-app-agent-run",
+ );
+
+ return startBackgroundRun({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ userId: ctx.session.user.id,
+ message: input.message,
+ context: input.context,
+ isV4Enabled: ctx.session.user.v4BetaEnabled === true,
+ model: env.LANGFUSE_AWS_BEDROCK_MODEL,
+ aiTelemetryEnabled: projectAvailability.aiTelemetryEnabled,
+ });
+ }),
+
+ cancelRun: protectedProjectProcedureWithoutTracing
+ .input(CancelRunInput)
+ .mutation(async ({ ctx, input }) => {
+ await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
+
+ return cancelBackgroundRun({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ runId: input.runId,
+ userId: ctx.session.user.id,
+ });
+ }),
+
+ /**
+ * Decide a pending tool approval.
+ *
+ * The client sends only IDs and a boolean. The tool name and arguments are
+ * read server-side from the persisted interrupt event, so there is nothing
+ * to tamper with on the way back and no fingerprint to keep in sync.
+ */
+ decideToolApproval: protectedProjectProcedureWithoutTracing
+ .input(DecideToolApprovalInput)
+ .mutation(async ({ ctx, input }) => {
+ const projectAvailability = await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
+
+ await assertInAppAgentRateLimit(
+ getInAppAgentApiAccessScope(
+ ctx.session.user,
+ input.projectId,
+ projectAvailability,
+ ),
+ "in-app-agent-run",
+ );
+
+ return decideBackgroundApproval({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ runId: input.runId,
+ toolCallId: input.toolCallId,
+ approved: input.approved,
+ userId: ctx.session.user.id,
+ model: env.LANGFUSE_AWS_BEDROCK_MODEL,
+ });
}),
deleteConversation: protectedProjectProcedureWithoutTracing
.input(ConversationIdInput)
.mutation(async ({ ctx, input }) => {
- await assertInAppAgentAvailable({ ctx, projectId: input.projectId });
+ await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
await getOwnedConversationOrThrow({
prisma: ctx.prisma,
@@ -183,7 +288,11 @@ export const inAppAgentRouter = createTRPCRouter({
renameConversation: protectedProjectProcedureWithoutTracing
.input(RenameConversationInput)
.mutation(async ({ ctx, input }) => {
- await assertInAppAgentAvailable({ ctx, projectId: input.projectId });
+ await assertInAppAgentAvailable({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ user: ctx.session.user,
+ });
await getOwnedConversationOrThrow({
prisma: ctx.prisma,
@@ -214,8 +323,9 @@ export const inAppAgentRouter = createTRPCRouter({
.input(SubmitFeedbackInput)
.mutation(async ({ ctx, input }) => {
const projectAvailability = await assertInAppAgentAvailable({
- ctx,
+ prisma: ctx.prisma,
projectId: input.projectId,
+ user: ctx.session.user,
});
await getOwnedConversationOrThrow({
@@ -292,51 +402,3 @@ export const inAppAgentRouter = createTRPCRouter({
return { feedback: { value: input.value, comment } };
}),
});
-
-async function assertInAppAgentAvailable({
- ctx,
- projectId,
-}: {
- ctx: {
- session: {
- user: NonNullable<Session["user"]>;
- };
- prisma: PrismaClient;
- };
- projectId: string;
-}) {
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- throw new BaseError(
- "PreconditionFailedError",
- 412,
- "In-app agent is not available in this environment yet.",
- true,
- );
- }
-
- throwIfNoEntitlement({
- entitlement: "in-app-agent",
- sessionUser: ctx.session.user,
- projectId,
- });
-
- const project = await ctx.prisma.project.findUnique({
- where: { id: projectId },
- select: {
- organization: {
- select: {
- aiFeaturesEnabled: true,
- aiTelemetryEnabled: true,
- },
- },
- },
- });
-
- if (!project?.organization.aiFeaturesEnabled) {
- throw new ForbiddenError("Assistant is not enabled for this organization");
- }
-
- return {
- aiTelemetryEnabled: project.organization.aiTelemetryEnabled,
- };
-}
diff --git a/web/src/features/in-app-agent/server/runContext.ts b/web/src/features/in-app-agent/server/runContext.ts
new file mode 100644
index 0000000000..b3989204a0
--- /dev/null
+++ b/web/src/features/in-app-agent/server/runContext.ts
@@ -0,0 +1,73 @@
+import {
+ type FilterState,
+ LangfuseNotFoundError,
+ TableViewPresetTableName,
+} from "@langfuse/shared";
+import type { AgUiRunAgentInput } from "@langfuse/shared/in-app-agent";
+
+type InAppAgentContext = AgUiRunAgentInput["context"];
+import {
+ logger,
+ parseSavedViewFromURL,
+ TableViewService,
+} from "@langfuse/shared/src/server";
+
+import { sanitizeInAppAgentContext } from "@/src/features/in-app-agent/context";
+
+/**
+ * Resolve and sanitize the AG-UI context items for a turn.
+ *
+ * Shared by the two submit paths: the foreground handler resolves at request
+ * time, and `startRun` resolves at submit time and stores the result in the
+ * run's request payload — so the worker replays a context that was resolved
+ * against the state the user actually saw, and never has to reach for a saved
+ * view that may since have been deleted.
+ */
+export async function resolveInAppAgentRunContext(params: {
+ context: InAppAgentContext;
+ projectId: string;
+ isV4Enabled: boolean;
+}): Promise<InAppAgentContext> {
+ const currentUrlContext = params.context.find(
+ (item) => item.description === "current_url",
+ );
+ const selectedSavedView = currentUrlContext
+ ? parseSavedViewFromURL(currentUrlContext.value, params.isV4Enabled)
+ : undefined;
+
+ let viewFilters: FilterState | undefined;
+
+ if (selectedSavedView) {
+ try {
+ const { filters, tableName } =
+ await TableViewService.getTableViewPresetsById(
+ selectedSavedView.viewId,
+ params.projectId,
+ );
+
+ if (
+ tableName === selectedSavedView.tableName ||
+ (selectedSavedView.tableName ===
+ TableViewPresetTableName.ObservationsEvents &&
+ tableName === TableViewPresetTableName.Observations)
+ ) {
+ viewFilters = filters;
+ }
+ } catch (error) {
+ // Saved views can be deleted while their URLs remain open or shared.
+ if (!(error instanceof LangfuseNotFoundError)) {
+ logger.warn("Failed to resolve saved view for in-app agent context", {
+ error,
+ projectId: params.projectId,
+ savedViewId: selectedSavedView.viewId,
+ });
+ }
+ }
+ }
+
+ return sanitizeInAppAgentContext(
+ params.context,
+ params.projectId,
+ viewFilters,
+ );
+}
diff --git a/web/src/features/in-app-agent/server/watchHandler.ts b/web/src/features/in-app-agent/server/watchHandler.ts
new file mode 100644
index 0000000000..7a0da1cc2e
--- /dev/null
+++ b/web/src/features/in-app-agent/server/watchHandler.ts
@@ -0,0 +1,160 @@
+import { getServerSession } from "next-auth";
+
+import { BaseError, ForbiddenError, UnauthorizedError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { addUserToSpan, logger } from "@langfuse/shared/src/server";
+import type { InAppAgentWatchFrame } from "@langfuse/shared/in-app-agent";
+import { assertConversationAccess } from "@langfuse/shared/in-app-agent/server/access";
+import { watchConversationFrames } from "@langfuse/shared/in-app-agent/server/watch";
+import { z } from "zod";
+
+import { assertInAppAgentAvailable } from "@/src/features/in-app-agent/server/availability";
+import { getAuthOptions } from "@/src/server/auth";
+import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
+
+const WatchQuerySchema = z.object({
+ projectId: z.string().min(1),
+ conversationId: z.string().min(1),
+ cursor: z.coerce.number().int().min(-1).default(-1),
+});
+
+export default async function watchHandler(request: Request) {
+ try {
+ const authOptions = await getAuthOptions();
+ const session = await getServerSession(authOptions);
+
+ if (!session?.user) {
+ throw new UnauthorizedError("Unauthenticated");
+ }
+
+ const user = session.user;
+
+ addUserToSpan({ userId: user.id, email: user.email ?? undefined });
+
+ const url = new URL(request.url);
+ const query = WatchQuerySchema.safeParse({
+ projectId: url.searchParams.get("projectId"),
+ conversationId: url.searchParams.get("conversationId"),
+ cursor:
+ url.searchParams.get("cursor") ??
+ request.headers.get("last-event-id") ??
+ -1,
+ });
+
+ if (!query.success) {
+ return Response.json({ error: "Invalid watch query" }, { status: 400 });
+ }
+
+ const { projectId, conversationId, cursor } = query.data;
+
+ if (!isProjectMemberOrAdmin(user, projectId)) {
+ throw new ForbiddenError("User is not a member of this project");
+ }
+
+ await assertInAppAgentAvailable({ prisma, projectId, user });
+
+ const conversation = await prisma.inAppAgentConversation.findUnique({
+ where: { id_projectId: { id: conversationId, projectId } },
+ select: { createdByUserId: true, deletedAt: true },
+ });
+
+ if (!conversation) {
+ throw new BaseError("NotFoundError", 404, "Conversation not found", true);
+ }
+
+ assertConversationAccess({
+ conversation,
+ userId: user.id,
+ });
+
+ // Everything fallible is done; from here on the response is a stream and
+ // failures can only be reported inside it.
+ const stream = createWatchStream({
+ projectId,
+ conversationId,
+ cursor,
+ signal: request.signal,
+ });
+
+ return new Response(stream as unknown as BodyInit, {
+ headers: {
+ "Content-Type": "text/event-stream; charset=utf-8",
+ "Content-Encoding": "none",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no",
+ },
+ });
+ } catch (error) {
+ if (error instanceof BaseError) {
+ return Response.json(
+ { error: error.message },
+ { status: error.httpCode },
+ );
+ }
+
+ throw error;
+ }
+}
+
+function createWatchStream(params: {
+ projectId: string;
+ conversationId: string;
+ cursor: number;
+ signal: AbortSignal;
+}): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder();
+
+ return new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const frames = watchConversationFrames({
+ prisma,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ cursor: params.cursor,
+ signal: params.signal,
+ });
+
+ try {
+ for await (const frame of frames) {
+ if (params.signal.aborted) {
+ break;
+ }
+
+ controller.enqueue(
+ encoder.encode(
+ frame === null ? ": keepalive\n\n" : encodeFrame(frame),
+ ),
+ );
+ }
+ } catch (error) {
+ logger.error("In-app agent watch stream failed", {
+ error,
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ });
+
+ if (!params.signal.aborted) {
+ controller.enqueue(
+ encoder.encode(
+ encodeFrame({
+ type: "error",
+ code: "watch_failed",
+ message: "The connection to the run was interrupted.",
+ }),
+ ),
+ );
+ }
+ } finally {
+ await frames.return(undefined);
+ controller.close();
+ }
+ },
+ });
+}
+
+function encodeFrame(frame: InAppAgentWatchFrame): string {
+ const id = frame.type === "event" ? `id: ${frame.sequenceNumber}\n` : "";
+
+ return `${id}event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`;
+}
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
index 22c4dd9c36..1b93558422 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -8,9 +8,7 @@ import {
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";
@@ -50,6 +48,7 @@ vi.mock("@langfuse/shared/in-app-agent/server", async (importOriginal) => {
return {
...actual,
+ IN_APP_AGENT_HEARTBEAT_INTERVAL_MS: 50,
createAgUiStream: async (params: {
input: never;
signal: AbortSignal;
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index 3ce2143785..017d595b2e 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -362,30 +362,20 @@ export async function executeInAppAgentRun(params: {
// ---- Run the loop; persistence via onEvent, no consumer for the SSE text. ----
const pendingPersistedEvents: AgUiEvent[] = [];
- const flushPersistedRunEvents = () =>
+ const flushPersistedRunEvents = (
+ finish?: Parameters<typeof flushPendingRunEvents>[0]["finish"],
+ ) =>
flushPendingRunEvents({
prisma,
projectId,
conversationId: conversation.id,
runId,
pendingEvents: pendingPersistedEvents,
+ finish,
});
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,
@@ -435,8 +425,7 @@ export async function executeInAppAgentRun(params: {
return flushPersistedRunEvents();
},
onComplete: async () => {
- await flushPersistedRunEvents();
- await finishWith(
+ await flushPersistedRunEvents(
interruptRequest
? { status: InAppAgentRunStatus.AWAITING_APPROVAL }
: { status: InAppAgentRunStatus.SUCCEEDED },
@@ -456,7 +445,6 @@ export async function executeInAppAgentRun(params: {
);
},
onAbort: async () => {
- await flushPersistedRunEvents();
const reason = abortController.signal.reason as AbortReason;
if (reason === "fenced") {
@@ -471,7 +459,7 @@ export async function executeInAppAgentRun(params: {
// and recording plain CANCELLED would read as "nothing happened".
const unknownOutcome = failureCode();
- await finishWith(
+ await flushPersistedRunEvents(
unknownOutcome
? { status: InAppAgentRunStatus.FAILED, ...unknownOutcome }
: {
@@ -483,7 +471,7 @@ export async function executeInAppAgentRun(params: {
return;
}
- await finishWith({
+ await flushPersistedRunEvents({
status: InAppAgentRunStatus.FAILED,
...(failureCode() ?? {
errorCode: InAppAgentRunErrorCode.WORKER_SHUTDOWN,
@@ -492,8 +480,7 @@ export async function executeInAppAgentRun(params: {
});
},
onError: async (error) => {
- await flushPersistedRunEvents();
- await finishWith({
+ await flushPersistedRunEvents({
status: InAppAgentRunStatus.FAILED,
...(failureCode() ?? {
errorCode: InAppAgentRunErrorCode.AGENT_ERROR,