🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(in-app-agent): make background execution the default path (#15835)
Lysander Kiesel3972f039d77a
diff --git a/.env.dev.example b/.env.dev.exampleindex 325da7028e..418e864f51 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -209,9 +209,11 @@ LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"# Optional: overrides Lambda's default INTERNET_EGRESS connector.# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EGRESS_NETWORK_CONNECTOR_ARN="arn:aws:lambda:us-east-1:123456789012:network-connector:langfuse-in-app-agent-sandbox-egress"-# Background execution of in-app agent runs (worker queue consumer, off by default).-# QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED="true"+# Turns run in background by default; without the consumer they die at queue_timeout.+QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED="true"# LANGFUSE_IN_APP_AGENT_RUN_QUEUE_PROCESSING_CONCURRENCY=5+# Background is the default; uncomment to force the foreground path locally.+# LANGFUSE_IN_APP_AGENT_EXECUTION_MODE="foreground"# V4 migration flags. Pinned to dual write mode to ensure we cover the tests;# bare deployments get the flipped v4 code defaults (events_only / direct).diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 7d79e9da22..f0f6efe2c7 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -534,6 +534,11 @@ const EnvSchema = z.object({.int().positive().default(24 * 60 * 60_000),+ // Rollback switch for the in-app agent: flip to "foreground" and ship.+ // Nothing sets this per region, so this default is the only place to change.+ LANGFUSE_IN_APP_AGENT_EXECUTION_MODE: z+ .enum(["background", "foreground"])+ .default("background"),// 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.coercediff --git a/web/src/features/in-app-agent/README.md b/web/src/features/in-app-agent/README.mdindex 032a7dad26..b93374b316 100644--- a/web/src/features/in-app-agent/README.md+++ b/web/src/features/in-app-agent/README.md@@ -1,8 +1,9 @@# In-App AgentThe in-app agent is Langfuse's project-scoped assistant inside the authenticated-product UI. Foreground execution remains the production default; an opt-in-background path executes the same conversation through a worker-owned run.+product UI. Background execution through a worker-owned run is the default; the+request-scoped foreground path remains as the rollback target until it is+deleted.`ARCHITECTURE.md` covers why the feature is shaped this way: the one-log /three-derivations contract, where code lives and why, the target state after@@ -20,11 +21,16 @@ The browser owns interaction state and submits intent. The server owns authorizaA conversation can have one active run. The browser uses one execution mode fora turn:-- **Foreground (default):** `HttpAgent` owns the live request. The run cannot- outlive the browser session.-- **Background (local opt-in):** the browser starts a durable run, hydrates one+- **Background (default):** the browser starts a durable run, hydrates onepersisted transcript/cursor snapshot, and observes its tail. Closing thedrawer detaches observation without cancelling the server run.+- **Foreground (rollback):** `HttpAgent` owns the live request. The run cannot+ outlive the browser session and is capped by the route's 120s `maxDuration`.++`lib/executionMode.ts` resolves which one applies, from the deployment's+`LANGFUSE_IN_APP_AGENT_EXECUTION_MODE` read through+`inAppAgent.getExecutionMode`. There is no per-user override. See "Rollout And+Migration" below.## Major Files@@ -54,7 +60,7 @@ a turn:- `lib/backgroundAgentClient.ts`: durable run start/watch AG-UI adapter.- `lib/backgroundExecutionSession.ts`: background transcript, cursor, run,approval, attachment, cancel, and decision owner.-- `lib/backgroundExecutionFlag.ts`: local, default-off background opt-in.+- `lib/executionMode.ts`: reads the deployment's execution mode.Outside this feature folder, `packages/in-app-agent-sandbox-runtime/src/*` provides the shared sandbox runtime and contract types used by both the local Docker provider and the Lambda MicroVM image.@@ -114,8 +120,8 @@ flowchart TB### Background-1. The provider selects the background client only when the local opt-in is- enabled and starts the durable run through `startRun`.+1. The provider selects the background client unless the resolved execution mode+ is foreground, and starts the durable run through `startRun`.2. `BackgroundExecutionSessionController` installs the persisted canonicalmessages, the display state, and the cursor before attaching the watchstream. The seed is never projected or pruned; see `ARCHITECTURE.md`.@@ -165,11 +171,30 @@ no product decision that a separate click event would answer yet.## Rollout And Migration-Background execution is default-off while the remaining project work is-completed and canaried. Conversation switching, detached invalidations,-capacity controls, retry, and conversation-list run statuses are separate-project issues. After background execution is stable, the foreground transport-and its state can be removed rather than preserved as a permanent abstraction.+Background execution is the default everywhere.++**Rollback is one line:** flip the `LANGFUSE_IN_APP_AGENT_EXECUTION_MODE`+default in `packages/shared/src/env.ts` to `"foreground"` and ship. Nothing sets+that variable per region, so that default is the single source of truth, and a+one-line PR puts every deployment back on the request-scoped path. It takes+effect on each client's next page load.++The variable exists on top of the default so an operator can override without a+code change if a redeploy is too slow. Anything that sets it per region would+become a second place to check during an incident, which is why nothing does.+It is server-owned rather than `NEXT_PUBLIC_*` because `web/Dockerfile` bakes+`NEXT_PUBLIC_*` at image build time.++`QUEUE_CONSUMER_IN_APP_AGENT_RUN_QUEUE_IS_ENABLED` must be on wherever turns run+in background, otherwise runs commit as `QUEUED` and die at `queue_timeout`. It+is already enabled in every Langfuse Cloud region. Check+`LANGFUSE_IN_APP_AGENT_MAX_ACTIVE_RUNS_PER_ORG` against execution capacity too:+its default of 20 equals full US capacity and exceeds JP and staging.++Conversation switching, detached invalidations, retry, and conversation-list run+statuses are separate project issues. After background execution is stable, the+foreground transport and its state can be removed rather than preserved as a+permanent abstraction.## Sandbox Runtimediff --git a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsxindex 02f8bdb95a..7e4c7dd0c8 100644--- a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx@@ -110,7 +110,7 @@ vi.mock("@/src/features/projects/hooks", () => ({}),}));-vi.mock("@/src/features/in-app-agent/lib/backgroundExecutionFlag", () => ({+vi.mock("@/src/features/in-app-agent/lib/executionMode", () => ({useInAppAgentBackgroundExecutionEnabled: () =>providerMocks.backgroundExecutionEnabled,}));diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 5f7219bf9f..573b4c82be 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -48,7 +48,7 @@ import {type InAppAgentDisplayState,} from "@/src/features/in-app-agent/lib/display";import { InAppAgentBackgroundClient } from "@/src/features/in-app-agent/lib/backgroundAgentClient";-import { useInAppAgentBackgroundExecutionEnabled } from "@/src/features/in-app-agent/lib/backgroundExecutionFlag";+import { useInAppAgentBackgroundExecutionEnabled } from "@/src/features/in-app-agent/lib/executionMode";import {BackgroundExecutionSessionController,isCancellableBackgroundRun,@@ -346,7 +346,8 @@ function InAppAiAgentProviderInner({const activeRunIdRef = useRef<string | null>(null);const toolCallNamesRef = useRef(new Map<string, string>());const handledToolCallIdsRef = useRef(new Set<string>());- const backgroundExecutionEnabled = useInAppAgentBackgroundExecutionEnabled();+ const backgroundExecutionEnabled =+ useInAppAgentBackgroundExecutionEnabled(projectId);const intentionalAbortRef = useRef(false);const submitInFlightRef = useRef(false);const runInFlightRef = useRef(false);@@ -1389,7 +1390,13 @@ function InAppAiAgentProviderInner({if (isNewConversation) {capture("in_app_agent:new_chat_started", { entryPoint });}- capture("in_app_agent:new_chat_turn", { entryPoint });+ capture("in_app_agent:new_chat_turn", {+ entryPoint,+ // Compares the two paths and confirms a rollback took effect.+ executionMode: backgroundExecutionEnabled+ ? "background"+ : "foreground",+ });startedRun = true;if (backgroundExecutionEnabled) {const backgroundSession = backgroundSessionRef.current;diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionFlag.ts b/web/src/features/in-app-agent/lib/backgroundExecutionFlag.tsdeleted file mode 100644index a88bdbf14f..0000000000--- a/web/src/features/in-app-agent/lib/backgroundExecutionFlag.ts+++ /dev/null@@ -1,14 +0,0 @@-import { useBrowserStorageValue } from "@/src/features/events/lib/appRootDefaultStorage";--// Internal dogfood switch; server authorization is independent of this flag.-export const IN_APP_AGENT_BACKGROUND_EXECUTION_STORAGE_KEY =- "langfuse-in-app-agent-background-execution";--export function useInAppAgentBackgroundExecutionEnabled(): boolean {- return (- useBrowserStorageValue(- "localStorage",- IN_APP_AGENT_BACKGROUND_EXECUTION_STORAGE_KEY,- ) === "true"- );-}diff --git a/web/src/features/in-app-agent/lib/executionMode.ts b/web/src/features/in-app-agent/lib/executionMode.tsnew file mode 100644index 0000000000..947cf84509--- /dev/null+++ b/web/src/features/in-app-agent/lib/executionMode.ts@@ -0,0 +1,20 @@+import { api } from "@/src/utils/api";++/**+ * Unresolved reports background, the shipped default. Falling back to+ * foreground would let a slow query defeat the rollout.+ */+export function useInAppAgentBackgroundExecutionEnabled(+ projectId: string,+): boolean {+ const executionModeQuery = api.inAppAgent.getExecutionMode.useQuery(+ { projectId },+ {+ enabled: Boolean(projectId),+ staleTime: Infinity,+ gcTime: Infinity,+ },+ );++ return executionModeQuery.data?.mode !== "foreground";+}diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.tsindex 9ea9594df4..af20dccf78 100644--- a/web/src/features/in-app-agent/server/router.ts+++ b/web/src/features/in-app-agent/server/router.ts@@ -11,6 +11,7 @@ import {upsertScore,} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";+import { env as sharedEnv } from "@langfuse/shared/src/env";import {AgUiContextSchema,getInAppAgentInstrumentationObservationId,@@ -88,6 +89,14 @@ const IN_APP_AGENT_FEEDBACK_SCORE_NAME = "in_app_agent_feedback";const IN_APP_AGENT_FEEDBACK_ENVIRONMENT = "langfuse-in-app-agent";export const inAppAgentRouter = createTRPCRouter({+ // Deployment config, not agent access, so no availability assert: an org+ // without the entitlement should get an answer rather than an error.+ getExecutionMode: protectedProjectProcedureWithoutTracing+ .input(z.object({ projectId: z.string() }))+ .query(() => ({+ mode: sharedEnv.LANGFUSE_IN_APP_AGENT_EXECUTION_MODE,+ })),+listConversations: protectedProjectProcedure.input(z.object({