Skip to content

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

feat(agent): bound concurrent background runs per user and organization (#15809)

Lysander Kiesel34d5c9fc90e8
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 017a29f9ba..7d79e9da22 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -534,6 +534,18 @@ const EnvSchema = z.object({
.int()
.positive()
.default(24 * 60 * 60_000),
+ // Flat safety ceilings on concurrent non-terminal runs. Per region, so a
+ // small region (JP, staging) can be tightened below its execution capacity.
+ LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(5),
+ LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(20),
LANGFUSE_IN_APP_AGENT_WATCH_TAIL_POLL_MS: z.coerce
.number()
.int()
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 086cea59b5..e8e15b4607 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
@@ -8,7 +8,8 @@ import type {
} from "@langfuse/shared/in-app-agent";
import { appendRunEvents } from "@langfuse/shared/in-app-agent/server/persistence";
import { env } from "@/src/env.mjs";
-import { InAppAgentRunStatus } from "@langfuse/shared";
+import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "@langfuse/shared";
+import { env as sharedEnv } from "@langfuse/shared/src/env";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import {
createAndAddApiKeysToDb,
@@ -1191,6 +1192,84 @@ describe("in-app agent public API route auth", () => {
}
});
+ it("sweeps the conversation's own stale run before applying the active-run ceiling", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { project, userId } = await setupInAppAgentProjectSession();
+ const conversationId = `conversation-${randomUUID()}`;
+ const originalMaxActiveRunsPerUser =
+ sharedEnv.LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER;
+
+ await prisma.inAppAgentConversation.create({
+ data: {
+ id: conversationId,
+ projectId: project.id,
+ createdByUserId: userId,
+ },
+ });
+
+ // A foreground stream that died before finishRun ran: `createRun`
+ // stale-closes exactly this row further down, so the ceiling must not
+ // count it and reject the replacement first. This route is the rollback
+ // path, where leaked rows and users at their ceiling coincide.
+ const abandonedRun = await prisma.inAppAgentRun.create({
+ data: {
+ id: `run-${randomUUID()}`,
+ projectId: project.id,
+ conversationId,
+ triggeredByUserId: userId,
+ status: InAppAgentRunStatus.RUNNING,
+ createdAt: new Date(Date.now() - 5 * 60_000),
+ },
+ });
+
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER = 1;
+
+ try {
+ const { default: handler } =
+ await import("@/src/features/in-app-agent/server/handler");
+ const response = await handler(
+ new Request("http://localhost/api/in-app-agent", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ threadId: conversationId,
+ runId: `client-run-${randomUUID()}`,
+ messages: [
+ {
+ id: `message-${randomUUID()}`,
+ role: "user",
+ content: "my run died, let me retry",
+ },
+ ],
+ tools: [],
+ context: [],
+ state: {
+ type: "existingConversation",
+ projectId: project.id,
+ conversationId,
+ },
+ forwardedProps: {},
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(agentMocks.createAgUiStream).toHaveBeenCalled();
+ await expect(
+ prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: abandonedRun.id, projectId: project.id },
+ }),
+ ).resolves.toMatchObject({
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: InAppAgentRunErrorCode.STALE,
+ });
+ } finally {
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER =
+ originalMaxActiveRunsPerUser;
+ }
+ });
+ });
+
it("passes malicious current_url search params as bounded screen context data", async () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
diff --git a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
index 54e09b749f..ed5cb45988 100644
--- a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
@@ -23,6 +23,7 @@ import {
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 as sharedEnv } from "@langfuse/shared/src/env";
import { env } from "@/src/env.mjs";
import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
@@ -74,6 +75,10 @@ vi.mock("@/src/server/auth", () => ({
describe("in-app agent background runs", () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
+ const originalMaxActiveRunsPerUser =
+ sharedEnv.LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER;
+ const originalMaxActiveRunsPerOrg =
+ sharedEnv.LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG;
beforeEach(() => {
(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
@@ -89,6 +94,10 @@ describe("in-app agent background runs", () => {
afterEach(() => {
(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
(env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER =
+ originalMaxActiveRunsPerUser;
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG =
+ originalMaxActiveRunsPerOrg;
});
const createCaller = async (
@@ -212,6 +221,25 @@ describe("in-app agent background runs", () => {
return runId;
};
+ /** An unfinished run holding a capacity slot, without going through submit. */
+ const createActiveRun = async (params: {
+ projectId: string;
+ conversationId: string;
+ userId: string;
+ createdAt?: Date;
+ }) =>
+ prisma.inAppAgentRun.create({
+ data: {
+ id: createInAppAgentRunId(),
+ projectId: params.projectId,
+ conversationId: params.conversationId,
+ triggeredByUserId: params.userId,
+ status: InAppAgentRunStatus.QUEUED,
+ request: { kind: "userMessage", context: [] },
+ ...(params.createdAt ? { createdAt: params.createdAt } : {}),
+ },
+ });
+
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 });
@@ -294,6 +322,167 @@ describe("in-app agent background runs", () => {
).toBe(1);
});
+ it("rejects a submit that exceeds the organization's active-run ceiling", async () => {
+ const { caller, orgId, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ // The slot is held by a different project of the same organization: the
+ // ceiling is organization-wide, so scoping the count to the submitting
+ // project would silently let an organization occupy a whole region.
+ const otherProject = await prisma.project.create({
+ data: { orgId, name: `other-project-${randomUUID()}` },
+ });
+ const otherConversation = await createConversation({
+ projectId: otherProject.id,
+ userId,
+ });
+ await createActiveRun({
+ projectId: otherProject.id,
+ conversationId: otherConversation.id,
+ userId,
+ });
+
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG = 1;
+
+ await expect(
+ caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "one too many",
+ }),
+ ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
+
+ // Rejected at admission: nothing committed, nothing queued.
+ expect(await prisma.inAppAgentRun.count({ where: { projectId } })).toBe(0);
+ expect(await prisma.inAppAgentEvent.count({ where: { projectId } })).toBe(
+ 0,
+ );
+ expect(enqueuedJobs).toEqual([]);
+ });
+
+ it("stops counting an active run that outlived its reconciliation deadline", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const abandonedConversation = await createConversation({
+ projectId,
+ userId,
+ });
+
+ // Conversation-scoped reconciliation only fires when that conversation is
+ // read, so a leaked QUEUED row would otherwise hold a slot forever.
+ await createActiveRun({
+ projectId,
+ conversationId: abandonedConversation.id,
+ userId,
+ createdAt: new Date(
+ Date.now() -
+ sharedEnv.LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS -
+ sharedEnv.LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS -
+ 60_000,
+ ),
+ });
+
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER = 1;
+
+ const { runId } = await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "the abandoned run must not block me",
+ });
+
+ expect(
+ await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: runId, projectId },
+ }),
+ ).toMatchObject({ status: InAppAgentRunStatus.QUEUED });
+ });
+
+ it("keeps counting an overdue run whose worker is still heartbeating", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const hungConversation = await createConversation({ projectId, userId });
+
+ // Nothing enforces the maximum duration in-process, so a hung tool call
+ // heartbeats past it and holds a real worker slot. Age alone must not free
+ // its slot in the accounting, or the ceiling leaks while hung runs pile up.
+ const overdue = new Date(
+ Date.now() -
+ sharedEnv.LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS -
+ sharedEnv.LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS -
+ 60_000,
+ );
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: createInAppAgentRunId(),
+ projectId,
+ conversationId: hungConversation.id,
+ triggeredByUserId: userId,
+ status: InAppAgentRunStatus.RUNNING,
+ request: { kind: "userMessage", context: [] },
+ createdAt: overdue,
+ claimedAt: overdue,
+ heartbeatAt: new Date(),
+ },
+ });
+
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER = 1;
+
+ await expect(
+ caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "the hung run still owns a worker",
+ }),
+ ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
+ });
+
+ it("admits a replacement turn when the conversation's own run lost its worker", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+
+ // Claimed recently enough to sit inside the capacity cutoff, but its
+ // heartbeat is dead: reconciliation will fail it, so the ceiling must not
+ // reject the replacement before that happens (a worker task rotating on
+ // deploy leaves exactly this row).
+ const abandonedRun = await prisma.inAppAgentRun.create({
+ data: {
+ id: createInAppAgentRunId(),
+ projectId,
+ conversationId: conversation.id,
+ triggeredByUserId: userId,
+ status: InAppAgentRunStatus.RUNNING,
+ request: { kind: "userMessage", context: [] },
+ createdAt: new Date(Date.now() - 5 * 60_000),
+ claimedAt: new Date(Date.now() - 5 * 60_000),
+ heartbeatAt: new Date(
+ Date.now() - sharedEnv.LANGFUSE_IN_APP_AGENT_HEARTBEAT_STALE_MS * 3,
+ ),
+ },
+ });
+
+ (sharedEnv as any).LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER = 1;
+
+ const { runId } = await caller.startRun({
+ projectId,
+ conversationId: conversation.id,
+ message: "my run died, let me retry",
+ });
+
+ expect(
+ await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: abandonedRun.id, projectId },
+ }),
+ ).toMatchObject({
+ status: InAppAgentRunStatus.FAILED,
+ errorCode: InAppAgentRunErrorCode.WORKER_LOST,
+ });
+ expect(
+ await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: runId, projectId },
+ }),
+ ).toMatchObject({ status: InAppAgentRunStatus.QUEUED });
+ });
+
it("supersedes a pending approval when a new message is submitted", async () => {
const { caller, projectId, userId } = await createCaller();
const conversation = await createConversation({ projectId, userId });
diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.ts
index 00861f0296..7ecb55f271 100644
--- a/web/src/features/in-app-agent/server/backgroundRunService.ts
+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts
@@ -6,6 +6,7 @@ import {
InAppAgentRunErrorCode,
InAppAgentRunStatus,
LangfuseNotFoundError,
+ type Plan,
} from "@langfuse/shared";
import { Prisma, type PrismaClient } from "@langfuse/shared/src/db";
import {
@@ -40,6 +41,7 @@ import {
} from "@langfuse/shared/in-app-agent/server/runLifecycle";
import { serializeInAppAgentDisplayState } from "@/src/features/in-app-agent/lib/display";
+import { assertInAppAgentRunCapacity } from "@/src/features/in-app-agent/server/runCapacity";
import { resolveInAppAgentRunContext } from "@/src/features/in-app-agent/server/runContext";
import { getConversationSnapshotFromEvents } from "@/src/features/in-app-agent/server/conversationSnapshot";
@@ -148,6 +150,8 @@ export async function getBackgroundConversationSnapshot(params: {
export async function startBackgroundRun(params: {
prisma: PrismaClient;
projectId: string;
+ orgId: string;
+ plan: Plan;
conversationId: string;
userId: string;
message: string;
@@ -162,6 +166,24 @@ export async function startBackgroundRun(params: {
conversationId: params.conversationId,
userId: params.userId,
});
+
+ // Reconcile before counting capacity: this turn is allowed to replace a run
+ // of its own conversation that already lost its worker or timed out, which
+ // `createQueuedRun` does under the lock further down. Counting that row would
+ // reject the replacement with a ceiling error instead. Ownership is verified
+ // above first, because reconciliation writes.
+ await reconcileConversationRuns({
+ prisma: params.prisma,
+ projectId: params.projectId,
+ conversationId: conversation.id,
+ });
+ await assertInAppAgentRunCapacity({
+ prisma: params.prisma,
+ orgId: params.orgId,
+ plan: params.plan,
+ userId: params.userId,
+ });
+
const events = await getConversationEvents({
prisma: params.prisma,
projectId: params.projectId,
diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.ts
index b79c933421..3da7d4b912 100644
--- a/web/src/features/in-app-agent/server/handler.ts
+++ b/web/src/features/in-app-agent/server/handler.ts
@@ -15,6 +15,8 @@ import {
checkInAppAgentRateLimit,
getInAppAgentApiAccessScope,
} from "@/src/features/in-app-agent/server/rateLimit";
+import { assertInAppAgentRunCapacity } from "@/src/features/in-app-agent/server/runCapacity";
+import { reconcileConversationRuns } from "@langfuse/shared/in-app-agent/server/runLifecycle";
import { getInAppAgentInstrumentationTraceId } from "@langfuse/shared/in-app-agent";
import {
AgUiRunAgentInputSchema,
@@ -235,7 +237,8 @@ export default async function handler(request: Request) {
plan: rateLimitScope.plan,
});
- // TODO: Add an additional user-level cap once the rate-limit service supports non-org keys.
+ // TODO: Add a per-user submission bucket once the rate-limit service
+ // supports non-org keys; the concurrency ceiling below is per user already.
const rateLimitResponse = await rateLimitInAppAgentRequest(
rateLimitScope,
"in-app-agent-run",
@@ -251,6 +254,24 @@ export default async function handler(request: Request) {
conversationId,
userId: userId,
});
+
+ // Reconcile, then count, in the order `startBackgroundRun` uses: this turn
+ // is allowed to replace a run of its own conversation that `createRun`
+ // would stale-close below, so counting that row would reject the
+ // replacement with a ceiling error instead. The ceiling is applied on this
+ // route at all so it cannot be bypassed by submitting through the
+ // foreground path, exactly as the shared rate-limit scope cannot be.
+ await reconcileConversationRuns({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ });
+ await assertInAppAgentRunCapacity({
+ prisma,
+ orgId: rateLimitScope.orgId,
+ plan: rateLimitScope.plan,
+ userId,
+ });
const conversationEvents = await getConversationEvents({
prisma,
projectId,
diff --git a/web/src/features/in-app-agent/server/rateLimit.ts b/web/src/features/in-app-agent/server/rateLimit.ts
index 7e261102a3..487fa6f066 100644
--- a/web/src/features/in-app-agent/server/rateLimit.ts
+++ b/web/src/features/in-app-agent/server/rateLimit.ts
@@ -19,7 +19,9 @@ type SessionUser = NonNullable<Session["user"]>;
* 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.
+ * TODO: this bucket is org-scoped only; a per-user submission cap needs the
+ * rate-limit service to support non-org keys. Concurrency is capped per user by
+ * `assertInAppAgentRunCapacity`.
*/
export function getInAppAgentApiAccessScope(
user: SessionUser,
diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.ts
index 8abaf45d4f..9ea9594df4 100644
--- a/web/src/features/in-app-agent/server/router.ts
+++ b/web/src/features/in-app-agent/server/router.ts
@@ -32,6 +32,7 @@ import {
assertInAppAgentRateLimit,
getInAppAgentApiAccessScope,
} from "@/src/features/in-app-agent/server/rateLimit";
+import { assertInAppAgentRunCapacity } from "@/src/features/in-app-agent/server/runCapacity";
import {
cancelBackgroundRun,
decideBackgroundApproval,
@@ -176,18 +177,21 @@ export const inAppAgentRouter = createTRPCRouter({
user: ctx.session.user,
});
- await assertInAppAgentRateLimit(
- getInAppAgentApiAccessScope(
- ctx.session.user,
- input.projectId,
- projectAvailability,
- ),
- "in-app-agent-run",
+ const rateLimitScope = getInAppAgentApiAccessScope(
+ ctx.session.user,
+ input.projectId,
+ projectAvailability,
);
+ await assertInAppAgentRateLimit(rateLimitScope, "in-app-agent-run");
+
+ // The concurrency ceiling is enforced inside `startBackgroundRun`, which
+ // owns the conversation lookup it has to reconcile against first.
return startBackgroundRun({
prisma: ctx.prisma,
projectId: input.projectId,
+ orgId: rateLimitScope.orgId,
+ plan: rateLimitScope.plan,
conversationId: input.conversationId,
userId: ctx.session.user.id,
message: input.message,
@@ -232,15 +236,23 @@ export const inAppAgentRouter = createTRPCRouter({
user: ctx.session.user,
});
- await assertInAppAgentRateLimit(
- getInAppAgentApiAccessScope(
- ctx.session.user,
- input.projectId,
- projectAvailability,
- ),
- "in-app-agent-run",
+ const rateLimitScope = getInAppAgentApiAccessScope(
+ ctx.session.user,
+ input.projectId,
+ projectAvailability,
);
+ await assertInAppAgentRateLimit(rateLimitScope, "in-app-agent-run");
+ // A continuation is a fresh run that occupies a worker slot, and parked
+ // approvals accumulate without holding one, so this path needs the
+ // ceiling for the same reason it already needs the daily bucket.
+ await assertInAppAgentRunCapacity({
+ prisma: ctx.prisma,
+ orgId: rateLimitScope.orgId,
+ plan: rateLimitScope.plan,
+ userId: ctx.session.user.id,
+ });
+
return decideBackgroundApproval({
prisma: ctx.prisma,
projectId: input.projectId,
diff --git a/web/src/features/in-app-agent/server/runCapacity.ts b/web/src/features/in-app-agent/server/runCapacity.ts
new file mode 100644
index 0000000000..8ab28d1fa6
--- /dev/null
+++ b/web/src/features/in-app-agent/server/runCapacity.ts
@@ -0,0 +1,101 @@
+import { BaseError, type Plan } from "@langfuse/shared";
+import type { PrismaClient } from "@langfuse/shared/src/db";
+import { env } from "@langfuse/shared/src/env";
+import { recordIncrement } from "@langfuse/shared/src/server";
+
+/**
+ * Flat safety ceiling on concurrent non-terminal runs, checked at admission.
+ *
+ * The daily `in-app-agent-run` bucket is also a burst allowance: it cannot stop
+ * one organization from filling a region's execution slots for 15 minutes at a
+ * time. This one count bounds queue depth, attached watches, poll load, worker
+ * occupancy and model spend. It is a safety valve, not a plan entitlement.
+ *
+ * Only QUEUED and RUNNING rows have `finishedAt: null`. A parked approval sets
+ * it, so it holds neither a worker nor the conversation slot and correctly does
+ * not count.
+ *
+ * The ceiling is coarse by design. The check runs outside the run-creating
+ * transaction, whose lock covers a single conversation and so cannot serialize
+ * submits across conversations anyway; concurrent submits may overshoot by the
+ * number of in-flight requests. The exact one-active-run-per-conversation
+ * invariant stays with the partial unique index.
+ */
+export async function assertInAppAgentRunCapacity(params: {
+ prisma: PrismaClient;
+ orgId: string;
+ plan: Plan;
+ userId: string;
+}): Promise<void> {
+ // A row past every reconciliation deadline must not hold a slot forever:
+ // conversation-scoped reconciliation only fires when that conversation is
+ // read, so a leaked row in a conversation nobody opens would block its user
+ // indefinitely. This is a coarse "should already have been failed" test, not
+ // proof the run stopped: nothing enforces RUN_MAX_DURATION in-process, so a
+ // hung tool keeps heartbeating past it (see `classifyStaleRun`, "Duration
+ // wins because a hung tool may keep renewing its heartbeat").
+ const reconcilableBefore = new Date(
+ Date.now() -
+ env.LANGFUSE_IN_APP_AGENT_QUEUE_TIMEOUT_MS -
+ env.LANGFUSE_IN_APP_AGENT_RUN_MAX_DURATION_MS,
+ );
+ // Which is why a fresh heartbeat overrides that test. It is the one positive
+ // liveness signal a row carries, and a run still holding a worker must keep
+ // counting however old it is, or the ceiling leaks exactly when hung runs are
+ // accumulating.
+ const heartbeatAliveSince = new Date(
+ Date.now() - env.LANGFUSE_IN_APP_AGENT_HEARTBEAT_STALE_MS,
+ );
+
+ // Grouped by user so one query answers both ceilings. Scoped through the
+ // project relation rather than a session-derived project list, which only
+ // holds the projects the caller can see and would undercount the org.
+ const activeRunsByUser = await params.prisma.inAppAgentRun.groupBy({
+ by: ["triggeredByUserId"],
+ where: {
+ project: { orgId: params.orgId },
+ finishedAt: null,
+ OR: [
+ { createdAt: { gt: reconcilableBefore } },
+ { heartbeatAt: { gt: heartbeatAliveSince } },
+ ],
+ },
+ _count: { _all: true },
+ });
+
+ const orgActiveRuns = activeRunsByUser.reduce(
+ (total, group) => total + group._count._all,
+ 0,
+ );
+ const userActiveRuns =
+ activeRunsByUser.find((group) => group.triggeredByUserId === params.userId)
+ ?._count._all ?? 0;
+
+ const perUser = env.LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_USER;
+ const perOrg = env.LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG;
+
+ // User first, so the message names the limit the caller can act on.
+ const exceeded =
+ userActiveRuns >= perUser
+ ? {
+ limit: "user" as const,
+ message: `You already have ${perUser} assistant runs in progress. Wait for one to finish.`,
+ }
+ : orgActiveRuns >= perOrg
+ ? {
+ limit: "org" as const,
+ message: `Your organization is at its limit of ${perOrg} assistant runs in progress. Try again shortly.`,
+ }
+ : null;
+
+ if (!exceeded) {
+ return;
+ }
+
+ recordIncrement("langfuse.in_app_agent.run_capacity_rejected", 1, {
+ plan: params.plan,
+ limit: exceeded.limit,
+ });
+
+ throw new BaseError("TooManyRequestsError", 429, exceeded.message, true);
+}