🪢 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(agent): Add client/web support for 'in-app agent' background execution (with a canonical hydration contract) (LFE-14374) (#15661)
Lysander Kieseld18dbacc75bd
diff --git a/packages/shared/src/in-app-agent/index.ts b/packages/shared/src/in-app-agent/index.tsindex df8453dc7c..b48f743f6a 100644--- a/packages/shared/src/in-app-agent/index.ts+++ b/packages/shared/src/in-app-agent/index.ts@@ -5,3 +5,4 @@ export * from "./schema";export * from "./backgroundWatch";export * from "./constants";export * from "./ids";+export * from "./messages";diff --git a/packages/shared/src/in-app-agent/messages.ts b/packages/shared/src/in-app-agent/messages.tsnew file mode 100644index 0000000000..e4588c67aa--- /dev/null+++ b/packages/shared/src/in-app-agent/messages.ts@@ -0,0 +1,65 @@+import type { AgUiMessage } from "./schema";++/**+ * Message-shape pruning shared by model-context replay and settled-transcript+ * rendering. These operate on canonical AG-UI messages and must never run over+ * a live agent seed: an in-flight tool call has no result yet, and removing it+ * leaves the arriving TOOL_CALL_RESULT with nothing to attach to.+ */++export function dropUnpairedAssistantToolCalls(+ messages: readonly AgUiMessage[],+) {+ const toolResultIds = new Set(+ messages.flatMap((message) =>+ message.role === "tool" ? [message.toolCallId] : [],+ ),+ );+ let changed = false;++ const sanitizedMessages = messages.map((message): AgUiMessage => {+ if (message.role !== "assistant" || !message.toolCalls?.length) {+ return message;+ }++ const pairedToolCalls = message.toolCalls.filter((toolCall) =>+ toolResultIds.has(toolCall.id),+ );++ if (pairedToolCalls.length === message.toolCalls.length) {+ return message;+ }++ changed = true;++ if (pairedToolCalls.length === 0) {+ const sanitizedMessage = { ...message };+ delete sanitizedMessage.toolCalls;+ return sanitizedMessage;+ }++ return { ...message, toolCalls: pairedToolCalls };+ });++ return changed ? sanitizedMessages : messages;+}++export function dropEmptyAssistantMessages(messages: readonly AgUiMessage[]) {+ let changed = false;+ const sanitizedMessages = messages.filter((message) => {+ if (message.role !== "assistant") {+ return true;+ }++ const hasContent =+ typeof message.content === "string" && message.content.length > 0;+ const hasToolCalls =+ message.toolCalls !== undefined && message.toolCalls.length > 0;+ const keepMessage = hasContent || hasToolCalls;++ changed = changed || !keepMessage;+ return keepMessage;+ });++ return changed ? sanitizedMessages : messages;+}diff --git a/packages/shared/src/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.tsindex 740e3bb267..05aa2a045a 100644--- a/packages/shared/src/in-app-agent/server/persistence.ts+++ b/packages/shared/src/in-app-agent/server/persistence.ts@@ -30,6 +30,10 @@ import {type AgUiEvent,type AgUiMessage,} from "../schema";+import {+ dropEmptyAssistantMessages,+ dropUnpairedAssistantToolCalls,+} from "../messages";import { assertConversationAccess } from "./access";import { compactPersistedEventDeltas } from "./eventCompaction";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "../constants";@@ -387,7 +391,7 @@ export async function appendRunEvents(params: {}export async function getConversationEvents(params: {- prisma: PrismaClient;+ prisma: PrismaClient | Prisma.TransactionClient;projectId: string;conversationId: string;}): Promise<PersistedConversationEvent[]> {@@ -496,23 +500,6 @@ export async function getConversationMessages(params: {return getMessagesFromPersistedEvents(await getConversationEvents(params));}-export async function getConversationMessagesForDisplay(params: {- prisma: PrismaClient;- projectId: string;- conversationId: string;-}) {- return getConversationMessagesForDisplayFromEvents(- await getConversationEvents(params),- );-}--export function getConversationMessagesForDisplayFromEvents(- events: readonly PersistedConversationEvent[],-) {- const messages = getMessagesFromPersistedEvents(events);- return dropEmptyAssistantMessages(dropUnpairedAssistantToolCalls(messages));-}-export async function getConversationMessagesForReplay(params: {prisma: PrismaClient;projectId: string;@@ -1120,6 +1107,12 @@ export function createConversationMessageAccumulator(if (draft) {draft.content += delta;draft.runId ??= runId;+ return upsertMessage({+ id: draft.id,+ role: "assistant",+ content: draft.content,+ ...(draft.runId ? { runId: draft.runId } : {}),+ });}return false;}@@ -1447,41 +1440,6 @@ function dropRedirectToolCallEvents(events: readonly AgUiEvent[]): AgUiEvent[] {});}-function dropUnpairedAssistantToolCalls(messages: readonly AgUiMessage[]) {- const toolResultIds = new Set(- messages.flatMap((message) =>- message.role === "tool" ? [message.toolCallId] : [],- ),- );- let changed = false;-- const sanitizedMessages = messages.map((message): AgUiMessage => {- if (message.role !== "assistant" || !message.toolCalls?.length) {- return message;- }-- const pairedToolCalls = message.toolCalls.filter((toolCall) =>- toolResultIds.has(toolCall.id),- );-- if (pairedToolCalls.length === message.toolCalls.length) {- return message;- }-- changed = true;-- if (pairedToolCalls.length === 0) {- const sanitizedMessage = { ...message };- delete sanitizedMessage.toolCalls;- return sanitizedMessage;- }-- return { ...message, toolCalls: pairedToolCalls };- });-- return changed ? sanitizedMessages : messages;-}-function dropRedirectActionToolResults(messages: readonly AgUiMessage[]) {let changed = false;const sanitizedMessages = messages.filter((message) => {@@ -1495,26 +1453,6 @@ function dropRedirectActionToolResults(messages: readonly AgUiMessage[]) {return changed ? sanitizedMessages : messages;}-function dropEmptyAssistantMessages(messages: readonly AgUiMessage[]) {- let changed = false;- const sanitizedMessages = messages.filter((message) => {- if (message.role !== "assistant") {- return true;- }-- const hasContent =- typeof message.content === "string" && message.content.length > 0;- const hasToolCalls =- message.toolCalls !== undefined && message.toolCalls.length > 0;- const keepMessage = hasContent || hasToolCalls;-- changed = changed || !keepMessage;- return keepMessage;- });-- return changed ? sanitizedMessages : messages;-}-function mergeToolCalls(existing: Extract<AgUiMessage, { role: "assistant" }>["toolCalls"],next: Extract<AgUiMessage, { role: "assistant" }>["toolCalls"],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 144b628d45..f126d37f26 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -854,6 +854,9 @@ importers:remark-gfm:specifier: ^4.0.1version: 4.0.1+ rxjs:+ specifier: 7.8.1+ version: 7.8.1sonner:specifier: ^2.0.7diff --git a/web/package.json b/web/package.jsonindex f14bb906bb..8eeef654c6 100644--- a/web/package.json+++ b/web/package.json@@ -156,6 +156,7 @@"react18-json-view": "^0.2.8-canary.6","recharts": "^3.8.0","remark-gfm": "^4.0.1",+ "rxjs": "7.8.1","sonner": "^2.0.7","streamdown": "^2.5.0","stripe": "^18.5.0",diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex 46ee0c8b48..0f96a18712 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -28,7 +28,15 @@ import {createInAppAgentConversationId,createInAppAgentRunId,} from "@langfuse/shared/in-app-agent";-import { type AgUiEvent } from "@langfuse/shared/in-app-agent";+import {+ dropEmptyAssistantMessages,+ dropUnpairedAssistantToolCalls,+ type AgUiEvent,+} from "@langfuse/shared/in-app-agent";+import {+ deserializeInAppAgentDisplayState,+ projectInAppAgentMessagesForDisplay,+} from "@/src/features/in-app-agent/lib/display";import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";import {createRun,@@ -1000,6 +1008,142 @@ describe("in-app agent persistence", () => {).resolves.toEqual(expectedReplayMessages);});+ it("preserves reasoning order when hydrating an assistant message that continues afterward", async () => {+ const { projectId, userId, caller } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });++ await appendRunEvents({+ prisma,+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events: [+ {+ type: EventType.RUN_STARTED,+ threadId: conversation.id,+ runId: run.id,+ input: {+ threadId: conversation.id,+ runId: run.id,+ state: null,+ messages: [+ {+ id: "interleaved-user",+ role: "user",+ content: "Investigate this",+ },+ ],+ tools: [],+ context: [],+ forwardedProps: {},+ },+ },+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "interleaved-assistant",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "interleaved-assistant",+ delta: "Initial answer.",+ },+ {+ type: EventType.REASONING_MESSAGE_START,+ messageId: "interleaved-reasoning",+ role: "reasoning",+ },+ {+ type: EventType.REASONING_MESSAGE_CONTENT,+ messageId: "interleaved-reasoning",+ delta: "A later thought.",+ },+ {+ type: EventType.REASONING_MESSAGE_END,+ messageId: "interleaved-reasoning",+ },+ ],+ });++ // Persist the continuation separately, as it would arrive after the+ // snapshot prefix containing the interleaved reasoning message.+ await appendRunEvents({+ prisma,+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events: [+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "interleaved-assistant",+ delta: " Final answer.",+ },+ {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "interleaved-assistant",+ },+ ],+ });++ // The wire carries canonical messages: the assistant message keeps its full+ // content so a resumed run can append to it. Interleaved ordering travels+ // separately, in the display state.+ const snapshot = await caller.getConversation({+ projectId,+ conversationId: conversation.id,+ });++ expect(snapshot.messages).toMatchObject([+ {+ id: "interleaved-user",+ role: "user",+ content: "Investigate this",+ },+ {+ id: "interleaved-assistant",+ role: "assistant",+ content: "Initial answer. Final answer.",+ },+ {+ id: "interleaved-reasoning",+ role: "reasoning",+ content: "A later thought.",+ },+ ]);+ expect(+ projectInAppAgentMessagesForDisplay(+ snapshot.messages,+ deserializeInAppAgentDisplayState(snapshot.displayState),+ ),+ ).toMatchObject([+ {+ id: "interleaved-user",+ role: "user",+ content: "Investigate this",+ },+ {+ id: "interleaved-assistant",+ role: "assistant",+ content: "Initial answer.",+ },+ {+ id: "interleaved-reasoning",+ role: "reasoning",+ content: "A later thought.",+ },+ {+ id: "display-text-interleaved-assistant-1",+ role: "assistant",+ content: " Final answer.",+ },+ ]);+ });+it("stores only compact events and skips raw adapter payloads", async () => {const { projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });@@ -1398,7 +1542,24 @@ describe("in-app agent persistence", () => {conversationId: conversation.id,});- expect(detail.messages).toEqual([+ // The snapshot stays canonical and keeps the unpaired call: a run resuming+ // from here still needs it present for its result to attach to, and a+ // pending approval renders against it.+ expect(+ detail.messages.flatMap((message) =>+ message.role === "assistant" ? (message.toolCalls ?? []) : [],+ ),+ ).toMatchObject([+ { id: "paired-tool-call" },+ { id: "unapproved-tool-call" },+ ]);++ // Settled transcripts prune it at render time instead.+ expect(+ dropEmptyAssistantMessages(+ dropUnpairedAssistantToolCalls(detail.messages),+ ),+ ).toEqual([{ id: "user-1", role: "user", content: "search" },{id: "assistant-1",diff --git a/web/src/__tests__/server/unit/in-app-agent-background-snapshot.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-background-snapshot.servertest.tsnew file mode 100644index 0000000000..4415872900--- /dev/null+++ b/web/src/__tests__/server/unit/in-app-agent-background-snapshot.servertest.ts@@ -0,0 +1,117 @@+import { EventType } from "@ag-ui/core";+import { describe, expect, it, vi } from "vitest";++import { InAppAgentRunStatus } from "@langfuse/shared";+import { Prisma, type PrismaClient } from "@langfuse/shared/src/db";++vi.mock("@langfuse/shared/src/server", () => ({+ ClickHouseClientManager: {+ getInstance: () => ({ closeAllConnections: vi.fn() }),+ },+ InAppAgentRunQueue: { getInstance: vi.fn() },+ QueueJobs: { InAppAgentRunJob: "in-app-agent-run" },+ logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn() },+ redis: null,+}));++import { getBackgroundConversationSnapshot } from "@/src/features/in-app-agent/server/backgroundRunService";++describe("getBackgroundConversationSnapshot", () => {+ it("does not combine a terminal run with an event cursor from before that commit", async () => {+ const projectId = "project-1";+ const conversationId = "conversation-1";+ const userId = "user-1";+ const runId = "run-1";+ const now = new Date("2026-08-04T08:00:00.000Z");+ const conversation = {+ id: conversationId,+ projectId,+ createdByUserId: userId,+ title: "Snapshot consistency",+ createdAt: now,+ updatedAt: now,+ deletedAt: null,+ };+ const eventsBeforeCommit = [+ {+ sequenceNumber: 0,+ runId,+ createdAt: now,+ event: {+ type: EventType.RUN_STARTED,+ threadId: conversationId,+ runId,+ input: {+ threadId: conversationId,+ runId,+ state: null,+ messages: [+ { id: "user-message", role: "user", content: "Investigate" },+ ],+ },+ },+ },+ ];++ const runRow = (status: InAppAgentRunStatus) => ({+ id: runId,+ status,+ errorCode: null,+ cancelRequestedAt: null,+ });+ const createReadView = (snapshotRunStatus: InAppAgentRunStatus) => ({+ inAppAgentEvent: {+ findMany: vi.fn().mockResolvedValue(eventsBeforeCommit),+ },+ inAppAgentRun: {+ findMany: vi.fn(async (args?: { orderBy?: unknown }) =>+ args?.orderBy ? [runRow(snapshotRunStatus)] : [],+ ),+ },+ });+ const rootReadView = createReadView(InAppAgentRunStatus.SUCCEEDED);+ const prisma = {+ ...rootReadView,+ inAppAgentConversation: {+ findFirst: vi.fn().mockResolvedValue(conversation),+ },+ $transaction: vi.fn(+ async (+ callback: (tx: ReturnType<typeof createReadView>) => Promise<unknown>,+ options?: { isolationLevel?: Prisma.TransactionIsolationLevel },+ ) => {+ // Independent READ COMMITTED statements can straddle the worker's+ // atomic terminal commit: events see RUNNING while runs see SUCCEEDED.+ // A repeatable snapshot must keep both reads on the earlier version.+ const hasRepeatableSnapshot =+ options?.isolationLevel ===+ Prisma.TransactionIsolationLevel.RepeatableRead ||+ options?.isolationLevel ===+ Prisma.TransactionIsolationLevel.Serializable;+ return callback(+ createReadView(+ hasRepeatableSnapshot+ ? InAppAgentRunStatus.RUNNING+ : InAppAgentRunStatus.SUCCEEDED,+ ),+ );+ },+ ),+ } as unknown as PrismaClient;++ const snapshot = await getBackgroundConversationSnapshot({+ prisma,+ projectId,+ conversationId,+ userId,+ });++ expect({+ eventCursor: snapshot.eventCursor,+ runStatus: snapshot.latestRun?.status,+ }).toEqual({+ eventCursor: 0,+ runStatus: InAppAgentRunStatus.RUNNING,+ });+ });+});diff --git a/web/src/features/in-app-agent/ARCHITECTURE.md b/web/src/features/in-app-agent/ARCHITECTURE.mdnew file mode 100644index 0000000000..4a4c6ee044--- /dev/null+++ b/web/src/features/in-app-agent/ARCHITECTURE.md@@ -0,0 +1,168 @@+# In-App Agent Architecture++Why the drawer is built the way it is, what the target shape is once background+execution replaces foreground, and which rules keep the two apart until then.++`README.md` is the operational guide: what each file owns, how a run flows, how+the sandbox and MCP authorization work. This document covers the parts you+cannot infer from any single file.++## One log, three derivations++Every message representation of a conversation is derived from one place: the+`in_app_agent_events` table, ordered by a per-conversation `sequence_number`.+Canonical, display and replay messages are not persisted independently as+additional sources of transcript truth.++| Derivation | Produced by | Consumed by | Shape | Never |+| ------------------------------ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |+| **Canonical messages** | `createConversationMessageAccumulator` (`packages/shared/.../persistence.ts`) | the `getConversation` wire, the AG-UI seed, feedback identity, title inference | complete assistant messages keyed by stable AG-UI message ids, `runId` preserved, in-flight tool calls kept | pruned or reordered before seeding a live agent |+| **Display state + projection** | `lib/display.ts` — `record*` accumulates, `projectInAppAgentMessagesForDisplay` folds | rendering only, once, in `InAppAiAgentProvider` | a sidecar describing where interleaved reasoning and tool calls belong, plus synthetic `display-text-<id>-N` segments | written back to the server, or fed to an agent |+| **Replay messages** | `getConversationMessagesForReplay` (`packages/shared/.../persistence.ts`) | model context for a resuming run | reasoning, redirect results, `runId`s and unpaired tool calls stripped | rendered, or used as a client hydration snapshot |++The three exist because they answer different questions: what happened, how it+should look, and what the model should see next. Confusing any two of them is+the failure mode this feature keeps rediscovering, so the table above is the+contract, not a description.++### The invariant: fold once++The display projection runs **exactly once, at render time, in the browser.**++This is not a style preference. The projection is lossy in a specific way: it+truncates an assistant message at its first interleaved block and moves the+continuation into a synthetic sibling message. That is correct for rendering and+wrong for anything else. When the server also projected — the shape this feature+shipped with — the browser seeded its live AG-UI agent with the truncated+message. AG-UI appends `TEXT_MESSAGE_CONTENT` by message id, so the next delta+of a resumed run landed on the truncated seed and the continuation vanished from+the canonical transcript until the run finished and re-hydrated.++The fix was not to pick a different accessor. It was to stop folding twice. The+wire now carries canonical messages plus the display state as a sidecar, and the+one fold happens where the live path already folded.++Two consequences worth stating explicitly:++- **Pruning is presentation too.** `dropUnpairedAssistantToolCalls` and+ `dropEmptyAssistantMessages` run at render time, and only for a settled+ transcript. A live seed must keep an in-flight tool call, otherwise the+ `TOOL_CALL_RESULT` that arrives for it has nothing to attach to and AG-UI+ appends an orphan `tool` message the drawer silently discards.+- **The sidecar is derived, never authoritative.** If it were lost the transcript+ would still be correct, just flatter. `deserializeInAppAgentDisplayState`+ therefore falls back to an empty state rather than throwing.++## Where code lives++`packages/shared` is for what web **and** worker both need. Web-only logic stays+in web even when it executes on a server.++The worker runs agents; it never renders. So the event log, canonical+accumulation, replay, the run lifecycle and watch framing are shared, while+display recording and projection live in `web/src/features/in-app-agent/lib/`+and are imported by both the browser and the web server that builds snapshots.+Shared persistence knows nothing about rendering.++The two message-pruning helpers are the deliberate exception: they prune+`AgUiMessage` shape rather than describe presentation, and replay needs them+from the worker, so they sit in `packages/shared/src/in-app-agent/messages.ts`+and are used by both replay sanitization and render-time settling.++## Current state: two execution paths++```mermaid+flowchart LR+ subgraph Browser+ P["InAppAiAgentProvider"]+ F["HttpAgent (foreground)"]+ S["BackgroundExecutionSessionController"]+ R["project → smooth → drawer"]+ end+ subgraph WebServer["web server"]+ H["handler.ts (streaming route)"]+ RT["router.ts / backgroundRunService.ts"]+ end+ subgraph Shared["packages/shared"]+ L[("in_app_agent_events")]+ A["agent runtime"]+ end+ W["worker: executeInAppAgentRun"]++ P --> F+ F -->|"SSE, request-scoped"| H+ H --> A+ H --> L++ P --> S+ S -->|"tRPC startRun"| RT+ RT -->|"enqueue"| W+ W --> A+ W --> L+ S -->|"snapshot + SSE tail above cursor"| RT+ RT --> L++ P --> R+ S -.->|"canonical + displayState"| R+ F -.->|"canonical + displayState"| R+```++Both paths share the agent runtime, persistence, tools, approvals and the entire+render tree. What is genuinely forked is the run driver (an in-request stream+versus a queued worker run), approval resume (request continuation versus a+continuation run), and the client state machine.++Foreground's run cannot outlive the browser session. Background's can: closing+the drawer detaches observation without cancelling the run, and reopening+hydrates one snapshot and resumes the tail above the persisted cursor.++## Target state: background only++```mermaid+flowchart LR+ subgraph Browser+ S["BackgroundExecutionSessionController"]+ R["project → smooth → drawer"]+ end+ RT["web server: snapshot + watch"]+ L[("in_app_agent_events")]+ W["worker: executeInAppAgentRun"]++ S -->|"startRun"| RT+ RT -->|"enqueue"| W+ W --> L+ S -->|"1. snapshot: canonical + displayState @ cursor"| RT+ S -->|"2. SSE tail, cursor-exclusive"| RT+ RT --> L+ S --> R+```++Getting there is a deletion, not a redesign: remove `HttpAgent` wiring, the+foreground state in the provider (`foregroundMessages`, its display state, its+seeding), and the streaming route. The contract the remaining path uses is+already the final one.++### The quarantine rule++Until foreground is deleted, do not introduce an abstraction whose purpose is+to normalize the foreground and background run drivers or client state+machines. Pure transcript contracts and presentation code may remain shared.++The temptation is to write an adapter that makes them interchangeable. That+adapter would be the most complex code in the feature and would have to be+untangled later rather than deleted.++Concretely: foreground-only members are marked delete-with-foreground, shared+code between the paths must be independent of how the server executes a run+(the projection, the drawer, the approval wire contract), and behavior tests+cover each path at its own seam.++## Change rules++- Adding a representation means adding a row to the table above, with its+ producer, its consumers, and where it must never appear. If you cannot fill+ those in, you are probably reaching for one that already exists.+- Do not project, prune or reorder messages on the way to a live agent.+- Keep the snapshot and the tail on one cursor.+- Read `README.md` for AG-UI event semantics before changing anything that+ touches ordering, compaction or persistence.diff --git a/web/src/features/in-app-agent/README.md b/web/src/features/in-app-agent/README.mdindex e18d1d4444..032a7dad26 100644--- a/web/src/features/in-app-agent/README.md+++ b/web/src/features/in-app-agent/README.md@@ -1,14 +1,30 @@# In-App Agent-The in-app agent is Langfuse's project-scoped foreground assistant inside the authenticated product UI.+The 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.++`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+foreground is removed, and the rules that keep the two execution paths apart.+Read it before changing how messages are represented or where logic lives.## Core Model-AG-UI is the durable contract for live streaming, persistence, replay, and rendering.+AG-UI events are the durable transcript vocabulary. Langfuse-owned protocols+coordinate persistence, watching, run lifecycle, approvals, and display+projection around those events.The browser owns interaction state and submits intent. The server owns authorization, run/message IDs, request sanitization, MCP credentials, runtime configuration, tool access, persistence, and replay.-Runs are foreground-only. A conversation can have one active run; stale unfinished runs are closed before a new run starts.+A conversation can have one active run. The browser uses one execution mode for+a 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+ persisted transcript/cursor snapshot, and observes its tail. Closing the+ drawer detaches observation without cancelling the server run.## Major Files@@ -17,7 +33,12 @@ Runs are foreground-only. A conversation can have one active run; stale unfinish- `server/agent.ts`: Mastra/Bedrock/MCP runtime setup, custom tool wiring, human-in-the-loop approval gates, AG-UI event normalization, and cleanup.- `server/human-in-the-loop.ts`: interrupt parsing helpers, pending tool approval persistence, and resume approval validation/consumption.- `server/tools.ts`: custom agent tools with strict schemas and scoped, user-visible behavior.-- `server/persistence.ts`: conversations, runs, events, replay, active-run locking, and stale-run recovery.+- `server/persistence.ts`: conversations, runs, events, canonical accumulation, replay, active-run locking, and stale-run recovery. Knows nothing about rendering.+- `lib/display.ts`: display-state recording, the render-time projection, and its+ wire serialization. Web-only; used by the browser and by the web server when+ it builds a conversation snapshot.+- `server/conversationSnapshot.ts`: rebuilds canonical messages and display state+ from one read of the persisted event log.- `server/router.ts`: non-streaming tRPC routes for conversation lists, replay, and feedback.- `server/instrumentation.ts`: optional Langfuse tracing for agent runs, prompts, events, and errors.- `server/sandbox/config.ts`: sandbox provider selection and runtime configuration.@@ -25,7 +46,15 @@ Runs are foreground-only. A conversation can have one active run; stale unfinish- `server/sandbox/providers/*`: provider adapters for local Docker and Lambda MicroVM sandboxes.- `server/sandbox/types.ts`: runtime-neutral sandbox interface used by tools/agent.- `constants.ts`: stable names shared across prompts, tools, persistence, and rendering.-- `components/*`: client controller and prop-driven render components.+- `components/InAppAiAgentProvider.tsx`: mode selection, foreground transport,+ query integration, and the React bridge to the background session.+- `components/ControlledInAppAgentWindow.tsx` and+ `components/InAppAgentWindow.tsx`: prop-driven rendering and the explicit+ foreground/background execution controls.+- `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.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.@@ -39,6 +68,13 @@ flowchart TBWindow --> Message["InAppAgentMessage.tsx\nmessage rendering"]Provider -->|AG-UI HttpAgent + SSE| Handler["server/handler.ts\nserver route for agent runs"]+ Provider -->|useSyncExternalStore| Session["backgroundExecutionSession.ts\nbackground state + actions"]+ Session --> BackgroundClient["backgroundAgentClient.ts\nstart + watch adapter"]+ Display["lib/display.ts\ndisplay state + projection"] -.-> Provider+ Display -.-> Session+ Display -.-> Snapshot["server/conversationSnapshot.ts\ncanonical + display state"]+ Router --> Snapshot+ BackgroundClient -->|start/watch| RouterProvider -->|tRPC| Router["server/router.ts\ntRPC routes (non-streaming)"]Schema["schema.ts\nshared AG-UI contract"] -.-> Provider@@ -60,7 +96,9 @@ flowchart TBRouter --> Persistence```-## Run Lifecycle+## Run Lifecycles++### Foreground1. Browser sends the latest message, conversation state, and screen context through `HttpAgent`.2. `server/handler.ts` validates the request and creates a server-owned run.@@ -74,6 +112,65 @@ flowchart TB10. `server/persistence.ts` stores compacted events and reconstructs replay messages.11. `InAppAiAgentProvider.tsx` renders live AG-UI state and hydrates selected conversations through `server/router.ts`.+### Background++1. The provider selects the background client only when the local opt-in is+ enabled and starts the durable run through `startRun`.+2. `BackgroundExecutionSessionController` installs the persisted canonical+ messages, the display state, and the cursor before attaching the watch+ stream. The seed is never projected or pruned; see `ARCHITECTURE.md`.+3. The session snapshot is the sole owner of background messages, approvals,+ current run, cancellation, and attachment state. React subscribes with+ `useSyncExternalStore`; it does not mirror those facts into component state.+4. Approval and cancellation promises represent the durable mutation. A later+ hydration/watch failure is attachment state and cannot undo an accepted+ command or resurrect an approval.+5. Closing the drawer calls `detach()`, which stops browser observation only.+ Reopening hydrates and resumes from the persisted cursor.++## Client State Ownership++- React Query owns conversation-list and persisted conversation query state.+- The foreground provider state owns the live `HttpAgent` transcript,+ approvals, and request lifecycle.+- `BackgroundExecutionSessionController` owns the equivalent background facts;+ persisted query data only seeds the coherent bootstrap view consumed by the+ same external-store hook before a controller exists. Rendering never unions+ query state with a live session snapshot.+- `InAppAgentWindow` receives one discriminated execution-UI value, so+ foreground copy cannot be combined with background Stop state.+- Display pacing remains in `useSmoothStreamingMessages`; canonical AG-UI+ messages are never rewritten for animation.+- Messages and their display state always come from the same source. The+ provider selects both together, so a live transcript can never be folded+ against persisted display state or the reverse.++The provider is still a large integration controller. Do not add another+background state mirror or a generic long-lived foreground/background adapter;+the foreground branch is scheduled for deletion after background rollout.++## Consumers And Stability Boundaries++`InAppAgentWindowHost` and the drawer shell mount the provider-backed controlled+window. Presentational components must remain context-free and consume explicit+props.++Streaming publications and background session snapshots are high-frequency.+Keep their subscription boundary narrow, derive status/notice values during+render, and preserve stable message references between session publications.++Stop intentionally emits no new analytics event during the internal rollout:+the existing run lifecycle is sufficient to diagnose correctness, and there is+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.+## Sandbox Runtime`server/sandbox/service.ts` gives the agent a conversation-scoped sandbox interface with `read`, `write`, and `edit` plus a separate turn-end callback. It reuses an existing provider session when the stored provider/session/TTL still match, otherwise it boots a fresh session and persists the new state on the conversation.@@ -137,3 +234,7 @@ Sandbox tools are separate from MCP authorization. When a sandbox provider is en- Keep persisted schemas backward-compatible unless there is an explicit migration.- Keep sandbox conversation state backward-compatible unless there is an explicit migration or cleanup plan.- Keep presentational components prop-driven; connect tRPC, streaming, and persistence at provider/router/handler boundaries.+- Before changing client state ownership or adding effects, read the+ frontend-large-feature architecture and refactor-react-effects skills.+- Protect both the default foreground contract and the background session+ contract with behavior tests at their public seams.diff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsxindex c8edab0f13..803eefa276 100644--- a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx@@ -3,7 +3,10 @@import { useMemo } from "react";import { useRouter } from "next/router";import { InAppAgentWindow } from "./InAppAgentWindow";-import type { InAppAgentWindowConversation } from "./InAppAgentWindow";+import type {+ InAppAgentWindowConversation,+ InAppAgentWindowExecutionUi,+} from "./InAppAgentWindow";import { useInAppAiAgent } from "./InAppAiAgentProvider";import { useSmoothStreamingMessages } from "./useSmoothStreamingMessages";import { getDrawerMessages } from "./utils/utils";@@ -12,10 +15,42 @@ import {getInAppAgentFocusedQuickActions,getInAppAgentQuickActionContext,} from "@/src/features/in-app-agent/quickActions";+import {+ getBackgroundRunFailureMessage,+ isCancellableBackgroundRun,+ type BackgroundExecutionRunView,+} from "@/src/features/in-app-agent/lib/backgroundExecutionSession";+import { InAppAgentRunStatus } from "@langfuse/shared";const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE ="Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";+function getBackgroundRunNotice(+ run: BackgroundExecutionRunView | null,+): string | null {+ if (!run) {+ return null;+ }++ if (isCancellableBackgroundRun(run.status) && run.cancelRequested) {+ return "Stopping the run…";+ }++ if (run.status === InAppAgentRunStatus.QUEUED) {+ return "Waiting for a worker to pick this up. You can close this; the run continues in the background.";+ }++ if (run.status === InAppAgentRunStatus.RUNNING) {+ return "You can close this; the run continues in the background.";+ }++ if (run.status === InAppAgentRunStatus.FAILED) {+ return getBackgroundRunFailureMessage(run.errorCode ?? null);+ }++ return null;+}+type ControlledInAppAgentWindowBaseProps = {isHeaderDragHandleEnabled?: boolean;isExpanded: boolean;@@ -46,6 +81,7 @@ export function ControlledInAppAgentWindow(isLoadingMoreConversations,isRunning,isSelectedConversationHydrating,+ execution,isSubmitting,invalidateConversations,loadMoreConversations,@@ -60,7 +96,12 @@ export function ControlledInAppAgentWindow(submit,submitFeedback,} = useInAppAiAgent();+ const isCancellingRun =+ execution.type === "background" && execution.isCancelling;+ const shouldFlushCancelledRun =+ execution.type === "background" && execution.run?.cancelRequested === true;const {+ finishAnimation,isAnimating,messages: displayedMessages,pendingToolApprovals: displayedPendingToolApprovals,@@ -69,8 +110,31 @@ export function ControlledInAppAgentWindow(messages,liveMessageVersion,pendingToolApprovals,- shouldFlush: error !== null,+ // Keep the cancelled run flushed through its terminal publication. The+ // final events and terminal status can arrive in one React batch, after+ // `isCancelling` has cleared, and must not restart the reveal after Stop.+ shouldFlush: error !== null || isCancellingRun || shouldFlushCancelledRun,});+ const windowExecutionUi: InAppAgentWindowExecutionUi =+ execution.type === "foreground"+ ? execution+ : {+ type: "background",+ notice: getBackgroundRunNotice(execution.run),+ stop:+ execution.run && isCancellableBackgroundRun(execution.run.status)+ ? {+ status: execution.isCancelling ? "stopping" : "available",+ onStop: () => {+ finishAnimation();+ execution.cancel();+ },+ }+ : null,+ };+ // Only a read-only conversation disables the composer outright. An assistant+ // turn -- including one paused on an approval -- blocks submission but leaves+ // the draft editable.const isConversationInteractionDisabled =selectedConversationIsWriteLocked || isSelectedConversationHydrating;const isAssistantTurnInProgress =@@ -147,6 +211,7 @@ export function ControlledInAppAgentWindow(}}onExpandedChange={props.onExpandedChange}onSubmit={submit}+ executionUi={windowExecutionUi}onApproveToolCall={approveToolCall}onRejectToolCall={rejectToolCall}onSubmitFeedback={submitFeedback}diff --git a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsxnew file mode 100644index 0000000000..5813acd31f--- /dev/null+++ b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx@@ -0,0 +1,811 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { HttpAgent, type AgentSubscriber } from "@ag-ui/client";+import { EventType } from "@ag-ui/core";+import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "@langfuse/shared";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";++import { TooltipProvider } from "@/src/components/ui/tooltip";+import { ControlledInAppAgentWindow } from "./ControlledInAppAgentWindow";+import { InAppAiAgentProvider } from "./InAppAiAgentProvider";+import styles from "./InAppAgentWindow.module.css";++const providerMocks = vi.hoisted(() => {+ const startRun = vi.fn();+ const cancelRun = vi.fn();+ const decideToolApproval = vi.fn();++ return {+ backgroundExecutionEnabled: false,+ capture: vi.fn(),+ startRun,+ cancelRun,+ decideToolApproval,+ mutations: {+ startRun: { mutateAsync: startRun },+ cancelRun: { isPending: false, mutateAsync: cancelRun },+ decideToolApproval: { mutateAsync: decideToolApproval },+ },+ getConversation: vi.fn(),+ listQuery: {+ data: { pages: [{ conversations: [] }] },+ error: null,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ },+ conversationQuery: {+ data: undefined as+ | undefined+ | {+ conversation: { id: string; isWriteLocked: boolean };+ messages: AgUiMessage[];+ eventCursor: number;+ latestRun: {+ id: string;+ status: InAppAgentRunStatus;+ errorCode: string | null;+ cancelRequested: boolean;+ } | null;+ displayState?: unknown;+ pendingToolApprovals: Array<{+ runId: string;+ approvalRequest: {+ type: "tool_approval_request";+ toolCallId: string;+ toolName: string;+ runId: string;+ };+ }>;+ },+ error: null,+ isLoading: false,+ },+ utils: {+ inAppAgent: {+ getConversation: {+ fetch: vi.fn(),+ invalidate: vi.fn(),+ },+ listConversations: {+ invalidate: vi.fn(),+ },+ },+ },+ };+});++vi.mock("next/router", () => ({+ useRouter: () => ({+ asPath: "/project/project-1/traces",+ query: { projectId: "project-1" },+ }),+}));++vi.mock("next-auth/react", () => ({+ useSession: () => ({ data: { user: { name: "Test User" } } }),+}));++vi.mock("@/src/features/entitlements/hooks", () => ({+ useHasEntitlement: () => true,+}));++vi.mock("@/src/features/projects/hooks", () => ({+ useQueryProjectOrOrganization: () => ({+ organization: { aiFeaturesEnabled: true },+ }),+}));++vi.mock("@/src/features/in-app-agent/lib/backgroundExecutionFlag", () => ({+ useInAppAgentBackgroundExecutionEnabled: () =>+ providerMocks.backgroundExecutionEnabled,+}));++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => providerMocks.capture,+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ useUtils: () => providerMocks.utils,+ inAppAgent: {+ listConversations: {+ useInfiniteQuery: () => providerMocks.listQuery,+ },+ getConversation: {+ useQuery: () => providerMocks.conversationQuery,+ },+ deleteConversation: {+ useMutation: () => ({ mutateAsync: vi.fn() }),+ },+ submitFeedback: {+ useMutation: () => ({ mutateAsync: vi.fn() }),+ },+ startRun: {+ useMutation: () => providerMocks.mutations.startRun,+ },+ cancelRun: {+ useMutation: () => providerMocks.mutations.cancelRun,+ },+ decideToolApproval: {+ useMutation: () => providerMocks.mutations.decideToolApproval,+ },+ },+ },+}));++Element.prototype.scrollTo = vi.fn();++function sseFrame(frame: unknown): string {+ return `data: ${JSON.stringify(frame)}\n\n`;+}++function renderExecutionUi() {+ return render(+ <TooltipProvider>+ <InAppAiAgentProvider defaultOpen>+ <ControlledInAppAgentWindow+ isExpanded={false}+ onDeleteConversation={vi.fn()}+ onExpandedChange={vi.fn()}+ showCloseButton={false}+ />+ </InAppAiAgentProvider>+ </TooltipProvider>,+ );+}++function queryActivityIndicator() {+ return document.querySelector(`.${styles.loadingGradient}`);+}++describe("in-app agent execution", () => {+ beforeEach(() => {+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })),+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ providerMocks.backgroundExecutionEnabled = false;+ providerMocks.conversationQuery.data = undefined;+ window.sessionStorage.clear();+ });++ it("keeps foreground submission and approval working when background execution is disabled", async () => {+ let subscriber: AgentSubscriber | undefined;+ const runAgent = vi+ .spyOn(HttpAgent.prototype, "runAgent")+ .mockResolvedValue({ result: undefined, newMessages: [] });+ const abortRun = vi.spyOn(HttpAgent.prototype, "abortRun");+ vi.spyOn(HttpAgent.prototype, "subscribe").mockImplementation(+ (nextSubscriber: AgentSubscriber) => {+ subscriber = nextSubscriber;+ return { unsubscribe: vi.fn() };+ },+ );++ const { unmount } = renderExecutionUi();++ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /stop run/i }),+ ).not.toBeInTheDocument();++ fireEvent.change(+ screen.getByRole("textbox", { name: "Message the assistant" }),+ { target: { value: "Investigate this project" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));++ await waitFor(() => {+ expect(runAgent).toHaveBeenCalledOnce();+ });+ expect(providerMocks.startRun).not.toHaveBeenCalled();++ await act(async () => {+ await subscriber?.onCustomEvent?.({+ event: {+ name: "on_interrupt",+ value: {+ type: "mastra_suspend",+ toolCallId: "tool-call-1",+ toolName: "dangerousTool",+ runId: "run-1",+ },+ },+ } as never);+ });++ fireEvent.click(+ await screen.findByRole("button", {+ name: "Confirm",+ }),+ );+ await waitFor(() => {+ expect(runAgent).toHaveBeenCalledTimes(2);+ });++ unmount();+ expect(abortRun).toHaveBeenCalled();+ });++ it("renders persisted background messages and approval actions in the drawer", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ providerMocks.conversationQuery.data = {+ conversation: {+ id: "conversation-1",+ isWriteLocked: false,+ },+ messages: [+ {+ id: "persisted-user",+ role: "user",+ content: "Create the prompt",+ },+ {+ id: "persisted-assistant",+ role: "assistant",+ content: "I need approval.",+ },+ ],+ eventCursor: 12,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [+ {+ runId: "run-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_createTextPrompt",+ runId: "run-1",+ },+ },+ ],+ };+ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );++ renderExecutionUi();++ expect(await screen.findByText("Create the prompt")).toBeInTheDocument();+ expect(screen.getByText("I need approval.")).toBeInTheDocument();+ expect(+ screen.getByRole("button", {+ name: "Confirm",+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", {+ name: "Reject",+ }),+ ).toBeInTheDocument();+ });++ it("keeps a hydrated in-flight tool call visibly running", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ providerMocks.conversationQuery.data = {+ conversation: {+ id: "conversation-1",+ isWriteLocked: false,+ },+ messages: [+ {+ id: "persisted-user",+ role: "user",+ content: "Inspect the traces",+ },+ {+ id: "persisted-assistant",+ role: "assistant",+ content: "",+ runId: "run-1",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "list_traces",+ arguments: "{}",+ },+ },+ ],+ },+ ],+ eventCursor: 12,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [],+ };+ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );+ vi.spyOn(globalThis, "fetch").mockImplementation(+ () => new Promise<Response>(() => undefined),+ );++ renderExecutionUi();++ expect(await screen.findByText("Calling 1 tool")).toBeInTheDocument();+ });++ it("keeps approval cancellation visibly stopping until hydration settles", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ providerMocks.conversationQuery.data = {+ conversation: {+ id: "conversation-1",+ isWriteLocked: false,+ },+ messages: [+ {+ id: "persisted-user",+ role: "user",+ content: "Create the prompt",+ },+ ],+ eventCursor: 12,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [+ {+ runId: "run-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_createTextPrompt",+ runId: "run-1",+ },+ },+ ],+ };+ providerMocks.cancelRun.mockResolvedValueOnce({+ cancelledImmediately: true,+ status: InAppAgentRunStatus.CANCELLED,+ });+ providerMocks.utils.inAppAgent.getConversation.fetch.mockImplementationOnce(+ () => new Promise(() => undefined),+ );+ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );++ renderExecutionUi();+ fireEvent.click(await screen.findByRole("button", { name: "Stop run" }));++ await waitFor(() => {+ expect(+ providerMocks.utils.inAppAgent.getConversation.fetch,+ ).toHaveBeenCalledOnce();+ });+ expect(screen.getByRole("button", { name: "Stopping run" })).toBeDisabled();+ expect(screen.getByRole("status")).toHaveTextContent("Stopping the run…");+ });++ it("does not observe a cached active run while the assistant is closed", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ const runningSnapshot = {+ conversation: { id: "conversation-1", isWriteLocked: false },+ messages: [],+ eventCursor: 5,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [],+ } satisfies NonNullable<typeof providerMocks.conversationQuery.data>;+ providerMocks.conversationQuery.data = runningSnapshot;+ providerMocks.utils.inAppAgent.getConversation.fetch.mockResolvedValue(+ runningSnapshot,+ );+ const watchFetch = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValue(new Response(sseFrame({ type: "done" })));+ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );++ render(+ <InAppAiAgentProvider defaultOpen={false}>+ <div />+ </InAppAiAgentProvider>,+ );+ await act(async () => undefined);++ expect(watchFetch).not.toHaveBeenCalled();+ });++ it("settles the drawer without restarting its activity state after Stop", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })),+ );++ const initialText = "I found the affected traces.";+ const finalText = "The remaining analysis was cancelled before completion.";+ const runningSnapshot = {+ conversation: { id: "conversation-1", isWriteLocked: false },+ messages: [+ { id: "persisted-user", role: "user", content: "Investigate this" },+ {+ id: "persisted-assistant",+ role: "assistant",+ content: initialText,+ },+ ] satisfies AgUiMessage[],+ eventCursor: 5,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [],+ };+ const cancellingSnapshot = {+ ...runningSnapshot,+ latestRun: { ...runningSnapshot.latestRun, cancelRequested: true },+ };+ const cancelledSnapshot = {+ ...runningSnapshot,+ messages: [+ ...runningSnapshot.messages,+ { id: "cancelled-assistant", role: "assistant", content: finalText },+ ] satisfies AgUiMessage[],+ eventCursor: 10,+ latestRun: {+ ...runningSnapshot.latestRun,+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ cancelRequested: true,+ },+ };++ providerMocks.conversationQuery.data = runningSnapshot;+ providerMocks.cancelRun.mockResolvedValue({+ cancelledImmediately: false,+ status: InAppAgentRunStatus.RUNNING,+ });+ providerMocks.utils.inAppAgent.getConversation.fetch+ .mockResolvedValueOnce(runningSnapshot)+ .mockResolvedValueOnce(cancellingSnapshot)+ .mockResolvedValueOnce(cancelledSnapshot);++ let resolveTerminalWatch: (response: Response) => void = () => undefined;+ const watchFetch = vi+ .spyOn(globalThis, "fetch")+ .mockImplementationOnce(+ (_input, init) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener(+ "abort",+ () => {+ reject(new DOMException("Aborted", "AbortError"));+ },+ { once: true },+ );+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise<Response>((resolve) => {+ resolveTerminalWatch = resolve;+ }),+ );+ const terminalWatchResponse = new Response(+ [+ sseFrame({+ type: "event",+ sequenceNumber: 6,+ event: {+ type: EventType.RUN_STARTED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 7,+ event: {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "cancelled-assistant",+ role: "assistant",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 8,+ event: {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "cancelled-assistant",+ delta: finalText,+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 9,+ event: {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "cancelled-assistant",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 10,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "status",+ runId: "run-1",+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ cancelRequested: true,+ }),+ sseFrame({ type: "done" }),+ ].join(""),+ );++ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );+ renderExecutionUi();++ await waitFor(() => {+ expect(watchFetch).toHaveBeenCalledOnce();+ });++ fireEvent.click(+ screen.getByRole("button", {+ name: "Stop run",+ }),+ );++ await waitFor(() => {+ expect(watchFetch).toHaveBeenCalledTimes(2);+ });+ await act(async () => {+ resolveTerminalWatch(terminalWatchResponse);+ });++ await waitFor(() => {+ expect(+ screen.queryByRole("button", { name: /stop(?:ping)? run/i }),+ ).not.toBeInTheDocument();+ });+ expect(screen.getByText(finalText)).toBeVisible();+ expect(+ screen.getByText("The assistant is aware of this trace view."),+ ).toBeVisible();+ expect(screen.getByRole("button", { name: "Good response" })).toBeVisible();+ });++ it("settles a newly submitted run as soon as Stop receives a terminal status", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => ({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })),+ );++ const finalText = "The investigation was cancelled before it completed.";+ providerMocks.conversationQuery.data = {+ conversation: { id: "conversation-1", isWriteLocked: false },+ messages: [],+ eventCursor: -1,+ latestRun: null,+ pendingToolApprovals: [],+ };+ const cancellingSnapshot = {+ conversation: { id: "conversation-1", isWriteLocked: false },+ messages: [+ { id: "persisted-user", role: "user", content: "Investigate this" },+ ] satisfies AgUiMessage[],+ eventCursor: -1,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: true,+ },+ pendingToolApprovals: [],+ };+ const cancelledSnapshot = {+ ...cancellingSnapshot,+ messages: [+ ...cancellingSnapshot.messages,+ { id: "persisted-assistant", role: "assistant", content: finalText },+ ] satisfies AgUiMessage[],+ eventCursor: 4,+ latestRun: {+ ...cancellingSnapshot.latestRun,+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ },+ };+ providerMocks.startRun+ .mockResolvedValueOnce({ runId: "run-1" })+ .mockResolvedValueOnce({ runId: "run-2" });+ providerMocks.cancelRun.mockResolvedValue({+ cancelledImmediately: false,+ status: InAppAgentRunStatus.RUNNING,+ });+ providerMocks.utils.inAppAgent.getConversation.fetch+ .mockResolvedValueOnce(cancellingSnapshot)+ .mockResolvedValueOnce(cancelledSnapshot);++ const encoder = new TextEncoder();+ let watchRequestCount = 0;+ vi.spyOn(globalThis, "fetch").mockImplementation((_input, init) => {+ watchRequestCount += 1;+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ watchRequestCount === 1+ ? sseFrame({+ type: "status",+ runId: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ })+ : watchRequestCount === 2+ ? [+ sseFrame({+ type: "event",+ sequenceNumber: 0,+ event: {+ type: EventType.RUN_STARTED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 1,+ event: {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "persisted-assistant",+ role: "assistant",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 2,+ event: {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "persisted-assistant",+ delta: finalText,+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 3,+ event: {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "persisted-assistant",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 4,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "status",+ runId: "run-1",+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ cancelRequested: true,+ }),+ ].join("")+ : sseFrame({+ type: "status",+ runId: "run-2",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ }),+ ),+ );+ init?.signal?.addEventListener(+ "abort",+ () => {+ controller.close();+ },+ { once: true },+ );+ },+ });++ return Promise.resolve(new Response(stream));+ });++ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );+ renderExecutionUi();++ fireEvent.change(+ screen.getByRole("textbox", { name: "Message the assistant" }),+ { target: { value: "Investigate this" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));++ const stopButton = await screen.findByRole("button", { name: "Stop run" });+ expect(queryActivityIndicator()).toBeInTheDocument();+ fireEvent.click(stopButton);++ await waitFor(() => {+ expect(watchRequestCount).toBe(2);+ });+ await waitFor(() => {+ expect(+ screen.queryByRole("button", { name: /stop(?:ping)? run/i }),+ ).not.toBeInTheDocument();+ });+ expect(screen.getByText(finalText)).toBeVisible();+ expect(queryActivityIndicator()).not.toBeInTheDocument();++ const textbox = screen.getByRole("textbox", {+ name: "Message the assistant",+ });+ fireEvent.change(textbox, { target: { value: "Start a new analysis" } });+ const sendButton = screen.getByRole("button", { name: "Send message" });+ expect(sendButton).toBeEnabled();+ fireEvent.click(sendButton);+ await waitFor(() => {+ expect(providerMocks.startRun).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsxindex fe94ec86e2..4b49460549 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx@@ -1,5 +1,6 @@import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { ScanSearch } from "lucide-react";+import { InAppAgentRunStatus } from "@langfuse/shared";import { TooltipProvider } from "@/src/components/ui/tooltip";import {InAppAgentWindow,@@ -17,6 +18,19 @@ const controlledAgent = vi.hoisted(() => ({isRunning: true,isSelectedConversationHydrating: false,isSubmitting: false,+ execution: { type: "foreground" } as+ | { type: "foreground" }+ | {+ type: "background";+ run: {+ id: string;+ status: InAppAgentRunStatus;+ errorCode: string | null;+ cancelRequested: boolean;+ } | null;+ isCancelling: boolean;+ cancel: () => void;+ },invalidateConversations: vi.fn(),liveMessageVersion: 0,loadMoreConversations: vi.fn(),@@ -43,8 +57,11 @@ vi.mock("./InAppAiAgentProvider", () => ({useInAppAiAgent: () => controlledAgent.value,}));+const finishAnimation = vi.fn();+vi.mock("./useSmoothStreamingMessages", () => ({useSmoothStreamingMessages: () => ({+ finishAnimation,isAnimating: false,messages: [],pendingToolApprovals: [],@@ -63,6 +80,7 @@ function windowElement(const props: InAppAgentWindowProps = {conversations: [],error: null,+ executionUi: { type: "foreground" },hasMoreConversations: false,isAssistantTurnInProgress: false,isExpanded: false,@@ -106,6 +124,10 @@ describe("InAppAgentWindow quick actions", () => {const onSubmit = vi.fn().mockResolvedValue(true);const { rerender } = render(windowElement({ onSubmit }));+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /stop run/i }),+ ).not.toBeInTheDocument();expect(screen.getAllByRole("tab").map((tab) => tab.textContent)).toEqual(["Observability","Prompts",@@ -275,6 +297,43 @@ describe("ControlledInAppAgentWindow composer", () => {});});+describe("ControlledInAppAgentWindow stop", () => {+ it("flushes the paced reveal and cancels the run from one Stop click", () => {+ const cancel = vi.fn();+ controlledAgent.value.isRunning = true;+ controlledAgent.value.pendingToolApprovals = [];+ controlledAgent.value.execution = {+ type: "background",+ run: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ },+ isCancelling: false,+ cancel,+ };++ render(+ <TooltipProvider>+ <ControlledInAppAgentWindow+ isExpanded={false}+ onClose={vi.fn()}+ onDeleteConversation={vi.fn()}+ onExpandedChange={vi.fn()}+ />+ </TooltipProvider>,+ );++ fireEvent.click(screen.getByRole("button", { name: "Stop run" }));++ // Cancelling alone only stops future frames. Without the flush the already+ // buffered block keeps typing out, which reads as "stop did nothing".+ expect(cancel).toHaveBeenCalledOnce();+ expect(finishAnimation).toHaveBeenCalledOnce();+ });+});+describe("InAppAgentWindow focus", () => {it("refocuses the composer when an active turn completes", () => {const { rerender } = render(diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsxindex 2941b146b7..793219dc5d 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx@@ -588,6 +588,7 @@ const meta = preview.meta({],args: {error: null,+ executionUi: { type: "foreground" as const },isExpanded: false,isConversationInteractionDisabled: false,conversations,@@ -993,6 +994,120 @@ export const Error = meta.story({},});+export const BackgroundRun = meta.story({+ args: {+ isAssistantTurnInProgress: true,+ executionUi: {+ type: "background",+ notice: "You can close this; the run continues in the background.",+ stop: { status: "available", onStop: fn() },+ },+ messages: [+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Summarize recent ingestion errors.",+ },+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: { type: "loading" },+ },+ ],+ },+});++export const BackgroundRunStops = meta.story({+ args: {+ isAssistantTurnInProgress: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Summarize recent ingestion errors.",+ },+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: { type: "loading" },+ },+ ],+ },+ render: function Render(args) {+ const [phase, setPhase] = useState<"running" | "stopping" | "settled">(+ "running",+ );+ const isSettled = phase === "settled";++ useEffect(() => {+ if (phase !== "stopping") {+ return;+ }++ const timeoutId = window.setTimeout(() => {+ setPhase("settled");+ }, 1_500);++ return () => {+ window.clearTimeout(timeoutId);+ };+ }, [phase]);++ return (+ <StatefulInAppAgentWindow+ {...args}+ isAssistantTurnInProgress={!isSettled}+ messages={+ isSettled+ ? [+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Summarize recent ingestion errors.",+ },+ },+ {+ id: "assistant-1",+ runId: "run-1",+ role: "assistant",+ content: {+ type: "text",+ text: "The run stopped before the investigation completed.",+ },+ },+ ]+ : args.messages+ }+ executionUi={+ isSettled+ ? { type: "background", notice: null, stop: null }+ : {+ type: "background",+ notice:+ phase === "stopping"+ ? "Stopping the run…"+ : "You can close this; the run continues in the background.",+ stop: {+ status: phase === "stopping" ? "stopping" : "available",+ onStop: () => {+ setPhase("stopping");+ },+ },+ }+ }+ />+ );+ },+});+export const RateLimited = meta.story({name: "(Test) Rate Limited",args: {diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsxindex 780a4e6f9b..0af04d2e19 100644--- a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx@@ -17,6 +17,7 @@ import {Minus,Plus,SendHorizontal,+ Square,Trash2,} from "lucide-react";import { Button } from "@/src/components/ui/button";@@ -255,10 +256,22 @@ type InAppAgentWindowCloseButtonProps =onClose: () => void;};+export type InAppAgentWindowExecutionUi =+ | { type: "foreground" }+ | {+ type: "background";+ notice: string | null;+ stop: {+ status: "available" | "stopping";+ onStop: () => void;+ } | null;+ };+export type InAppAgentWindowProps = {conversations: InAppAgentWindowConversation[];disablePendingToolApprovalActions?: boolean;error: InAppAgentError | null;+ executionUi: InAppAgentWindowExecutionUi;hasMoreConversations: boolean;isAssistantTurnInProgress: boolean;isHeaderDragHandleEnabled?: boolean;@@ -360,6 +373,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {conversations,disablePendingToolApprovalActions = false,error,+ executionUi,hasMoreConversations,isAssistantTurnInProgress,isHeaderDragHandleEnabled = false,@@ -393,6 +407,12 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {const isComposerDisabled = isConversationInteractionDisabled;const isSubmitDisabled =isComposerDisabled || isRateLimited || isAssistantTurnInProgress;+ const backgroundNotice =+ executionUi.type === "background" ? executionUi.notice : null;+ const executionStop =+ executionUi.type === "background" ? executionUi.stop : null;+ const canStopRun = executionStop !== null && isAssistantTurnInProgress;+ const isCancellingRun = executionStop?.status === "stopping";const viewportRef = useRef<HTMLDivElement>(null);const isAutoScrollAttachedRef = useRef(true);const previousScrollTopRef = useRef(0);@@ -874,6 +894,24 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {</div></div></div>+ {backgroundNotice ? (+ <div className="shrink-0 px-2 pb-2">+ <div className={cn(isExpanded && "mx-auto max-w-3xl")}>+ <p+ role="status"+ className={cn(+ "border-border bg-muted/60 text-foreground-tertiary flex w-full items-center gap-1 rounded-lg border px-2 py-1",+ isExpanded ? "text-sm" : "text-xs",+ )}+ >+ <Info aria-hidden="true" className="size-3 shrink-0" />+ <span className="min-w-0" title={backgroundNotice}>+ {backgroundNotice}+ </span>+ </p>+ </div>+ </div>+ ) : null}{error?.type === "rate_limit" && (<divclassName={cn(@@ -963,32 +1001,64 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {: "border-input max-h-40 min-h-8 px-3 py-1",)}/>- {!isExpanded && (- <Button- type="submit"- size="icon"- className="h-8 w-8 rounded-md border"- aria-label="Send message"- variant="outline"- disabled={isSubmitDisabled || !input.trim()}- >- <SendHorizontal className="h-4 w-4" />- </Button>- )}-- {isExpanded && (- <div className="flex w-full justify-end p-1">+ {!isExpanded &&+ (canStopRun ? (+ <Button+ type="button"+ size="icon"+ className="h-8 w-8 rounded-md border"+ aria-label={isCancellingRun ? "Stopping run" : "Stop run"}+ variant="outline"+ disabled={isCancellingRun}+ onClick={() => {+ executionStop?.onStop();+ }}+ >+ <Square className="h-3 w-3" />+ </Button>+ ) : (<Buttontype="submit"- className="h-8 w-fit rounded-md px-3"+ size="icon"+ className="h-8 w-8 rounded-md border"aria-label="Send message"+ variant="outline"disabled={isSubmitDisabled || !input.trim()}- onClick={(e) => {- e.stopPropagation();- }}>- Send <SendHorizontal className="ml-2 h-4 w-4" />+ <SendHorizontal className="h-4 w-4" /></Button>+ ))}++ {isExpanded && (+ <div className="flex w-full justify-end p-1">+ {canStopRun ? (+ <Button+ type="button"+ variant="outline"+ className="h-8 w-fit rounded-md px-3"+ aria-label={isCancellingRun ? "Stopping run" : "Stop run"}+ disabled={isCancellingRun}+ onClick={(e) => {+ e.stopPropagation();+ executionStop?.onStop();+ }}+ >+ {isCancellingRun ? "Stopping" : "Stop"}+ <Square className="ml-2 h-3 w-3" />+ </Button>+ ) : (+ <Button+ type="submit"+ className="h-8 w-fit rounded-md px-3"+ aria-label="Send message"+ disabled={isSubmitDisabled || !input.trim()}+ onClick={(e) => {+ e.stopPropagation();+ }}+ >+ Send <SendHorizontal className="ml-2 h-4 w-4" />+ </Button>+ )}</div>)}</form>diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex b9afe607ac..8bda7245eb 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -6,14 +6,19 @@ import {useMemo,useRef,useState,+ useSyncExternalStore,type PropsWithChildren,type Dispatch,type SetStateAction,} from "react";-import { EventType, HttpAgent } from "@ag-ui/client";+import {+ EventType,+ HttpAgent,+ type AbstractAgent,+ type AgentSubscriber,+} from "@ag-ui/client";import { useSession } from "next-auth/react";import { useRouter } from "next/router";-import { z } from "zod";import useSessionStorage from "@/src/components/useSessionStorage";import { env } from "@/src/env.mjs";@@ -25,12 +30,34 @@ import {import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";import {AgUiMessageSchema,+ dropEmptyAssistantMessages,+ dropUnpairedAssistantToolCalls,+ isActiveInAppAgentRunStatus,type AgUiMessage,type InAppAgentMessageFeedback,type InAppAgentMessageFeedbackValue,type InAppAgentRuntimeState,type InAppAgentToolApprovalRequest,} from "@langfuse/shared/in-app-agent";+import {+ createInAppAgentDisplayState,+ deserializeInAppAgentDisplayState,+ projectInAppAgentMessagesForDisplay,+ recordInAppAgentMessagesForDisplay,+ recordInAppAgentToolCallForDisplay,+ 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 {+ BackgroundExecutionSessionController,+ isCancellableBackgroundRun,+ parseInAppAgentInterruptEvent,+ type AgentInput,+ type BackgroundExecutionRunView,+ type BackgroundExecutionSession,+ type BackgroundExecutionView,+} from "@/src/features/in-app-agent/lib/backgroundExecutionSession";import type { InAppAgentError } from "@/src/features/in-app-agent/components/utils/utils";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showErrorToast } from "@/src/features/notifications/showErrorToast";@@ -68,20 +95,22 @@ const FEEDBACK_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-feedback";const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE ="Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";const EMPTY_MESSAGES: AgUiMessage[] = [];+const EMPTY_BACKGROUND_VIEW: BackgroundExecutionView = {+ messages: EMPTY_MESSAGES,+ displayState: createInAppAgentDisplayState(),+ liveMessageRevision: 0,+ eventCursor: -1,+ currentRun: null,+ pendingToolApprovals: [],+ cancelStatus: "idle",+ attachment: { status: "detached" },+};export type InAppAgentEntryPoint =| "top_nav"| "keyboard_shortcut"| "dashboard_widget";-const MastraSuspendEventSchema = z.object({- type: z.literal("mastra_suspend"),- toolCallId: z.string().min(1),- toolName: z.string().min(1),- args: z.unknown().optional(),- runId: z.string().min(1),-});-const getConversationAgentState = (projectId: string,conversationId: string,@@ -91,6 +120,23 @@ const getConversationAgentState = (? { type: "newConversation", projectId }: { type: "existingConversation", projectId, conversationId };+function useBackgroundExecutionView(+ session: BackgroundExecutionSession | null,+ bootstrapView: BackgroundExecutionView,+): BackgroundExecutionView {+ const subscribe = useCallback(+ (listener: () => void) =>+ session ? session.subscribe(listener) : () => undefined,+ [session],+ );+ const getSnapshot = useCallback(+ () => session?.getSnapshot() ?? bootstrapView,+ [bootstrapView, session],+ );++ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+}+const NOOP_CONTEXT: InAppAiAgentContextType = {isAvailable: false,open: false,@@ -102,6 +148,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {isSubmitting: false,pendingToolApprovals: [],isSelectedConversationHydrating: false,+ execution: { type: "foreground" },error: null,messages: [],liveMessageVersion: 0,@@ -125,37 +172,12 @@ type InAppAiAgentFeedbackByConversationId = Record<Record<string, InAppAgentMessageFeedback>>;-type InAppAgentDisplayPlacement = {- anchorMessageId: string;- order: number;-};--type InAppAgentDisplayState = {- latestPlacement: InAppAgentDisplayPlacement | null;- nativeToolCallParentMessageId: string | null;- latestNewMessageId: string | null;- nextOrder: number;- seenMessageIds: ReadonlySet<string>;- textByMessageId: Record<- string,- {- nativeContent: string;- publishedContent: string;- segments: Array<- InAppAgentDisplayPlacement & {- id: string;- content: string;- }- >;- }- >;- toolCallPlacements: Record<string, InAppAgentDisplayPlacement | null>;-};-export type InAppAgentPendingToolApproval = {id: string;approvalRequest: InAppAgentToolApprovalRequest;status: "pending" | "submitting";+ // Present for approvals restored from persisted background events.+ runId?: string;};export type InAppAiAgentConversation = {@@ -165,13 +187,20 @@ export type InAppAiAgentConversation = {isWriteLocked: boolean;};+type InAppAiAgentExecution =+ | { type: "foreground" }+ | {+ type: "background";+ run: BackgroundExecutionRunView | null;+ isCancelling: boolean;+ cancel: () => void;+ };+type InAppAiAgentContextType = {isAvailable: boolean;open: boolean;setOpen: Dispatch<SetStateAction<boolean>>;- /** Open the assistant from an entrypoint. Owns the AI-features gate: shows- * the disabled dialog and returns false when the organization has AI- * features turned off. */+ /** Returns false and opens the disabled dialog when AI features are off. */openAssistant: (source: InAppAgentEntryPoint) => boolean;isExpanded: boolean;setIsExpanded: Dispatch<SetStateAction<boolean>>;@@ -179,6 +208,7 @@ type InAppAiAgentContextType = {isSubmitting: boolean;pendingToolApprovals: InAppAgentPendingToolApproval[];isSelectedConversationHydrating: boolean;+ execution: InAppAiAgentExecution;error: InAppAgentError | null;messages: InAppAiAgentMessage[];liveMessageVersion: number;@@ -286,32 +316,40 @@ function InAppAiAgentProviderInner({`${FEEDBACK_STORAGE_KEY_PREFIX}:${projectId}`,{},);- const [messages, setMessages] = useState<AgUiMessage[]>([]);+ const [foregroundMessages, setForegroundMessages] = useState<AgUiMessage[]>(+ [],+ );// Only live AG-UI publications increment this version. The display smoother// uses it to distinguish stream updates from history hydration, including// updates where the agent mutates message objects in place.- const [liveMessageVersion, setLiveMessageVersion] = useState(0);+ const [foregroundLiveMessageVersion, setForegroundLiveMessageVersion] =+ useState(0);const [displayState, setDisplayState] = useState(createInAppAgentDisplayState,);- const [pendingToolApprovals, setPendingToolApprovals] = useState<+ const [foregroundPendingToolApprovals, setForegroundPendingToolApprovals] =+ useState<InAppAgentPendingToolApproval[]>([]);+ const foregroundPendingToolApprovalsRef = useRef<InAppAgentPendingToolApproval[]>([]);- const pendingToolApprovalsRef = useRef<InAppAgentPendingToolApproval[]>([]);- const [isRunning, setIsRunning] = useState(false);+ const [isForegroundRunning, setIsForegroundRunning] = useState(false);const [isExpanded, setIsExpanded] = useState(false);const [isSubmitting, setIsSubmitting] = useState(false);const [loadingEventIds, setLoadingEventIds] = useState<ReadonlySet<string>>(() => new Set(),);const [error, setError] = useState<InAppAgentError | null>(null);- const agentRef = useRef<HttpAgent | null>(null);+ const agentRef = useRef<AbstractAgent | null>(null);+ const backgroundSessionRef = useRef<BackgroundExecutionSession | null>(null);+ const [backgroundSession, setBackgroundSession] =+ useState<BackgroundExecutionSession | null>(null);const activeRunIdRef = useRef<string | null>(null);const toolCallNamesRef = useRef(new Map<string, string>());+ const backgroundExecutionEnabled = useInAppAgentBackgroundExecutionEnabled();const intentionalAbortRef = useRef(false);const submitInFlightRef = useRef(false);const runInFlightRef = useRef(false);- const subscriptionRef = useRef<ReturnType<HttpAgent["subscribe"]> | null>(+ const subscriptionRef = useRef<ReturnType<AbstractAgent["subscribe"]> | null>(null,);@@ -335,6 +373,10 @@ function InAppAiAgentProviderInner({const deleteConversationMutation =api.inAppAgent.deleteConversation.useMutation();const feedbackMutation = api.inAppAgent.submitFeedback.useMutation();+ const startRunMutation = api.inAppAgent.startRun.useMutation();+ const cancelRunMutation = api.inAppAgent.cancelRun.useMutation();+ const decideToolApprovalMutation =+ api.inAppAgent.decideToolApproval.useMutation();const isSelectedConversationNotFound =conversationQuery.error?.data?.code === "NOT_FOUND";const selectedConversationId = isSelectedConversationNotFound@@ -351,9 +393,115 @@ function InAppAiAgentProviderInner({const isLoadingMoreConversations = conversationListQuery.isFetchingNextPage;const selectedConversationIsWriteLocked =conversationQuery.data?.conversation.isWriteLocked ?? false;- const currentMessages = useMemo(() => {++ const bootstrapBackgroundView = useMemo<BackgroundExecutionView>(() => {+ if (+ conversationQuery.data?.conversation.id !== selectedConversationId ||+ !conversationQuery.data+ ) {+ return EMPTY_BACKGROUND_VIEW;+ }++ const latestRun = conversationQuery.data.latestRun;+ return {+ messages: conversationQuery.data.messages.filter(+ isAgentConversationMessage,+ ),+ displayState: deserializeInAppAgentDisplayState(+ conversationQuery.data.displayState,+ ),+ liveMessageRevision: 0,+ eventCursor: conversationQuery.data.eventCursor,+ currentRun: latestRun+ ? {+ id: latestRun.id,+ status: latestRun.status,+ errorCode: latestRun.errorCode,+ cancelRequested: latestRun.cancelRequested,+ }+ : null,+ pendingToolApprovals: conversationQuery.data.pendingToolApprovals.map(+ (approval) => ({ ...approval, status: "pending" as const }),+ ),+ cancelStatus: "idle",+ attachment: { status: "detached" },+ };+ }, [conversationQuery.data, selectedConversationId]);+ const backgroundExecutionView = useBackgroundExecutionView(+ backgroundSession,+ bootstrapBackgroundView,+ );+ const currentBackgroundRun = backgroundExecutionEnabled+ ? backgroundExecutionView.currentRun+ : null;+ const isBackgroundRunning =+ backgroundExecutionEnabled &&+ (backgroundExecutionView.attachment.status === "attaching" ||+ backgroundExecutionView.attachment.status === "attached" ||+ Boolean(+ currentBackgroundRun &&+ isActiveInAppAgentRunStatus(currentBackgroundRun.status),+ ));+ const isRunning = backgroundExecutionEnabled+ ? isBackgroundRunning+ : isForegroundRunning;+ const effectiveError =+ backgroundExecutionEnabled &&+ backgroundExecutionView.attachment.status === "error"+ ? getInAppAgentError(backgroundExecutionView.attachment.error)+ : error;+ const liveMessageVersion = backgroundExecutionEnabled+ ? backgroundExecutionView.liveMessageRevision+ : foregroundLiveMessageVersion;++ const effectivePendingToolApprovals = useMemo(() => {+ if (!backgroundExecutionEnabled) {+ return foregroundPendingToolApprovals;+ }++ return backgroundExecutionView.pendingToolApprovals.map(+ ({ runId, approvalRequest, status }): InAppAgentPendingToolApproval => ({+ id: approvalRequest.toolCallId,+ approvalRequest,+ status,+ runId,+ }),+ );+ }, [+ backgroundExecutionEnabled,+ backgroundExecutionView.pendingToolApprovals,+ foregroundPendingToolApprovals,+ ]);+ /**+ * Messages and their display sidecar always come from the same source, so the+ * projection below can never fold live messages against persisted state (or+ * the reverse). `isSettled` marks a transcript the server has finished+ * writing, which is the only case where pruning is safe.+ *+ * A run paused on an approval needs no special case: `human-in-the-loop.ts`+ * emits the tool call's START and RESULT in one batch when the decision is+ * resolved, so a pending approval has no tool call yet and a resolved one is+ * never unpaired.+ */+ const currentSource = useMemo((): {+ messages: readonly AgUiMessage[];+ displayState: InAppAgentDisplayState;+ isSettled: boolean;+ } => {if (isSelectedConversationNotFound) {- return EMPTY_MESSAGES;+ return {+ messages: EMPTY_MESSAGES,+ displayState: EMPTY_BACKGROUND_VIEW.displayState,+ isSettled: true,+ };+ }++ if (backgroundExecutionEnabled) {+ return {+ messages: backgroundExecutionView.messages,+ displayState: backgroundExecutionView.displayState,+ isSettled: !isBackgroundRunning,+ };}const storedMessages =@@ -364,29 +512,83 @@ function InAppAiAgentProviderInner({if (!isRunning &&storedMessages &&- messages.length <= storedMessages.length+ foregroundMessages.length <= storedMessages.length) {- return storedMessages;+ return {+ messages: storedMessages,+ displayState: deserializeInAppAgentDisplayState(+ conversationQuery.data?.displayState,+ ),+ isSettled: true,+ };}- return messages;+ return {+ messages: foregroundMessages,+ displayState,+ isSettled: false,+ };}, [+ backgroundExecutionEnabled,+ backgroundExecutionView.displayState,+ backgroundExecutionView.messages,conversationQuery.data,+ displayState,+ foregroundMessages,+ isBackgroundRunning,isRunning,isSelectedConversationNotFound,- messages,selectedConversationId,]);const messagesWithUiState = useMemo(() => {+ // Unpaired tool calls and empty assistant messages are pruned only once the+ // transcript is settled. A live seed must keep them: an in-flight tool call+ // needs to be present for its arriving result to attach to.+ const prunedMessages = currentSource.isSettled+ ? dropEmptyAssistantMessages(+ dropUnpairedAssistantToolCalls(currentSource.messages),+ )+ : currentSource.messages;+ const messagesWithRunId = backgroundExecutionEnabled+ ? attachActiveRunIdToAssistantMessages(+ prunedMessages,+ currentBackgroundRun?.id ?? null,+ )+ : prunedMessages;const messagesWithFeedback = mergeMessagesWithFeedback(- currentMessages,+ messagesWithRunId,selectedConversationId? feedbackByConversationId[selectedConversationId]: undefined,);+ const unresolvedActiveRunToolCallIds = new Set<string>();+ if (+ backgroundExecutionEnabled &&+ currentBackgroundRun &&+ isActiveInAppAgentRunStatus(currentBackgroundRun.status)+ ) {+ const resultToolCallIds = new Set(+ prunedMessages.flatMap((message) =>+ message.role === "tool" ? [message.toolCallId] : [],+ ),+ );+ for (const message of prunedMessages) {+ if (+ message.role !== "assistant" ||+ message.runId !== currentBackgroundRun.id+ ) {+ continue;+ }+ for (const toolCall of message.toolCalls ?? []) {+ if (!resultToolCallIds.has(toolCall.id)) {+ unresolvedActiveRunToolCallIds.add(toolCall.id);+ }+ }+ }+ }const displayMessages = projectInAppAgentMessagesForDisplay(messagesWithFeedback,- displayState,+ currentSource.displayState,);return displayMessages.map((message) => {@@ -405,17 +607,19 @@ function InAppAiAgentProviderInner({(message.toolCalls?.some((toolCall) =>toolCall.function.name !== IN_APP_AGENT_REDIRECT_TOOL_NAME &&- loadingEventIds.has(toolCall.id),+ (loadingEventIds.has(toolCall.id) ||+ unresolvedActiveRunToolCallIds.has(toolCall.id)),) ??false),};});}, [+ backgroundExecutionEnabled,+ currentBackgroundRun,feedbackByConversationId,- currentMessages,+ currentSource,loadingEventIds,selectedConversationId,- displayState,]);const fetchNextConversationsPage = conversationListQuery.fetchNextPage;const loadMoreConversations = useCallback(() => {@@ -461,9 +665,9 @@ function InAppAiAgentProviderInner({currentApprovals: InAppAgentPendingToolApproval[],) => InAppAgentPendingToolApproval[],) => {- const nextApprovals = updater(pendingToolApprovalsRef.current);- pendingToolApprovalsRef.current = nextApprovals;- setPendingToolApprovals(nextApprovals);+ const nextApprovals = updater(foregroundPendingToolApprovalsRef.current);+ foregroundPendingToolApprovalsRef.current = nextApprovals;+ setForegroundPendingToolApprovals(nextApprovals);},[],);@@ -490,16 +694,25 @@ function InAppAiAgentProviderInner({currentIds.size > 0 ? new Set() : currentIds,);}, []);- const publishLiveMessages = useCallback((messages: AgUiMessage[]) => {- setMessages(messages);- setLiveMessageVersion((currentVersion) => currentVersion + 1);- }, []);+ const publishLiveMessages = useCallback(+ (messages: readonly AgUiMessage[]) => {+ setForegroundMessages([...messages]);+ setForegroundLiveMessageVersion((currentVersion) => currentVersion + 1);+ },+ [],+ );+ const recordAgentMessagesForDisplay = useCallback(+ (messages: AgUiMessage[]) => {+ setDisplayState((currentState) =>+ recordInAppAgentMessagesForDisplay(currentState, messages),+ );+ },+ [],+ );const publishAgentMessages = useCallback((agentMessages: readonly unknown[]) => {const nextMessages = agentMessages.filter(isAgentConversationMessage);- setDisplayState((currentState) =>- recordInAppAgentMessagesForDisplay(currentState, nextMessages),- );+ recordAgentMessagesForDisplay(nextMessages);publishLiveMessages(attachActiveRunIdToAssistantMessages(@@ -508,7 +721,7 @@ function InAppAiAgentProviderInner({),);},- [publishLiveMessages],+ [publishLiveMessages, recordAgentMessagesForDisplay],);const resetAgent = useCallback(() => {if (agentRef.current?.isRunning) {@@ -517,15 +730,20 @@ function InAppAiAgentProviderInner({subscriptionRef.current?.unsubscribe();subscriptionRef.current = null;- agentRef.current?.abortRun();+ backgroundSessionRef.current?.dispose();+ backgroundSessionRef.current = null;+ setBackgroundSession(null);+ if (!backgroundExecutionEnabled) {+ agentRef.current?.abortRun();+ }agentRef.current = null;activeRunIdRef.current = null;toolCallNamesRef.current.clear();setDisplayState(createInAppAgentDisplayState());- pendingToolApprovalsRef.current = [];- setPendingToolApprovals([]);+ foregroundPendingToolApprovalsRef.current = [];+ setForegroundPendingToolApprovals([]);clearLoadingEvents();- }, [clearLoadingEvents]);+ }, [backgroundExecutionEnabled, clearLoadingEvents]);useEffect(() => {return () => {@@ -561,13 +779,18 @@ function InAppAiAgentProviderInner({};}, [rateLimitRetryAt]);- const ensureSubscription = useCallback(- (agent: HttpAgent) => {- if (subscriptionRef.current) {- return;- }-- subscriptionRef.current = agent.subscribe({+ const createSharedAgentSubscriber = useCallback(+ (+ options: {+ reportRunError?: boolean;+ /**+ * Foreground only. The background session owns its own display state,+ * so it must not also feed the provider's foreground copy.+ */+ recordDisplayState?: boolean;+ } = {},+ ) =>+ ({onRunStartedEvent: ({event,messages: runMessages,@@ -575,12 +798,14 @@ function InAppAiAgentProviderInner({event: unknown;messages: readonly unknown[];}) => {- setDisplayState((currentState) =>- recordInAppAgentMessagesForDisplay(- currentState,- runMessages.filter(isAgentConversationMessage),- ),- );+ if (options.recordDisplayState !== false) {+ setDisplayState((currentState) =>+ recordInAppAgentMessagesForDisplay(+ currentState,+ runMessages.filter(isAgentConversationMessage),+ ),+ );+ }if (typeof event === "object" &&@@ -610,13 +835,15 @@ function InAppAiAgentProviderInner({if (event.type === EventType.TOOL_CALL_START) {toolCallNamesRef.current.set(event.toolCallId, event.toolCallName);- setDisplayState((currentState) =>- recordInAppAgentToolCallForDisplay(- currentState,- event.toolCallId,- event.parentMessageId,- ),- );+ if (options.recordDisplayState !== false) {+ setDisplayState((currentState) =>+ recordInAppAgentToolCallForDisplay(+ currentState,+ event.toolCallId,+ event.parentMessageId,+ ),+ );+ }updateLoadingEvent(event.toolCallId, true);return;@@ -636,6 +863,45 @@ function InAppAiAgentProviderInner({clearLoadingEvents();}},+ onToolCallResultEvent: ({ event }) => {+ const toolName = toolCallNamesRef.current.get(event.toolCallId);+ toolCallNamesRef.current.delete(event.toolCallId);+ if (toolName && shouldPerformToolSideEffects(event.error)) {+ performToolSideEffects({ toolName, utils }).catch(+ (error: unknown) => {+ console.error(+ "Failed to invalidate tRPC routes after in-app agent tool call",+ { error, toolName },+ );+ },+ );+ }+ },+ onRunErrorEvent: ({ event }) => {+ if (intentionalAbortRef.current) {+ return;+ }++ setError(getInAppAgentError(event));+ if (options.reportRunError !== false) {+ console.error("In-app agent drawer run error", event);+ }+ },+ }) satisfies AgentSubscriber,+ [clearLoadingEvents, updateLoadingEvent, utils],+ );+ const ensureSubscription = useCallback(+ (agent: AbstractAgent) => {+ if (+ subscriptionRef.current ||+ agent instanceof InAppAgentBackgroundClient+ ) {+ return;+ }++ const sharedSubscriber = createSharedAgentSubscriber();+ subscriptionRef.current = agent.subscribe({+ ...sharedSubscriber,onCustomEvent: ({ event }) => {const approvalRequest = parseInAppAgentInterruptEvent(event);@@ -663,35 +929,15 @@ function InAppAiAgentProviderInner({return nextApprovals;});},- onToolCallResultEvent: ({ event }) => {- const toolName = toolCallNamesRef.current.get(event.toolCallId);- toolCallNamesRef.current.delete(event.toolCallId);- if (toolName && shouldPerformToolSideEffects(event.error)) {- performToolSideEffects({ toolName, utils }).catch(- (error: unknown) => {- console.error(- "Failed to invalidate tRPC routes after in-app agent tool call",- { error, toolName },- );- },- );- }-+ onToolCallResultEvent: (params) => {+ sharedSubscriber.onToolCallResultEvent(params);updatePendingToolApprovals((currentApprovals) =>currentApprovals.filter((approval) =>- approval.approvalRequest.toolCallId !== event.toolCallId,+ approval.approvalRequest.toolCallId !== params.event.toolCallId,),);},- onRunErrorEvent: ({ event }) => {- if (intentionalAbortRef.current) {- return;- }-- setError(getInAppAgentError(event));- console.error("In-app agent drawer run error", event);- },onMessagesChanged: ({ messages }) => {publishAgentMessages(messages);},@@ -701,14 +947,17 @@ function InAppAiAgentProviderInner({});},[- clearLoadingEvents,+ createSharedAgentSubscriber,publishAgentMessages,- utils,- updateLoadingEvent,updatePendingToolApprovals,],);+ const releaseSubmitLock = useCallback(() => {+ submitInFlightRef.current = false;+ setIsSubmitting(false);+ }, []);+const getOrCreateAgent = useCallback((conversationId: string,@@ -721,34 +970,183 @@ function InAppAiAgentProviderInner({resetAgent();- const agent = new HttpAgent({- url: getInAppAgentUrl(),- threadId: conversationId,- initialMessages,- initialState: getConversationAgentState(- projectId,- conversationId,- isNewConversation,- ),- });+ const initialState = getConversationAgentState(+ projectId,+ conversationId,+ isNewConversation,+ );++ const initialCursor =+ conversationQuery.data?.conversation.id === conversationId+ ? conversationQuery.data.eventCursor+ : -1;+ const initialRun =+ conversationQuery.data?.conversation.id === conversationId &&+ conversationQuery.data.latestRun+ ? {+ id: conversationQuery.data.latestRun.id,+ status: conversationQuery.data.latestRun.status,+ errorCode: conversationQuery.data.latestRun.errorCode,+ cancelRequested: conversationQuery.data.latestRun.cancelRequested,+ }+ : null;++ const agent = backgroundExecutionEnabled+ ? new InAppAgentBackgroundClient({+ projectId,+ conversationId,+ threadId: conversationId,+ initialMessages,+ initialState,+ cursor: initialCursor,+ startRun: (params) =>+ startRunMutation.mutateAsync({+ projectId,+ conversationId,+ message: params.message,+ context: [...params.context],+ }),+ })+ : new HttpAgent({+ url: getInAppAgentUrl(),+ threadId: conversationId,+ initialMessages,+ initialState,+ });agentRef.current = agent;+ if (agent instanceof InAppAgentBackgroundClient) {+ const nextBackgroundSession = new BackgroundExecutionSessionController({+ agent,+ // The session owns background display state; the shared subscriber+ // must not also record into the foreground-only provider state.+ subscriber: createSharedAgentSubscriber({+ reportRunError: false,+ recordDisplayState: false,+ }),+ initialView: {+ messages: initialMessages,+ displayState: deserializeInAppAgentDisplayState(+ conversationQuery.data?.conversation.id === conversationId+ ? conversationQuery.data.displayState+ : undefined,+ ),+ eventCursor: initialCursor,+ currentRun: initialRun,+ },+ hydrate: async () => {+ const snapshot = await utils.inAppAgent.getConversation.fetch({+ projectId,+ conversationId,+ });++ return {+ messages: snapshot.messages.filter(isAgentConversationMessage),+ displayState: deserializeInAppAgentDisplayState(+ snapshot.displayState,+ ),+ eventCursor: snapshot.eventCursor,+ currentRun: snapshot.latestRun+ ? {+ id: snapshot.latestRun.id,+ status: snapshot.latestRun.status,+ errorCode: snapshot.latestRun.errorCode,+ cancelRequested: snapshot.latestRun.cancelRequested,+ }+ : null,+ pendingToolApprovals: snapshot.pendingToolApprovals.map(+ (approval) => ({ ...approval, status: "pending" as const }),+ ),+ } satisfies Omit<+ BackgroundExecutionView,+ "attachment" | "cancelStatus" | "liveMessageRevision"+ >;+ },+ cancelRun: (runId) =>+ cancelRunMutation.mutateAsync({+ projectId,+ conversationId,+ runId,+ }),+ decideApproval: (input) =>+ decideToolApprovalMutation.mutateAsync({+ projectId,+ conversationId,+ runId: input.runId,+ toolCallId: input.toolCallId,+ approved: input.approved,+ }),+ onSettled: () => {+ clearLoadingEvents();+ utils.inAppAgent.listConversations.invalidate({ projectId });+ utils.inAppAgent.getConversation.invalidate({+ projectId,+ conversationId,+ });+ releaseSubmitLock();+ activeRunIdRef.current = null;+ intentionalAbortRef.current = false;+ },+ });+ backgroundSessionRef.current = nextBackgroundSession;+ setBackgroundSession(nextBackgroundSession);+ }+return agent;},- [projectId, resetAgent],+ [+ backgroundExecutionEnabled,+ cancelRunMutation,+ clearLoadingEvents,+ conversationQuery.data,+ createSharedAgentSubscriber,+ decideToolApprovalMutation,+ projectId,+ releaseSubmitLock,+ resetAgent,+ startRunMutation,+ utils.inAppAgent.getConversation,+ utils.inAppAgent.listConversations,+ ],);- const releaseSubmitLock = useCallback(() => {- submitInFlightRef.current = false;- setIsSubmitting(false);- }, []);+ const createRunInput = useCallback(+ (+ runParameters?: AgentInput,+ quickActionAttribution?: InAppAgentQuickActionAttribution,+ messageEntryPoint?: InAppAgentMessageEntryPoint,+ ): AgentInput => ({+ ...runParameters,+ context: createInAppAgentScreenContext({+ currentUrl: window.location.href,+ }).concat(+ createInAppAgentUserContext({+ userName: session.data?.user?.name,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ languages:+ navigator.languages.length > 0+ ? Array.from(navigator.languages)+ : [navigator.language],+ }),+ quickActionAttribution+ ? createInAppAgentQuickActionAttributionContext(+ quickActionAttribution,+ )+ : [],+ messageEntryPoint+ ? createInAppAgentMessageEntryPointContext(messageEntryPoint)+ : [],+ ),+ }),+ [session.data?.user?.name],+ );const runAgent = useCallback((- agent: HttpAgent,+ agent: AbstractAgent,conversationId: string,- runParameters?: Parameters<HttpAgent["runAgent"]>[0],+ runParameters?: Parameters<AbstractAgent["runAgent"]>[0],quickActionAttribution?: InAppAgentQuickActionAttribution,messageEntryPoint?: InAppAgentMessageEntryPoint,) => {@@ -758,32 +1156,16 @@ function InAppAiAgentProviderInner({runInFlightRef.current = true;clearLoadingEvents();- setIsRunning(true);+ setIsForegroundRunning(true);return (async () => {try {- await agent.runAgent({- ...runParameters,- context: createInAppAgentScreenContext({- currentUrl: window.location.href,- }).concat(- createInAppAgentUserContext({- userName: session.data?.user?.name,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- languages:- navigator.languages.length > 0- ? Array.from(navigator.languages)- : [navigator.language],- }),- quickActionAttribution- ? createInAppAgentQuickActionAttributionContext(- quickActionAttribution,- )- : [],- messageEntryPoint- ? createInAppAgentMessageEntryPointContext(messageEntryPoint)- : [],+ await agent.runAgent(+ createRunInput(+ runParameters,+ quickActionAttribution,+ messageEntryPoint,),- });+ );return true;} catch (error) {if (intentionalAbortRef.current) {@@ -800,7 +1182,7 @@ function InAppAiAgentProviderInner({} finally {const runId = activeRunIdRef.current;clearLoadingEvents();- setIsRunning(false);+ setIsForegroundRunning(false);publishLiveMessages(attachActiveRunIdToAssistantMessages(agent.messages.filter(isAgentConversationMessage),@@ -822,9 +1204,9 @@ function InAppAiAgentProviderInner({[projectId,clearLoadingEvents,+ createRunInput,publishLiveMessages,releaseSubmitLock,- session.data?.user?.name,utils.inAppAgent.getConversation,utils.inAppAgent.listConversations,],@@ -840,7 +1222,7 @@ function InAppAiAgentProviderInner({isInAppAgentRateLimited(currentError) ? currentError : null,);resetAgent();- setMessages([]);+ setForegroundMessages([]);setSelectedConversationId(conversationId);},[_selectedConversationId, isRunning, resetAgent, setSelectedConversationId],@@ -860,7 +1242,7 @@ function InAppAiAgentProviderInner({if (conversationId === selectedConversationId) {resetAgent();- setMessages([]);+ setForegroundMessages([]);setSelectedConversationId(null);}@@ -948,9 +1330,14 @@ function InAppAiAgentProviderInner({conversationQuery.data?.conversation.id === conversationId? conversationQuery.data.messages: undefined;- const initialMessages = !isNewConversation- ? getHydratedMessages(messages, storedMessages)- : [];+ const initialMessages = isNewConversation+ ? []+ : backgroundExecutionEnabled+ ? // Persisted state is the render source on the background path, so+ // prefer it over the in-memory transcript.+ (storedMessages?.filter(isAgentConversationMessage) ??+ getHydratedMessages(foregroundMessages, storedMessages))+ : getHydratedMessages(foregroundMessages, storedMessages);// TODO: Avoid hydrating the full history once the agent client can send// only the latest user turn; the server rebuilds history from persistence.const agent = getOrCreateAgent(@@ -963,6 +1350,11 @@ function InAppAiAgentProviderInner({return false;}+ // Start background turns from the persisted transcript and cursor.+ if (agent instanceof InAppAgentBackgroundClient && !isNewConversation) {+ agent.setMessages(initialMessages);+ }+ensureSubscription(agent);const userMessage = {@@ -972,24 +1364,49 @@ function InAppAiAgentProviderInner({} satisfies AgUiMessage;agent.addMessage(userMessage);- setMessages(agent.messages.filter(isAgentConversationMessage));+ if (!backgroundExecutionEnabled) {+ setForegroundMessages(+ agent.messages.filter(isAgentConversationMessage),+ );+ }const entryPoint = options?.entryPoint ?? "chat";if (isNewConversation) {capture("in_app_agent:new_chat_started", { entryPoint });}capture("in_app_agent:new_chat_turn", { entryPoint });startedRun = true;- runAgent(- agent,- conversationId,- undefined,- options?.quickAction,- entryPoint,- );+ if (backgroundExecutionEnabled) {+ const backgroundSession = backgroundSessionRef.current;++ if (!backgroundSession) {+ throw new Error("Background execution session is unavailable");+ }++ clearLoadingEvents();+ backgroundSession+ .run(createRunInput(undefined, options?.quickAction, entryPoint))+ .catch((error: unknown) => {+ if (+ backgroundSession.getSnapshot().attachment.status !== "error"+ ) {+ setError(getInAppAgentError(error));+ }+ });+ } else {+ runAgent(+ agent,+ conversationId,+ undefined,+ options?.quickAction,+ entryPoint,+ );+ }return true;} catch (error) {setError(getInAppAgentError(error));- console.error("Failed to start in-app agent conversation", error);+ if (!backgroundExecutionEnabled) {+ console.error("Failed to start in-app agent conversation", error);+ }return false;} finally {if (!startedRun) {@@ -998,14 +1415,17 @@ function InAppAiAgentProviderInner({}},[+ backgroundExecutionEnabled,conversationQuery.data,capture,+ clearLoadingEvents,ensureSubscription,error,+ createRunInput,getOrCreateAgent,isSelectedConversationHydrating,isRunning,- messages,+ foregroundMessages,releaseSubmitLock,runAgent,selectedConversationId,@@ -1070,6 +1490,60 @@ function InAppAiAgentProviderInner({],);+ // Hydrate transcript and cursor from one snapshot before observing its tail.+ const attachToConversation = useCallback(+ async (conversationId: string) => {+ if (!backgroundExecutionEnabled) {+ return;+ }++ const initialMessages =+ conversationQuery.data?.conversation.id === conversationId+ ? conversationQuery.data.messages.filter(isAgentConversationMessage)+ : [];+ const agent = getOrCreateAgent(conversationId, initialMessages, false);++ if (!(agent instanceof InAppAgentBackgroundClient)) {+ return;+ }++ ensureSubscription(agent);+ await backgroundSessionRef.current?.hydrateAndAttach();+ },+ [+ backgroundExecutionEnabled,+ conversationQuery.data,+ ensureSubscription,+ getOrCreateAgent,+ ],+ );+ const attachToConversationRef = useRef(attachToConversation);+ attachToConversationRef.current = attachToConversation;++ const hydratedActiveRunId =+ open &&+ backgroundExecutionEnabled &&+ conversationQuery.data?.conversation.id === selectedConversationId &&+ conversationQuery.data.latestRun &&+ isActiveInAppAgentRunStatus(conversationQuery.data.latestRun.status)+ ? conversationQuery.data.latestRun.id+ : null;++ // Reattach after refresh once the persisted active run is known.+ useEffect(() => {+ if (!hydratedActiveRunId || !selectedConversationId) {+ return;+ }++ attachToConversationRef+ .current(selectedConversationId)+ .catch(() => undefined);++ return () => {+ backgroundSessionRef.current?.detach();+ };+ }, [hydratedActiveRunId, selectedConversationId]);+const setAgentOpen = useCallback<Dispatch<SetStateAction<boolean>>>((action) => {const nextOpen = evaluateSetStateAction(action, open);@@ -1077,11 +1551,27 @@ function InAppAiAgentProviderInner({if (!nextOpen) {// Collapse the drawer when closingsetIsExpanded(false);++ if (backgroundExecutionEnabled) {+ backgroundSessionRef.current?.detach();+ releaseSubmitLock();+ }+ }++ if (nextOpen && backgroundExecutionEnabled && selectedConversationId) {+ attachToConversation(selectedConversationId).catch(() => undefined);}setOpen(nextOpen);},- [open, setOpen],+ [+ attachToConversation,+ backgroundExecutionEnabled,+ open,+ releaseSubmitLock,+ selectedConversationId,+ setOpen,+ ],);const openAssistant = useCallback(@@ -1099,6 +1589,92 @@ function InAppAiAgentProviderInner({[capture, organization, setAgentOpen],);+ const isCancellingRun = Boolean(+ backgroundExecutionView.cancelStatus === "submitting" ||+ (currentBackgroundRun &&+ isCancellableBackgroundRun(currentBackgroundRun.status) &&+ currentBackgroundRun.cancelRequested),+ );++ const cancelRun = useCallback(() => {+ const run = currentBackgroundRun;++ if (+ !selectedConversationId ||+ !run ||+ !isCancellableBackgroundRun(run.status) ||+ run.cancelRequested+ ) {+ return;+ }++ const initialMessages =+ conversationQuery.data?.conversation.id === selectedConversationId+ ? conversationQuery.data.messages.filter(isAgentConversationMessage)+ : [];+ const agent = getOrCreateAgent(+ selectedConversationId,+ initialMessages,+ false,+ );+ ensureSubscription(agent);+ const backgroundSession = backgroundSessionRef.current;++ if (!backgroundSession) {+ return;+ }++ backgroundSession.cancel().catch((error: unknown) => {+ showErrorToast("Failed to stop the run", getAgentErrorMessage(error));+ });+ }, [+ conversationQuery.data,+ currentBackgroundRun,+ ensureSubscription,+ getOrCreateAgent,+ selectedConversationId,+ ]);++ const decideBackgroundToolApproval = useCallback(+ async (params: {+ approval: InAppAgentPendingToolApproval;+ approved: boolean;+ conversationId: string;+ }) => {+ const runId =+ params.approval.runId ?? params.approval.approvalRequest.runId;++ setError(null);++ try {+ const initialMessages =+ conversationQuery.data?.conversation.id === params.conversationId+ ? conversationQuery.data.messages.filter(isAgentConversationMessage)+ : [];+ const agent = getOrCreateAgent(+ params.conversationId,+ initialMessages,+ false,+ );+ ensureSubscription(agent);+ const backgroundSession = backgroundSessionRef.current;++ if (!backgroundSession) {+ throw new Error("Background execution session is unavailable");+ }++ await backgroundSession.decide({+ runId,+ toolCallId: params.approval.approvalRequest.toolCallId,+ approved: params.approved,+ });+ } catch (error) {+ setError(getInAppAgentError(error));+ }+ },+ [conversationQuery.data, ensureSubscription, getOrCreateAgent],+ );+const resumeToolApproval = useCallback(async (approvalId: string, approved: boolean) => {if (selectedConversationIsWriteLocked) {@@ -1109,7 +1685,7 @@ function InAppAiAgentProviderInner({return;}- const approval = pendingToolApprovals.find(+ const approval = effectivePendingToolApprovals.find((approval) => approval.id === approvalId,);@@ -1123,6 +1699,15 @@ function InAppAiAgentProviderInner({return;}+ if (backgroundExecutionEnabled) {+ await decideBackgroundToolApproval({+ approval,+ approved,+ conversationId: selectedConversationId,+ });+ return;+ }+const agent = agentRef.current;if (!agent || agent.threadId !== selectedConversationId) {showErrorToast(@@ -1199,10 +1784,12 @@ function InAppAiAgentProviderInner({}},[+ backgroundExecutionEnabled,+ decideBackgroundToolApproval,+ effectivePendingToolApprovals,ensureSubscription,error,isRunning,- pendingToolApprovals,runAgent,selectedConversationId,selectedConversationIsWriteLocked,@@ -1210,6 +1797,24 @@ function InAppAiAgentProviderInner({],);+ const execution = useMemo<InAppAiAgentExecution>(() => {+ if (!backgroundExecutionEnabled) {+ return { type: "foreground" };+ }++ return {+ type: "background",+ run: currentBackgroundRun,+ isCancelling: isCancellingRun,+ cancel: cancelRun,+ };+ }, [+ backgroundExecutionEnabled,+ cancelRun,+ currentBackgroundRun,+ isCancellingRun,+ ]);+const approveToolCall = useCallback((approvalId: string) => resumeToolApproval(approvalId, true),[resumeToolApproval],@@ -1232,9 +1837,10 @@ function InAppAiAgentProviderInner({isSubmitting,pendingToolApprovals: isSelectedConversationNotFound? []- : pendingToolApprovals,+ : effectivePendingToolApprovals,isSelectedConversationHydrating,- error,+ execution,+ error: effectiveError,messages: messagesWithUiState,liveMessageVersion,conversations,@@ -1255,7 +1861,7 @@ function InAppAiAgentProviderInner({approveToolCall,isExpanded,conversations,- error,+ effectiveError,hasMoreConversations,isLoadingMoreConversations,isRunning,@@ -1269,7 +1875,8 @@ function InAppAiAgentProviderInner({messagesWithUiState,open,openAssistant,- pendingToolApprovals,+ execution,+ effectivePendingToolApprovals,rejectToolCall,setAgentOpen,invalidateConversations,@@ -1310,9 +1917,9 @@ function getHydratedMessages(}function mergeMessagesWithFeedback(- messages: AgUiMessage[],+ messages: readonly AgUiMessage[],feedbackByMessageId: Record<string, InAppAgentMessageFeedback> | undefined,-): AgUiMessage[] {+): readonly AgUiMessage[] {if (!feedbackByMessageId || Object.keys(feedbackByMessageId).length === 0) {return messages;}@@ -1332,9 +1939,9 @@ function mergeMessagesWithFeedback(}function attachActiveRunIdToAssistantMessages(- messages: AgUiMessage[],+ messages: readonly AgUiMessage[],runId: string | null,-): AgUiMessage[] {+): readonly AgUiMessage[] {if (!runId) {return messages;}@@ -1348,303 +1955,6 @@ function attachActiveRunIdToAssistantMessages(});}-export function createInAppAgentDisplayState() {- const state: InAppAgentDisplayState = {- latestPlacement: null,- nativeToolCallParentMessageId: null,- latestNewMessageId: null,- nextOrder: 0,- seenMessageIds: new Set(),- textByMessageId: {},- toolCallPlacements: {},- };-- return state;-}--export function recordInAppAgentMessagesForDisplay(- state: InAppAgentDisplayState,- messages: AgUiMessage[],-): InAppAgentDisplayState {- const seenMessageIds = new Set(state.seenMessageIds);- const textByMessageId = { ...state.textByMessageId };- let latestNewMessageId = state.latestNewMessageId;- let latestPlacement = state.latestPlacement;- let nativeToolCallParentMessageId = state.nativeToolCallParentMessageId;- let nextOrder = state.nextOrder;-- for (const message of messages) {- if (seenMessageIds.has(message.id)) {- continue;- }-- seenMessageIds.add(message.id);- latestNewMessageId = message.id;- latestPlacement = null;- nativeToolCallParentMessageId = null;-- if (message.role === "assistant" && typeof message.content === "string") {- textByMessageId[message.id] = {- nativeContent: message.content,- publishedContent: message.content,- segments: [],- };- }- }-- for (const message of messages) {- if (message.role !== "assistant" || typeof message.content !== "string") {- continue;- }-- const textState = textByMessageId[message.id];- if (!textState || textState.publishedContent === message.content) {- continue;- }-- nativeToolCallParentMessageId = null;- if (!message.content.startsWith(textState.publishedContent)) {- textByMessageId[message.id] = {- nativeContent: message.content,- publishedContent: message.content,- segments: [],- };- continue;- }-- const appendedContent = message.content.slice(- textState.publishedContent.length,- );- const latestSegment = textState.segments.at(-1);- if (latestPlacement && latestSegment?.order === latestPlacement.order) {- textByMessageId[message.id] = {- ...textState,- publishedContent: message.content,- segments: textState.segments.slice(0, -1).concat({- ...latestSegment,- content: latestSegment.content + appendedContent,- }),- };- continue;- }-- if (latestNewMessageId === message.id && latestPlacement === null) {- textByMessageId[message.id] = {- ...textState,- nativeContent: textState.nativeContent + appendedContent,- publishedContent: message.content,- };- continue;- }-- const anchorMessageId =- latestPlacement?.anchorMessageId ?? latestNewMessageId;- if (!anchorMessageId) {- textByMessageId[message.id] = {- ...textState,- nativeContent: textState.nativeContent + appendedContent,- publishedContent: message.content,- };- continue;- }-- const placement = { anchorMessageId, order: nextOrder };- const segment = {- ...placement,- id: `display-text-${message.id}-${textState.segments.length + 1}`,- content: appendedContent,- };- nextOrder += 1;- latestPlacement = placement;- textByMessageId[message.id] = {- ...textState,- publishedContent: message.content,- segments: textState.segments.concat(segment),- };- }-- return {- ...state,- latestPlacement,- nativeToolCallParentMessageId,- latestNewMessageId,- nextOrder,- seenMessageIds,- textByMessageId,- };-}--export function recordInAppAgentToolCallForDisplay(- state: InAppAgentDisplayState,- toolCallId: string,- parentMessageId: string | undefined,-): InAppAgentDisplayState {- if (toolCallId in state.toolCallPlacements) {- return state;- }-- const anchorMessageId =- state.latestPlacement?.anchorMessageId ?? state.latestNewMessageId;- const placement = anchorMessageId- ? { anchorMessageId, order: state.nextOrder }- : null;- const isNativePlacement =- (state.latestPlacement === null && anchorMessageId === parentMessageId) ||- state.nativeToolCallParentMessageId === parentMessageId;-- return {- ...state,- latestPlacement: placement,- nativeToolCallParentMessageId: isNativePlacement ? anchorMessageId : null,- nextOrder: state.nextOrder + 1,- toolCallPlacements: {- ...state.toolCallPlacements,- [toolCallId]: isNativePlacement ? null : placement,- },- };-}--export function projectInAppAgentMessagesForDisplay(- messages: AgUiMessage[],- state: InAppAgentDisplayState,-) {- // Canonical messages stay untouched for persistence and subsequent runs.- const messageIds = new Set(messages.map((message) => message.id));- const placementsByAnchor = new Map<- string,- Array<{ order: number; message: AgUiMessage }>- >();-- const addPlacement = (- placement: InAppAgentDisplayPlacement,- message: AgUiMessage,- ) => {- if (!messageIds.has(placement.anchorMessageId)) {- return;- }-- placementsByAnchor.set(- placement.anchorMessageId,- (placementsByAnchor.get(placement.anchorMessageId) ?? []).concat({- order: placement.order,- message,- }),- );- };-- for (const message of messages) {- if (message.role !== "assistant") {- continue;- }-- for (const toolCall of message.toolCalls ?? []) {- const placement = state.toolCallPlacements[toolCall.id];- if (- !placement ||- toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME- ) {- continue;- }-- addPlacement(placement, {- id: `display-tool-${toolCall.id}`,- role: "assistant",- content: "",- toolCalls: [toolCall],- });- }- }-- for (const [sourceMessageId, textState] of Object.entries(- state.textByMessageId,- )) {- const sourceMessage = messages.find(- (message) =>- message.role === "assistant" && message.id === sourceMessageId,- );-- for (const segment of textState.segments) {- addPlacement(segment, {- id: segment.id,- role: "assistant",- content: segment.content,- ...(sourceMessage?.role === "assistant"- ? {- runId: sourceMessage.runId,- feedback: sourceMessage.feedback,- feedbackMessageId: sourceMessage.id,- }- : {}),- });- }- }-- return messages.flatMap<InAppAiAgentMessage>((message) => {- const projectedMessage =- message.role === "assistant"- ? {- ...message,- content:- state.textByMessageId[message.id]?.nativeContent ??- message.content,- toolCalls: message.toolCalls?.filter((toolCall) => {- const placement = state.toolCallPlacements[toolCall.id];- return (- toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME ||- !placement ||- !messageIds.has(placement.anchorMessageId)- );- }),- }- : message;- const placements = placementsByAnchor.get(message.id);- if (!placements) {- return [projectedMessage];- }-- return [- projectedMessage,- ...placements- .sort((left, right) => left.order - right.order)- .map(({ message: placedMessage }) => placedMessage),- ];- });-}--function parseInAppAgentInterruptEvent(event: unknown) {- if (!event || typeof event !== "object") {- return null;- }-- if (!("name" in event) || event.name !== "on_interrupt") {- return null;- }-- const value = "value" in event ? event.value : undefined;- const parsedValue = typeof value === "string" ? parseJson(value) : value;- const interrupt = MastraSuspendEventSchema.safeParse(parsedValue);-- if (!interrupt.success) {- return null;- }-- return {- type: "tool_approval_request" as const,- toolCallId: interrupt.data.toolCallId,- toolName: interrupt.data.toolName,- args: interrupt.data.args,- runId: interrupt.data.runId,- } satisfies InAppAgentToolApprovalRequest;-}--function parseJson(value: string) {- try {- return JSON.parse(value) as unknown;- } catch {- return null;- }-}-function getInAppAgentUrl() {return `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`;}diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.ts b/web/src/features/in-app-agent/components/inAppAgentDisplay.clienttest.tssimilarity index 98%rename from web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.tsrename to web/src/features/in-app-agent/components/inAppAgentDisplay.clienttest.tsindex 7197468fdc..e0219f79b6 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.clienttest.ts+++ b/web/src/features/in-app-agent/components/inAppAgentDisplay.clienttest.ts@@ -4,7 +4,7 @@ import {projectInAppAgentMessagesForDisplay,recordInAppAgentMessagesForDisplay,recordInAppAgentToolCallForDisplay,-} from "./InAppAiAgentProvider";+} from "@/src/features/in-app-agent/lib/display";const assistantToolMessage = {id: "assistant-tools",@@ -20,7 +20,7 @@ const assistantToolMessage = {})),} satisfies AgUiMessage;-describe("in-app agent display order", () => {+describe("in-app agent display projection", () => {it("keeps consecutive tool calls with the same parent together", () => {const assistantMessage = {id: "assistant-tools",diff --git a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsxindex 1d887d7067..c684da6a43 100644--- a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx+++ b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.clienttest.tsx@@ -1,4 +1,4 @@-import { act, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";import { StrictMode } from "react";import type { InAppAgentPendingToolApproval } from "./InAppAiAgentProvider";@@ -149,6 +149,9 @@ function TestConsumer({</span><span data-testid="tool-call-ids">{toolCallIds.join(",")}</span><span data-testid="tool-result-ids">{toolResultIds.join(",")}</span>+ <button type="button" onClick={smoothStreaming.finishAnimation}>+ Stop display+ </button></>);}@@ -246,6 +249,41 @@ describe("useSmoothStreamingMessages", () => {expect(screen.getByTestId("animating")).toHaveTextContent("false");});+ it("shows cached history immediately when switching conversations", () => {+ const firstConversationText = "a".repeat(80);+ const cachedConversationText = "b".repeat(80);+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={1}+ messages={[userMessage, assistantMessage(firstConversationText)]}+ />,+ );+ runAllAnimationFrames();++ rerender(+ <TestConsumer+ liveMessageVersion={0}+ messages={[+ { id: "cached-user", role: "user", content: "Cached conversation" },+ {+ id: "cached-assistant",+ role: "assistant",+ content: cachedConversationText,+ },+ ]}+ />,+ );++ expect(screen.getByTestId("content")).toHaveTextContent(+ cachedConversationText,+ );+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ });+it("animates a live message that completes in one update", () => {const content ="This final response arrived atomically but should still be displayed smoothly.";@@ -276,39 +314,44 @@ describe("useSmoothStreamingMessages", () => {expect(screen.getByTestId("animating")).toHaveTextContent("false");});- it("matches the observed generation rate for the next text chunk", () => {+ it("finishes the local reveal immediately when the user stops a completed server run", () => {+ const content =+ "The server has already completed this response while the drawer is still revealing it.";const { rerender } = render(<TestConsumer liveMessageVersion={0} messages={[userMessage]} />,);- const emptyAssistantMessage = assistantMessage("");rerender(<TestConsumerliveMessageVersion={1}- messages={[userMessage, emptyAssistantMessage]}+ messages={[userMessage, assistantMessage(content)]}/>,);- act(() => {- vi.advanceTimersByTime(2_000);- });- const generatedContent = "x".repeat(200);- rerender(- <TestConsumer- liveMessageVersion={2}- messages={[userMessage, assistantMessage(generatedContent)]}- />,- );- advanceAnimationFrames(25);+ expect(screen.getByTestId("content")).not.toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("true");- const displayedLength =- screen.getByTestId("content-assistant").textContent?.length ?? 0;- expect(displayedLength).toBeGreaterThanOrEqual(75);- expect(displayedLength).toBeLessThanOrEqual(85);- runAllAnimationFrames();+ fireEvent.click(screen.getByRole("button", { name: "Stop display" }));++ expect(screen.getByTestId("content")).toHaveTextContent(content);+ expect(screen.getByTestId("animating")).toHaveTextContent("false");});- it("keeps pacing headroom when the next chunk arrives late", () => {+ /**+ * Replaces three earlier cases that pinned the EMA-only ceiling (observed+ * rate, late-chunk headroom, single-fast-chunk clamp). Those bounds were+ * derived from a *generation* rate, which is meaningless once text arrives in+ * whole compacted blocks: the backlog-aware floor dominates there, so+ * re-asserting the old ceilings would only restate the implementation.+ *+ * What is worth protecting is the user-visible regression the floor fixes. A+ * ~800-grapheme block at the 40 graphemes/second default crawled for ~20s,+ * which is what the background path publishes on every flush. The floor+ * recomputes from the remaining backlog each frame, so it eases out rather+ * than finishing on a hard deadline — hence a generous bound here. It is+ * still an order of magnitude away from the old behavior, which is the point.+ */+ it("reveals a whole compacted block progressively, not at the default crawl", () => {const { rerender } = render(<TestConsumer liveMessageVersion={0} messages={[userMessage]} />,);@@ -323,65 +366,37 @@ describe("useSmoothStreamingMessages", () => {vi.advanceTimersByTime(2_000);});- const generatedContent = "x".repeat(200);+ const generatedContent = "x".repeat(800);rerender(<TestConsumerliveMessageVersion={2}messages={[userMessage, assistantMessage(generatedContent)]}/>,);- advanceAnimationFrames(50);- const displayedLength =+ advanceAnimationFrames(1);+ const afterFirstFrame =screen.getByTestId("content-assistant").textContent?.length ?? 0;- expect(displayedLength).toBeGreaterThanOrEqual(155);- expect(displayedLength).toBeLessThanOrEqual(165);- expect(screen.getByTestId("animating")).toHaveTextContent("true");- runAllAnimationFrames();- });-- it("limits acceleration from one unusually fast chunk", () => {- const { rerender } = render(- <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,- );-- rerender(- <TestConsumer- liveMessageVersion={1}- messages={[userMessage, assistantMessage("")]}- />,- );- act(() => {- vi.advanceTimersByTime(2_000);- });- rerender(- <TestConsumer- liveMessageVersion={2}- messages={[userMessage, assistantMessage("x".repeat(100))]}- />,- );- act(() => {- vi.advanceTimersByTime(100);- });+ // Smoothed, not dumped.+ expect(afterFirstFrame).toBeGreaterThan(0);+ expect(afterFirstFrame).toBeLessThan(generatedContent.length);++ let frames = 1;+ const maxFrames = Math.ceil(5_000 / 40);+ while (+ frames < maxFrames &&+ (screen.getByTestId("content-assistant").textContent?.length ?? 0) <+ generatedContent.length+ ) {+ advanceAnimationFrames(1);+ frames += 1;+ }- rerender(- <TestConsumer- liveMessageVersion={3}- messages={[userMessage, assistantMessage("x".repeat(200))]}- />,+ expect(screen.getByTestId("content-assistant")).toHaveTextContent(+ generatedContent,);- const displayedBeforeFastChunk =- screen.getByTestId("content-assistant").textContent?.length ?? 0;- advanceAnimationFrames(25);-- const displayedAfterOneSecond =- screen.getByTestId("content-assistant").textContent?.length ?? 0;- expect(- displayedAfterOneSecond - displayedBeforeFastChunk,- ).toBeGreaterThanOrEqual(45);- expect(- displayedAfterOneSecond - displayedBeforeFastChunk,- ).toBeLessThanOrEqual(51);+ // 800 graphemes at the 40/s default would have needed ~500 frames (~20s).+ expect(frames).toBeLessThan(maxFrames);runAllAnimationFrames();});@@ -685,6 +700,36 @@ describe("useSmoothStreamingMessages", () => {);});+ it("shows an approval restored from history without pacing the restored tools", () => {+ // A pending approval survives a refresh, so hydration delivers it with no+ // live publication. Pacing that schedules an appearance transition for every+ // tool call in the restored history at 2/second, and the approval card sorts+ // last — so it waited behind the whole backlog while `isAnimating` kept the+ // drawer looking like the run was still executing.+ const { rerender } = render(+ <TestConsumer liveMessageVersion={0} messages={[userMessage]} />,+ );++ rerender(+ <TestConsumer+ liveMessageVersion={0}+ messages={[+ userMessage,+ assistantToolMessage(["tool-1", "tool-2", "tool-3"], true),+ ]}+ pendingToolApprovals={[pendingToolApproval("approval-1", "pending")]}+ />,+ );++ // Hydration is applied whole: the restored tools and the approval are all+ // visible on the first render, with nothing left animating.+ expect(screen.getByTestId("tool-call-ids")).toHaveTextContent(+ "tool-1,tool-2,tool-3",+ );+ expect(screen.getByTestId("approval-ids")).toHaveTextContent("approval-1");+ expect(screen.getByTestId("animating")).toHaveTextContent("false");+ });+it("does not animate for reduced-motion users", () => {prefersReducedMotion = true;const content =diff --git a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.tsindex 9fb9ccad08..0648862154 100644--- a/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts+++ b/web/src/features/in-app-agent/components/useSmoothStreamingMessages.ts@@ -13,6 +13,7 @@ const PACING_EMA_WEIGHT = 0.35;const PACING_TARGET_UTILIZATION = 0.8;const MAX_PACING_INCREASE_FACTOR = 1.2;const MIN_SMOOTHED_GRAPHEMES = 16;+const CATCH_UP_TARGET_MS = 1_500;const TOOL_TRANSITION_INTERVAL_MS = 500;const MIN_TOOL_RUNNING_DURATION_MS = 750;@@ -154,8 +155,12 @@ export function useSmoothStreamingMessages({state.toolDisplayById,);const runningToolCallIds = getRunningToolCallIds(state.toolDisplayById);+ const finishAnimation = () => {+ dispatch({ type: "finish", nowMs: performance.now() });+ };return {+ finishAnimation,isAnimating,pendingToolApprovals: state.displayedToolApprovals,runningToolCallIds,@@ -216,8 +221,10 @@ function enqueueStreamingUpdate(action: Extract<SmoothStreamingAction, { type: "enqueue" }>,) {const nextMessages = snapshotMessages(action.messages);+ // Revisions increase within one live session. A reset to a lower revision+ // installs hydrated history from a different session/conversation.const isLivePublication =- action.liveMessageVersion !== state.liveMessageVersion;+ action.liveMessageVersion > state.liveMessageVersion;const isLoadingOnlyUpdate =!isLivePublication &&areMessagesEqualExceptLoading(state.targetMessages, nextMessages);@@ -248,10 +255,18 @@ function enqueueStreamingUpdate(publishedTexts,action.canAnimate,);- const approvalsChanged = !areToolApprovalsEqual(- state.targetToolApprovals,- action.pendingToolApprovals,- );+ // Only a *live* approval change is worth pacing. Hydration delivers approvals+ // too — a pending approval survives a refresh by design — and pacing those+ // schedules an "appearance" transition for every tool call in the restored+ // history at 2/second. The approval card sorts last, so it waits behind the+ // entire backlog while `isAnimating` keeps the drawer looking busy: the run+ // reads as still executing and the card never arrives.+ const approvalsChanged =+ isLivePublication &&+ !areToolApprovalsEqual(+ state.targetToolApprovals,+ action.pendingToolApprovals,+ );if (!action.canAnimate ||@@ -326,11 +341,23 @@ function advanceStreamingFrame(state: SmoothStreamingState) {const remainingGraphemes = splitGraphemes(pendingText.targetText.slice(pendingText.displayedText.length),);+ const pacedRate =+ state.textPacingByMessageId[pendingText.targetMessage.id]+ ?.graphemesPerSecond ?? DEFAULT_GRAPHEMES_PER_SECOND;+ // Backlog-aware catch-up floor. The EMA estimates a *generation* rate from+ // observed appends, which is meaningless when text arrives in whole+ // compacted blocks: a single ~800-grapheme publication would crawl for ~20s+ // at the default rate. Guaranteeing the backlog drains within+ // CATCH_UP_TARGET_MS keeps the reveal smooth without pretending to pace+ // something that already finished. It eases out naturally as the backlog+ // shrinks, and it never fires on token-level streams, where the backlog is+ // a few graphemes at a time.+ const rate = Math.max(+ pacedRate,+ remainingGraphemes.length / (CATCH_UP_TARGET_MS / 1_000),+ );const graphemeBudget =- state.animation.graphemeBudget +- (state.textPacingByMessageId[pendingText.targetMessage.id]- ?.graphemesPerSecond ?? DEFAULT_GRAPHEMES_PER_SECOND) *- (FRAME_DURATION_MS / 1_000);+ state.animation.graphemeBudget + rate * (FRAME_DURATION_MS / 1_000);const graphemesThisFrame = Math.floor(graphemeBudget);const nextText =pendingText.displayedText +diff --git a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/features/in-app-agent/components/utils/utils.clienttest.tsindex 94a703e68d..8d36dfa239 100644--- a/web/src/features/in-app-agent/components/utils/utils.clienttest.ts+++ b/web/src/features/in-app-agent/components/utils/utils.clienttest.ts@@ -6,7 +6,6 @@ import {isInAppAgentRateLimited,type InAppAiAgentMessage,} from "./utils";-describe("getInAppAgentError", () => {const now = new Date("2026-07-08T20:00:54.997Z").getTime();const rateLimitError = {diff --git a/web/src/features/in-app-agent/lib/backgroundAgentClient.ts b/web/src/features/in-app-agent/lib/backgroundAgentClient.tsnew file mode 100644index 0000000000..34d61ecb3a--- /dev/null+++ b/web/src/features/in-app-agent/lib/backgroundAgentClient.ts@@ -0,0 +1,374 @@+import { AbstractAgent, type RunAgentInput } from "@ag-ui/client";+import type { BaseEvent } from "@ag-ui/core";+import { Observable } from "rxjs";++import { InAppAgentRunStatus } from "@langfuse/shared";+import {+ InAppAgentWatchFrameSchema,+ type AgUiMessage,+ type AgUiRunAgentInput,+ type InAppAgentWatchFrame,+} from "@langfuse/shared/in-app-agent";++import { env } from "@/src/env.mjs";+import { parseSSEBuffer } from "@/src/hooks/useSSEDashboardQuery";+import { BackgroundExecutionConnectionError } from "./backgroundExecutionErrors";++export type InAppAgentRunStatusUpdate = Extract<+ InAppAgentWatchFrame,+ { type: "status" }+>;++const WATCH_RECONNECT_ATTEMPTS = 5;+const WATCH_RECONNECT_BASE_DELAY_MS = 500;++class InvalidWatchFrameError extends BackgroundExecutionConnectionError {+ constructor() {+ super("Assistant watch returned an invalid frame", { retryable: false });+ }+}++function sleep(ms: number, signal: AbortSignal): Promise<void> {+ return new Promise((resolve) => {+ const timeout = setTimeout(resolve, ms);+ signal.addEventListener(+ "abort",+ () => {+ clearTimeout(timeout);+ resolve();+ },+ { once: true },+ );+ });+}++type StartRunFn = (params: {+ message: string;+ context: AgUiRunAgentInput["context"];+}) => Promise<{ runId: string }>;++// AG-UI's Zod v3 declarations resolve as unknown against this repo's Zod v4.+function asAgUiRunAgentInput(input: RunAgentInput): AgUiRunAgentInput {+ return input as unknown as AgUiRunAgentInput;+}++// AG-UI transport backed by a tRPC start mutation and persisted event tail.+export class InAppAgentBackgroundClient extends AbstractAgent {+ private readonly projectId: string;+ private readonly conversationId: string;+ private readonly startRun: StartRunFn;+ private onStatus?: (status: InAppAgentRunStatusUpdate) => void;+ private onCursor?: (cursor: number) => void;+ private cursor: number;+ private abortController = new AbortController();++ constructor(config: {+ projectId: string;+ conversationId: string;+ /** High-water `sequenceNumber` of the hydrated history. */+ cursor: number;+ startRun: StartRunFn;+ onStatus?: (status: InAppAgentRunStatusUpdate) => void;+ threadId?: string;+ initialMessages?: AgUiMessage[];+ initialState?: unknown;+ }) {+ super({+ threadId: config.threadId,+ initialMessages: config.initialMessages as never,+ initialState: config.initialState as never,+ });++ this.projectId = config.projectId;+ this.conversationId = config.conversationId;+ this.cursor = config.cursor;+ this.startRun = config.startRun;+ this.onStatus = config.onStatus;+ }++ run(input: RunAgentInput): Observable<BaseEvent> {+ return new Observable<BaseEvent>((subscriber) => {+ const controller = this.resetAbortController();++ const runInput = asAgUiRunAgentInput(input);+ const message = getLastUserMessageContent(runInput.messages);++ if (!message) {+ subscriber.error(new Error("A user message is required"));+ return;+ }++ this.startRun({ message, context: runInput.context })+ .then(({ runId }) => {+ this.onStatus?.({+ type: "status",+ runId,+ status: InAppAgentRunStatus.QUEUED,+ errorCode: null,+ cancelRequested: false,+ });+ return this.streamWithReconnects(subscriber, controller.signal);+ })+ .catch((error: unknown) => {+ if (controller.signal.aborted) {+ subscriber.complete();+ return;+ }+ subscriber.error(error);+ });++ return () => {+ controller.abort();+ };+ });+ }++ connect(): Observable<BaseEvent> {+ return new Observable<BaseEvent>((subscriber) => {+ const controller = this.resetAbortController();++ this.streamWithReconnects(subscriber, controller.signal).catch(+ (error: unknown) => {+ if (controller.signal.aborted) {+ subscriber.complete();+ return;+ }+ subscriber.error(error);+ },+ );++ return () => {+ controller.abort();+ };+ });+ }++ // Stop observing without cancelling the server run.+ abortRun(): void {+ this.abortController.abort();+ super.abortRun();+ }++ // Hydration must set messages and cursor from the same persisted snapshot.+ setCursor(cursor: number): void {+ this.cursor = cursor;+ }++ setStatusListener(+ listener?: (status: InAppAgentRunStatusUpdate) => void,+ ): void {+ this.onStatus = listener;+ }++ setCursorListener(listener?: (cursor: number) => void): void {+ this.onCursor = listener;+ }++ private resetAbortController(): AbortController {+ this.abortController.abort();+ this.abortController = new AbortController();+ return this.abortController;+ }++ private async streamWithReconnects(+ subscriber: {+ next: (event: BaseEvent) => void;+ complete: () => void;+ },+ signal: AbortSignal,+ ): Promise<void> {+ let consecutiveFailures = 0;+ let consecutiveQuietConnections = 0;++ while (!signal.aborted) {+ const cursorBeforeRequest = this.cursor;+ let sawDoneFrame: boolean;++ try {+ sawDoneFrame = await this.streamOnce(subscriber, signal);+ } catch (error) {+ if (signal.aborted) {+ break;+ }++ if (+ error instanceof BackgroundExecutionConnectionError &&+ !error.retryable+ ) {+ throw error;+ }++ consecutiveFailures += 1;++ // Give up only once retrying has stopped looking like a blip;+ // the run itself keeps executing regardless of the browser.+ if (consecutiveFailures > WATCH_RECONNECT_ATTEMPTS) {+ throw new BackgroundExecutionConnectionError(getErrorMessage(error), {+ retryable: true,+ cause: error,+ });+ }++ await sleep(+ WATCH_RECONNECT_BASE_DELAY_MS * consecutiveFailures,+ signal,+ );+ continue;+ }++ if (sawDoneFrame) {+ subscriber.complete();+ return;+ }++ consecutiveFailures = 0;++ if (this.cursor !== cursorBeforeRequest) {+ consecutiveQuietConnections = 0;+ continue;+ }++ consecutiveQuietConnections += 1;+ await sleep(+ WATCH_RECONNECT_BASE_DELAY_MS *+ Math.min(consecutiveQuietConnections, WATCH_RECONNECT_ATTEMPTS),+ signal,+ );+ }++ subscriber.complete();+ }++ /** Returns whether the server signalled that there is nothing left to watch. */+ private async streamOnce(+ subscriber: { next: (event: BaseEvent) => void },+ signal: AbortSignal,+ ): Promise<boolean> {+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";+ const url = new URL(+ `${basePath}/api/in-app-agent/watch`,+ window.location.origin,+ );+ url.searchParams.set("projectId", this.projectId);+ url.searchParams.set("conversationId", this.conversationId);+ url.searchParams.set("cursor", String(this.cursor));++ const response = await fetch(url.toString(), {+ method: "GET",+ headers: { Accept: "text/event-stream" },+ signal,+ });++ if (!response.ok) {+ const message = await readErrorMessage(response);+ if (+ response.status >= 400 &&+ response.status < 500 &&+ response.status !== 408 &&+ response.status !== 429+ ) {+ throw new BackgroundExecutionConnectionError(message, {+ retryable: false,+ });+ }+ throw new Error(message);+ }++ const reader = response.body?.getReader();++ if (!reader) {+ throw new Error("The assistant stream is unavailable");+ }++ const decoder = new TextDecoder();+ let buffer = "";++ while (!signal.aborted) {+ const { done, value } = await reader.read();++ if (done) {+ return false;+ }++ buffer += decoder.decode(value, { stream: true });+ const { events, remaining } = parseSSEBuffer(buffer);+ buffer = remaining;++ for (const sseEvent of events) {+ let payload: unknown;+ try {+ payload = JSON.parse(sseEvent.data) as unknown;+ } catch {+ throw new InvalidWatchFrameError();+ }+ const frame = InAppAgentWatchFrameSchema.safeParse(payload);++ if (!frame.success) {+ throw new InvalidWatchFrameError();+ }++ if (frame.data.type === "done") {+ return true;+ }++ if (frame.data.type === "status") {+ // Run status is not an AG-UI event; it drives the drawer's own+ // "working" / failure rendering.+ this.onStatus?.(frame.data);+ continue;+ }++ if (frame.data.type === "error") {+ // A server-side tail failure, not a run failure. Reconnecting with+ // the cursor is the correct response.+ throw new Error(frame.data.message);+ }++ this.cursor = frame.data.sequenceNumber;+ this.onCursor?.(this.cursor);+ subscriber.next(frame.data.event as unknown as BaseEvent);+ }+ }++ return false;+ }+}++function getErrorMessage(error: unknown): string {+ return error instanceof Error+ ? error.message+ : "Assistant watch connection failed";+}++function getLastUserMessageContent(+ messages: AgUiRunAgentInput["messages"],+): string | undefined {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];++ if (message?.role === "user" && typeof message.content === "string") {+ return message.content;+ }+ }++ return undefined;+}++async function readErrorMessage(response: Response): Promise<string> {+ try {+ const body: unknown = await response.json();++ if (+ body &&+ typeof body === "object" &&+ "error" in body &&+ typeof body.error === "string"+ ) {+ return body.error;+ }+ } catch {+ // Fall through to the generic message below.+ }++ return "The assistant is unavailable right now";+}diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionErrors.ts b/web/src/features/in-app-agent/lib/backgroundExecutionErrors.tsnew file mode 100644index 0000000000..b72fa7059a--- /dev/null+++ b/web/src/features/in-app-agent/lib/backgroundExecutionErrors.ts@@ -0,0 +1,11 @@+export class BackgroundExecutionConnectionError extends Error {+ readonly retryable: boolean;++ constructor(+ message: string,+ options: { retryable: boolean; cause?: unknown },+ ) {+ super(message, options.cause === undefined ? undefined : options);+ this.retryable = options.retryable;+ }+}diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionFlag.ts b/web/src/features/in-app-agent/lib/backgroundExecutionFlag.tsnew file mode 100644index 0000000000..a88bdbf14f--- /dev/null+++ b/web/src/features/in-app-agent/lib/backgroundExecutionFlag.ts@@ -0,0 +1,14 @@+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/backgroundExecutionSession.clienttest.ts b/web/src/features/in-app-agent/lib/backgroundExecutionSession.clienttest.tsnew file mode 100644index 0000000000..1d59db2293--- /dev/null+++ b/web/src/features/in-app-agent/lib/backgroundExecutionSession.clienttest.ts@@ -0,0 +1,1267 @@+import { EventType } from "@ag-ui/core";+import type { AgentSubscriber } from "@ag-ui/client";+import { afterEach, describe, expect, it, vi } from "vitest";++import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "@langfuse/shared";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";++import { InAppAgentBackgroundClient } from "./backgroundAgentClient";+import {+ createInAppAgentDisplayState,+ projectInAppAgentMessagesForDisplay,+ recordInAppAgentMessagesForDisplay,+} from "./display";+import { BackgroundExecutionConnectionError } from "./backgroundExecutionErrors";+import {+ BackgroundExecutionSessionController,+ type BackgroundExecutionView,+} from "./backgroundExecutionSession";++const message = {+ id: "message-1",+ role: "assistant",+ content: "persisted",+} satisfies AgUiMessage;++const runningView = {+ messages: [message],+ displayState: createInAppAgentDisplayState(),+ eventCursor: 7,+ currentRun: {+ id: "run-1",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [],+} satisfies Omit<+ BackgroundExecutionView,+ "attachment" | "cancelStatus" | "liveMessageRevision"+>;++const userMessage = {+ id: "user-message",+ role: "user",+ content: "Add a cost widget to this dashboard",+} satisfies AgUiMessage;++const explanationMessage = {+ id: "assistant-explanation",+ role: "assistant",+ content: "I will create the widget and then add it to the dashboard.",+} satisfies AgUiMessage;++const createWidgetMessage = {+ id: "create-widget-call",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "create-widget",+ type: "function",+ function: {+ name: "langfuse_createDashboardWidget",+ arguments: '{"name":"Cost by Model"}',+ },+ },+ ],+} satisfies AgUiMessage;++const createWidgetResult = {+ id: "create-widget-result",+ role: "tool",+ toolCallId: "create-widget",+ content: '{"id":"widget-1"}',+} satisfies AgUiMessage;++const addPlacementMessage = {+ id: "add-placement-call",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "add-placement",+ type: "function",+ function: {+ name: "langfuse_addDashboardPlacement",+ arguments: '{"widgetId":"widget-1"}',+ },+ },+ ],+} satisfies AgUiMessage;++const addPlacementResult = {+ id: "add-placement-result",+ role: "tool",+ toolCallId: "add-placement",+ content: '{"id":"placement-1"}',+} satisfies AgUiMessage;++const finalMessage = {+ id: "assistant-final",+ role: "assistant",+ content: "Done. I created and placed the Cost by Model widget.",+} satisfies AgUiMessage;++function createAgent() {+ return {+ messages: [],+ setMessages: vi.fn(),+ setCursor: vi.fn(),+ runAgent: vi.fn().mockResolvedValue(undefined),+ connectAgent: vi.fn().mockResolvedValue(undefined),+ abortRun: vi.fn(),+ subscribe: vi.fn(() => ({ unsubscribe: vi.fn() })),+ };+}++afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe("BackgroundExecutionSessionController", () => {+ it("hydrates messages and cursor before attaching", async () => {+ let subscriber: AgentSubscriber | undefined;+ const agent = {+ ...createAgent(),+ subscribe: vi.fn((nextSubscriber: AgentSubscriber) => {+ subscriber = nextSubscriber;+ return { unsubscribe: vi.fn() };+ }),+ setMessages: vi.fn((messages: AgUiMessage[]) => {+ const onMessagesChanged = subscriber?.onMessagesChanged as+ | ((params: never) => void)+ | undefined;+ onMessagesChanged?.({ messages } as never);+ }),+ connectAgent: vi.fn(() => new Promise<unknown>(() => undefined)),+ };+ const hydrate = vi.fn().mockResolvedValue(runningView);+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate,+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ await session.hydrateAndAttach();++ expect(agent.setMessages).toHaveBeenCalledWith([message]);+ expect(agent.setCursor).toHaveBeenCalledWith(7);+ expect(agent.connectAgent).toHaveBeenCalledOnce();+ expect(hydrate).toHaveBeenCalledOnce();+ expect(session.getSnapshot()).toMatchObject({+ messages: [message],+ eventCursor: 7,+ liveMessageRevision: 0,+ });+ });++ it("detaches observation without cancelling the server run", async () => {+ const agent = {+ ...createAgent(),+ connectAgent: vi.fn(() => new Promise<unknown>(() => undefined)),+ };+ const cancelRun = vi.fn();+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun,+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ session.detach();++ expect(agent.abortRun).toHaveBeenCalledOnce();+ expect(cancelRun).not.toHaveBeenCalled();+ expect(session.getSnapshot()).toMatchObject({+ attachment: { status: "detached" },+ currentRun: runningView.currentRun,+ });++ await session.hydrateAndAttach();++ expect(agent.connectAgent).toHaveBeenCalledTimes(2);+ expect(session.getSnapshot().attachment).toEqual({ status: "attached" });+ expect(session.getSnapshot().currentRun).toEqual(runningView.currentRun);+ expect(session.getSnapshot().messages).toEqual([message]);+ });++ it("stays detached when cancellation finishes after observation stopped", async () => {+ let resolveCancel: () => void = () => undefined;+ const agent = {+ ...createAgent(),+ connectAgent: vi.fn(() => new Promise<unknown>(() => undefined)),+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveCancel = resolve;+ }),+ ),+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ const cancelling = session.cancel();+ session.detach();+ resolveCancel();+ await cancelling;++ expect(agent.connectAgent).toHaveBeenCalledOnce();+ expect(session.getSnapshot().attachment).toEqual({ status: "detached" });+ });++ it("cancels the active server run", async () => {+ const agent = createAgent();+ const cancelRun = vi.fn().mockResolvedValue(undefined);+ const onSettled = vi.fn();+ const cancelledView = {+ ...runningView,+ currentRun: {+ ...runningView.currentRun,+ status: InAppAgentRunStatus.CANCELLED,+ },+ pendingToolApprovals: [],+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(cancelledView),+ cancelRun,+ decideApproval: vi.fn(),+ onSettled,+ initialView: { currentRun: runningView.currentRun },+ });++ await session.cancel();++ expect(cancelRun).toHaveBeenCalledWith("run-1");+ expect(session.getSnapshot().currentRun?.status).toBe(+ InAppAgentRunStatus.CANCELLED,+ );+ expect(agent.connectAgent).not.toHaveBeenCalled();+ expect(onSettled).toHaveBeenCalledOnce();+ });++ it("restores cancellation controls when the mutation fails", async () => {+ const mutationError = new Error("cancel failed");+ const session = new BackgroundExecutionSessionController({+ agent: createAgent(),+ hydrate: vi.fn(),+ cancelRun: vi.fn().mockRejectedValue(mutationError),+ decideApproval: vi.fn(),+ initialView: { currentRun: runningView.currentRun },+ });++ await expect(session.cancel()).rejects.toBe(mutationError);++ expect(session.getSnapshot()).toMatchObject({+ currentRun: {+ id: "run-1",+ cancelRequested: false,+ },+ cancelStatus: "idle",+ attachment: { status: "detached" },+ });+ });++ it("keeps a terminal status delivered while the cancel mutation is in flight", async () => {+ let statusListener:+ | ((status: {+ runId: string;+ status: InAppAgentRunStatus;+ errorCode?: string | null;+ cancelRequested?: boolean;+ }) => void)+ | undefined;+ const agent = {+ ...createAgent(),+ setStatusListener: vi.fn((listener?: typeof statusListener) => {+ statusListener = listener;+ }),+ };+ let resolveCancel: () => void = () => undefined;+ // Deferred so the post-command refresh cannot mask the view cancel() wrote.+ let resolveHydrate: (view: typeof runningView) => void = () => undefined;+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn(+ () =>+ new Promise<typeof runningView>((resolve) => {+ resolveHydrate = resolve;+ }),+ ),+ cancelRun: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveCancel = resolve;+ }),+ ),+ decideApproval: vi.fn(),+ initialView: { currentRun: runningView.currentRun },+ });++ const cancelling = session.cancel();+ statusListener?.({+ runId: "run-1",+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ cancelRequested: true,+ });+ resolveCancel();++ await vi.waitFor(() => {+ expect(session.getSnapshot().cancelStatus).toBe("idle");+ });+ expect(session.getSnapshot().currentRun).toEqual({+ id: "run-1",+ status: InAppAgentRunStatus.CANCELLED,+ errorCode: InAppAgentRunErrorCode.CANCELLED,+ cancelRequested: true,+ });++ resolveHydrate(runningView);+ await cancelling;+ });++ it("does not stamp cancellation onto a superseding run", async () => {+ let statusListener:+ | ((status: {+ runId: string;+ status: InAppAgentRunStatus;+ errorCode?: string | null;+ cancelRequested?: boolean;+ }) => void)+ | undefined;+ const agent = {+ ...createAgent(),+ setStatusListener: vi.fn((listener?: typeof statusListener) => {+ statusListener = listener;+ }),+ };+ let resolveCancel: () => void = () => undefined;+ let resolveHydrate: (view: typeof runningView) => void = () => undefined;+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn(+ () =>+ new Promise<typeof runningView>((resolve) => {+ resolveHydrate = resolve;+ }),+ ),+ cancelRun: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveCancel = resolve;+ }),+ ),+ decideApproval: vi.fn(),+ initialView: { currentRun: runningView.currentRun },+ });++ const cancelling = session.cancel();+ statusListener?.({+ runId: "run-2",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ });+ resolveCancel();++ await vi.waitFor(() => {+ expect(session.getSnapshot().cancelStatus).toBe("idle");+ });+ expect(session.getSnapshot().currentRun).toEqual({+ id: "run-2",+ status: InAppAgentRunStatus.RUNNING,+ errorCode: null,+ cancelRequested: false,+ });++ resolveHydrate(runningView);+ await cancelling;+ });++ it("keeps an accepted cancellation when attachment refresh fails", async () => {+ const refreshError = new Error("refresh failed");+ const agent = {+ ...createAgent(),+ connectAgent: vi.fn(() => new Promise<unknown>(() => undefined)),+ };+ const hydrate = vi+ .fn()+ .mockResolvedValueOnce(runningView)+ .mockRejectedValueOnce(refreshError);+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate,+ cancelRun: vi.fn().mockResolvedValue(undefined),+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ await expect(session.cancel()).resolves.toBeUndefined();++ expect(agent.abortRun).toHaveBeenCalledOnce();+ expect(hydrate).toHaveBeenCalledTimes(2);+ expect(session.getSnapshot()).toMatchObject({+ currentRun: {+ id: "run-1",+ cancelRequested: true,+ },+ attachment: {+ status: "error",+ error: refreshError,+ },+ });+ });++ it("keeps an accepted approval resolved when attachment refresh fails", async () => {+ const refreshError = new Error("refresh failed");+ const session = new BackgroundExecutionSessionController({+ agent: createAgent(),+ hydrate: vi.fn().mockRejectedValue(refreshError),+ cancelRun: vi.fn(),+ decideApproval: vi.fn().mockResolvedValue(undefined),+ initialView: {+ currentRun: {+ ...runningView.currentRun,+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ },+ pendingToolApprovals: [+ {+ runId: "run-1",+ status: "pending",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "dangerousTool",+ runId: "run-1",+ },+ },+ ],+ },+ });++ await expect(+ session.decide({+ runId: "run-1",+ toolCallId: "tool-call-1",+ approved: true,+ }),+ ).resolves.toBeUndefined();++ expect(session.getSnapshot()).toMatchObject({+ pendingToolApprovals: [],+ attachment: {+ status: "error",+ error: refreshError,+ },+ });+ });++ it("keeps a rejected approval mutation actionable", async () => {+ let rejectDecision: (error: Error) => void = () => undefined;+ const decision = new Promise<void>((_, reject) => {+ rejectDecision = reject;+ });+ const session = new BackgroundExecutionSessionController({+ agent: createAgent(),+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn(() => decision),+ initialView: {+ currentRun: {+ ...runningView.currentRun,+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ },+ pendingToolApprovals: [+ {+ runId: "run-1",+ status: "pending",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "dangerousTool",+ runId: "run-1",+ },+ },+ ],+ },+ });++ const result = session.decide({+ runId: "run-1",+ toolCallId: "tool-call-1",+ approved: true,+ });++ expect(session.getSnapshot().pendingToolApprovals).toMatchObject([+ { status: "submitting" },+ ]);++ const decisionError = new Error("decision failed");+ rejectDecision(decisionError);+ await expect(result).rejects.toBe(decisionError);+ expect(session.getSnapshot().pendingToolApprovals).toMatchObject([+ { status: "pending" },+ ]);+ });++ it("keeps run-start failures outside attachment state", async () => {+ const startError = new Error("start failed");+ const session = new BackgroundExecutionSessionController({+ agent: {+ ...createAgent(),+ runAgent: vi.fn().mockRejectedValue(startError),+ },+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await expect(session.run({ context: [] } as never)).rejects.toBe(+ startError,+ );+ expect(session.getSnapshot().attachment).toEqual({+ status: "detached",+ });+ });++ it("surfaces reconnect exhaustion from a newly started run", async () => {+ const watchError = new BackgroundExecutionConnectionError("watch failed", {+ retryable: true,+ });+ const session = new BackgroundExecutionSessionController({+ agent: {+ ...createAgent(),+ runAgent: vi.fn().mockRejectedValue(watchError),+ },+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await expect(session.run({ context: [] } as never)).rejects.toBe(+ watchError,+ );+ expect(session.getSnapshot().attachment).toMatchObject({+ status: "error",+ retryable: true,+ });+ });++ it("owns streamed messages and approval state", async () => {+ let subscriber: AgentSubscriber | undefined;+ const unsubscribe = vi.fn();+ const agent = {+ ...createAgent(),+ subscribe: vi.fn((nextSubscriber: AgentSubscriber) => {+ subscriber = nextSubscriber;+ return { unsubscribe };+ }),+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await subscriber?.onMessagesChanged?.({+ messages: [message],+ } as never);+ await subscriber?.onCustomEvent?.({+ event: {+ type: EventType.CUSTOM,+ name: "on_interrupt",+ value: {+ type: "mastra_suspend",+ toolCallId: "tool-call-1",+ toolName: "dangerousTool",+ runId: "run-1",+ },+ },+ } as never);++ expect(session.getSnapshot()).toMatchObject({+ messages: [message],+ liveMessageRevision: 1,+ pendingToolApprovals: [+ {+ runId: "run-1",+ status: "pending",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ },+ },+ ],+ });++ await subscriber?.onToolCallResultEvent?.({+ event: { toolCallId: "tool-call-1" },+ } as never);++ expect(session.getSnapshot().pendingToolApprovals).toEqual([]);++ session.dispose();++ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("reattaches an accepted approval from a coherent persisted snapshot", async () => {+ let installedMessages: AgUiMessage[] = [];+ let installedCursor = -1;+ const attachedSnapshots: Array<{+ messages: AgUiMessage[];+ cursor: number;+ }> = [];+ const agent = {+ ...createAgent(),+ setMessages: vi.fn((messages: AgUiMessage[]) => {+ installedMessages = messages;+ }),+ setCursor: vi.fn((cursor: number) => {+ installedCursor = cursor;+ }),+ connectAgent: vi.fn(() => {+ attachedSnapshots.push({+ messages: installedMessages,+ cursor: installedCursor,+ });+ return new Promise<unknown>(() => undefined);+ }),+ abortRun: vi.fn(),+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn().mockResolvedValue(undefined),+ });++ await session.hydrateAndAttach();+ await session.decide({+ runId: "parked-run",+ toolCallId: "tool-call-1",+ approved: true,+ });++ expect(attachedSnapshots).toEqual([+ { messages: [message], cursor: 7 },+ { messages: [message], cursor: 7 },+ ]);+ expect(agent.abortRun).toHaveBeenCalledOnce();+ expect(session.getSnapshot()).toMatchObject({+ messages: [message],+ eventCursor: 7,+ attachment: { status: "attached" },+ });+ });++ it("converges sequential approval continuations to the persisted transcript", async () => {+ let subscriber: AgentSubscriber | undefined;+ let resolveCreateRun: () => void = () => undefined;+ let resolvePlacementRun: () => void = () => undefined;+ const createRun = new Promise<void>((resolve) => {+ resolveCreateRun = resolve;+ });+ const placementRun = new Promise<void>((resolve) => {+ resolvePlacementRun = resolve;+ });+ const messagesBeforeApproval = [userMessage, explanationMessage];+ const messagesAfterCreate = [+ ...messagesBeforeApproval,+ createWidgetMessage,+ createWidgetResult,+ ];+ const finalPersistedMessages = [+ ...messagesAfterCreate,+ addPlacementMessage,+ addPlacementResult,+ finalMessage,+ ];+ let phase:+ | "before-create"+ | "creating"+ | "awaiting-placement"+ | "placing"+ | "complete" = "before-create";+ const hydrate = vi.fn(async () => {+ if (phase === "creating") {+ return {+ ...runningView,+ messages: messagesBeforeApproval,+ currentRun: { ...runningView.currentRun, id: "create-run" },+ };+ }++ if (phase === "awaiting-placement") {+ return {+ ...runningView,+ messages: messagesAfterCreate,+ currentRun: {+ ...runningView.currentRun,+ id: "create-run",+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ },+ };+ }++ if (phase === "placing") {+ return {+ ...runningView,+ messages: messagesAfterCreate,+ currentRun: { ...runningView.currentRun, id: "placement-run" },+ };+ }++ return {+ ...runningView,+ messages: finalPersistedMessages,+ currentRun: {+ ...runningView.currentRun,+ id: "placement-run",+ status: InAppAgentRunStatus.SUCCEEDED,+ },+ };+ });+ const agent = {+ ...createAgent(),+ subscribe: vi.fn((nextSubscriber: AgentSubscriber) => {+ subscriber = nextSubscriber;+ return { unsubscribe: vi.fn() };+ }),+ connectAgent: vi+ .fn()+ .mockImplementationOnce(() => createRun)+ .mockImplementationOnce(() => placementRun),+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate,+ cancelRun: vi.fn(),+ decideApproval: vi.fn(async ({ toolCallId }) => {+ phase = toolCallId === "create-widget" ? "creating" : "placing";+ }),+ initialView: {+ messages: messagesBeforeApproval,+ currentRun: {+ ...runningView.currentRun,+ id: "approval-run",+ status: InAppAgentRunStatus.AWAITING_APPROVAL,+ },+ },+ });++ await session.decide({+ runId: "approval-run",+ toolCallId: "create-widget",+ approved: true,+ });+ await subscriber?.onMessagesChanged?.({+ messages: messagesAfterCreate,+ } as never);+ phase = "awaiting-placement";+ resolveCreateRun();+ await vi.waitFor(() => {+ expect(session.getSnapshot().attachment.status).toBe("detached");+ });+ expect(session.getSnapshot().messages).toEqual(messagesAfterCreate);++ await session.decide({+ runId: "create-run",+ toolCallId: "add-placement",+ approved: true,+ });+ await subscriber?.onMessagesChanged?.({+ // Reproduce the live-only loss of the previously completed create call.+ messages: [+ ...messagesBeforeApproval,+ addPlacementMessage,+ addPlacementResult,+ finalMessage,+ ],+ } as never);+ phase = "complete";+ resolvePlacementRun();+ await vi.waitFor(() => {+ expect(session.getSnapshot().attachment.status).toBe("detached");+ });++ expect(session.getSnapshot().messages).toEqual(finalPersistedMessages);+ });++ it("keeps the server run active and can retry when observation fails", async () => {+ const onError = vi.fn();+ const agent = {+ ...createAgent(),+ connectAgent: vi+ .fn()+ .mockRejectedValueOnce(+ new BackgroundExecutionConnectionError("watch failed", {+ retryable: true,+ }),+ )+ .mockImplementationOnce(() => new Promise<unknown>(() => undefined)),+ };+ const session = new BackgroundExecutionSessionController({+ agent,+ hydrate: vi.fn().mockResolvedValue(runningView),+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ onError,+ });++ await session.hydrateAndAttach();+ await vi.waitFor(() => {+ expect(onError).toHaveBeenCalledOnce();+ });++ expect(session.getSnapshot()).toMatchObject({+ attachment: {+ status: "error",+ retryable: true,+ },+ currentRun: runningView.currentRun,+ });++ await session.hydrateAndAttach();++ expect(agent.connectAgent).toHaveBeenCalledTimes(2);+ expect(session.getSnapshot()).toMatchObject({+ attachment: { status: "attached" },+ currentRun: runningView.currentRun,+ });+ });+});++describe("BackgroundExecutionSessionController hydration", () => {+ it("keeps a live tool call on its newly created assistant parent", async () => {+ const question = {+ id: "user-question",+ role: "user",+ content: "Why is latency up?",+ } satisfies AgUiMessage;+ const displayState = recordInAppAgentMessagesForDisplay(+ createInAppAgentDisplayState(),+ [question],+ );+ const hydrate = vi+ .fn()+ .mockResolvedValueOnce({+ messages: [question],+ displayState,+ eventCursor: 7,+ currentRun: runningView.currentRun,+ pendingToolApprovals: [],+ })+ // Keep the completed-run convergence open so this assertion observes+ // the live projection rather than a subsequently hydrated snapshot.+ .mockImplementation(() => new Promise<never>(() => undefined));++ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(+ [+ sseFrame({+ type: "event",+ sequenceNumber: 8,+ event: {+ type: EventType.RUN_STARTED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 9,+ event: {+ type: EventType.TOOL_CALL_START,+ toolCallId: "tool-call-1",+ toolCallName: "list_traces",+ parentMessageId: "assistant-tools",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 10,+ event: {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: "{}",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 11,+ event: {+ type: EventType.TOOL_CALL_END,+ toolCallId: "tool-call-1",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 12,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({ type: "done" }),+ ].join(""),+ ),+ );++ const session = new BackgroundExecutionSessionController({+ agent: new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn(),+ }),+ hydrate,+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ await vi.waitFor(() => {+ expect(+ session+ .getSnapshot()+ .messages.find((message) => message.id === "assistant-tools"),+ ).toMatchObject({+ toolCalls: [{ id: "tool-call-1" }],+ });+ });++ const snapshot = session.getSnapshot();+ expect(+ projectInAppAgentMessagesForDisplay(+ snapshot.messages,+ snapshot.displayState,+ ).map((message) => message.id),+ ).toEqual([question.id, "assistant-tools"]);+ });++ it("continues a hydrated assistant message that already interleaved a thought", async () => {+ const question = {+ id: "user-question",+ role: "user",+ content: "Why is latency up?",+ } satisfies AgUiMessage;+ const thought = {+ id: "assistant-thought",+ role: "reasoning",+ content: "Checking the traces.",+ } satisfies AgUiMessage;+ const answerBeforeThought = {+ id: "assistant-answer",+ role: "assistant",+ content: "Initial answer.",+ } satisfies AgUiMessage;+ const answerAfterThought = {+ ...answerBeforeThought,+ content: "Initial answer. Final answer.",+ } satisfies AgUiMessage;++ // Mirrors the fold the web server runs over the persisted event log: the+ // assistant answered, a thought was placed, then the same message continued.+ let displayState = createInAppAgentDisplayState();+ displayState = recordInAppAgentMessagesForDisplay(displayState, [+ question,+ answerBeforeThought,+ ]);+ displayState = recordInAppAgentMessagesForDisplay(displayState, [+ question,+ answerBeforeThought,+ thought,+ ]);+ displayState = recordInAppAgentMessagesForDisplay(displayState, [+ question,+ answerAfterThought,+ thought,+ ]);++ const hydrate = vi+ .fn()+ .mockResolvedValueOnce({+ messages: [question, answerAfterThought, thought],+ displayState,+ eventCursor: 7,+ currentRun: runningView.currentRun,+ pendingToolApprovals: [],+ })+ // The post-execution converge would refetch the settled transcript and+ // hide any damage the live tail did, so hold it open.+ .mockImplementation(() => new Promise<never>(() => undefined));++ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(+ [+ sseFrame({+ type: "event",+ sequenceNumber: 8,+ event: {+ type: EventType.RUN_STARTED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 9,+ event: {+ type: EventType.TEXT_MESSAGE_START,+ messageId: answerAfterThought.id,+ role: "assistant",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 10,+ event: {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: answerAfterThought.id,+ delta: " And one more.",+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 11,+ event: {+ type: EventType.TEXT_MESSAGE_END,+ messageId: answerAfterThought.id,+ },+ }),+ sseFrame({+ type: "event",+ sequenceNumber: 12,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({ type: "done" }),+ ].join(""),+ ),+ );++ const session = new BackgroundExecutionSessionController({+ agent: new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn(),+ }),+ hydrate,+ cancelRun: vi.fn(),+ decideApproval: vi.fn(),+ });++ await session.hydrateAndAttach();+ await vi.waitFor(() => {+ expect(+ session+ .getSnapshot()+ .messages.find((message) => message.id === answerAfterThought.id),+ ).toMatchObject({+ content: "Initial answer. Final answer. And one more.",+ });+ });++ const snapshot = session.getSnapshot();+ // The canonical transcript stays one assistant message: no synthetic+ // display-text sibling was ever seeded into the agent.+ expect(snapshot.messages.map((message) => message.id)).toEqual([+ question.id,+ answerAfterThought.id,+ thought.id,+ ]);+ expect(+ projectInAppAgentMessagesForDisplay(+ snapshot.messages,+ snapshot.displayState,+ ).map((message) => ({ id: message.id, content: message.content })),+ ).toEqual([+ { id: question.id, content: question.content },+ { id: answerAfterThought.id, content: "Initial answer." },+ { id: thought.id, content: thought.content },+ {+ id: `display-text-${answerAfterThought.id}-1`,+ content: " Final answer. And one more.",+ },+ ]);+ });+});++describe("InAppAgentBackgroundClient reconnect", () => {+ it("publishes a cancellable queued run as soon as start succeeds", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(sseFrame({ type: "done" })),+ );+ const onStatus = vi.fn();+ const client = new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn().mockResolvedValue({ runId: "run-1" }),+ onStatus,+ });++ client.addMessage({+ id: "message-1",+ role: "user",+ content: "Investigate this project",+ });+ await client.runAgent({ context: [] });++ expect(onStatus).toHaveBeenCalledWith({+ type: "status",+ runId: "run-1",+ status: InAppAgentRunStatus.QUEUED,+ errorCode: null,+ cancelRequested: false,+ });+ });++ it("continues from its cursor and delivers each event once", async () => {+ const frames = [+ sseFrame({+ type: "event",+ sequenceNumber: 0,+ event: {+ type: EventType.RUN_STARTED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ [+ sseFrame({+ type: "event",+ sequenceNumber: 1,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({ type: "done" }),+ ].join(""),+ ];+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => new Response(frames.shift() ?? ""));+ const client = new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn(),+ });+ const events: string[] = [];++ await new Promise<void>((resolve, reject) => {+ client.connect().subscribe({+ next: (event) => events.push(event.type),+ error: reject,+ complete: resolve,+ });+ });++ expect(events).toEqual([EventType.RUN_STARTED, EventType.RUN_FINISHED]);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain("cursor=-1");+ expect(String(fetchMock.mock.calls[1]?.[0])).toContain("cursor=0");+ });++ it("keeps watching across repeated quiet connection rotations", async () => {+ vi.useFakeTimers();+ const responses = [+ ...Array.from({ length: 6 }, () => new Response("")),+ new Response(+ [+ sseFrame({+ type: "event",+ sequenceNumber: 0,+ event: {+ type: EventType.RUN_FINISHED,+ runId: "run-1",+ threadId: "conversation-1",+ },+ }),+ sseFrame({ type: "done" }),+ ].join(""),+ ),+ ];+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => responses.shift() ?? new Response(""));+ const client = new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn(),+ });+ const events: string[] = [];+ const result = new Promise<string>((resolve, reject) => {+ client.connect().subscribe({+ next: (event) => {+ events.push(event.type);+ },+ error: reject,+ complete: () => {+ resolve("completed");+ },+ });+ });++ await vi.runAllTimersAsync();++ await expect(result).resolves.toBe("completed");+ expect(events).toEqual([EventType.RUN_FINISHED]);+ expect(fetchMock).toHaveBeenCalledTimes(7);+ });++ it("fails visibly when the watch returns an invalid frame", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(+ [+ sseFrame({ type: "event", sequenceNumber: "invalid" }),+ sseFrame({ type: "done" }),+ ].join(""),+ ),+ );+ const client = new InAppAgentBackgroundClient({+ projectId: "project-1",+ conversationId: "conversation-1",+ cursor: -1,+ startRun: vi.fn(),+ });+ const result = new Promise<unknown>((resolve) => {+ client.connect().subscribe({+ error: resolve,+ complete: () => {+ resolve("completed");+ },+ });+ });++ await expect(result).resolves.toMatchObject({+ message: "Assistant watch returned an invalid frame",+ retryable: false,+ });+ });+});++function sseFrame(frame: Record<string, unknown>): string {+ return `event: ${String(frame.type)}\ndata: ${JSON.stringify(frame)}\n\n`;+}diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts b/web/src/features/in-app-agent/lib/backgroundExecutionSession.tsnew file mode 100644index 0000000000..b8d2d0d9d2--- /dev/null+++ b/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts@@ -0,0 +1,604 @@+import type { AbstractAgent, AgentSubscriber } from "@ag-ui/client";+import { z } from "zod";++import { InAppAgentRunErrorCode, InAppAgentRunStatus } from "@langfuse/shared";+import type {+ AgUiMessage,+ InAppAgentToolApprovalRequest,+} from "@langfuse/shared/in-app-agent";+import { AgUiMessageSchema } from "@langfuse/shared/in-app-agent";+import { BackgroundExecutionConnectionError } from "./backgroundExecutionErrors";+import {+ createInAppAgentDisplayState,+ recordInAppAgentMessagesForDisplay,+ recordInAppAgentToolCallForDisplay,+ type InAppAgentDisplayState,+} from "./display";++export type AgentInput = Parameters<AbstractAgent["runAgent"]>[0];++export type ApprovalDecision = {+ runId: string;+ toolCallId: string;+ approved: boolean;+};++export type BackgroundExecutionRunView = {+ id: string;+ status: InAppAgentRunStatus;+ errorCode: string | null;+ cancelRequested: boolean;+};++export type BackgroundExecutionApprovalView = {+ runId: string;+ approvalRequest: InAppAgentToolApprovalRequest;+ status: "pending" | "submitting";+};++export type BackgroundExecutionAttachment =+ | { status: "detached" }+ | { status: "attaching" }+ | { status: "attached" }+ | { status: "error"; error: unknown; retryable: boolean };++export type BackgroundExecutionView = {+ messages: AgUiMessage[];+ /**+ * Rendering sidecar for {@link messages}. Seeded from the hydrated snapshot+ * and advanced by live events, so the projection at render time sees the same+ * state the server built from the persisted log.+ */+ displayState: InAppAgentDisplayState;+ liveMessageRevision: number;+ eventCursor: number;+ currentRun: BackgroundExecutionRunView | null;+ pendingToolApprovals: BackgroundExecutionApprovalView[];+ cancelStatus: "idle" | "submitting";+ attachment: BackgroundExecutionAttachment;+};++export type BackgroundExecutionSession = {+ hydrateAndAttach(): Promise<void>;+ run(input: AgentInput): Promise<void>;+ cancel(): Promise<void>;+ decide(input: ApprovalDecision): Promise<void>;+ detach(): void;+ dispose(): void;+ getSnapshot(): BackgroundExecutionView;+ subscribe(listener: () => void): () => void;+};++type BackgroundExecutionAgent = {+ messages: readonly unknown[];+ setMessages(messages: AgUiMessage[]): void;+ subscribe(subscriber: AgentSubscriber): { unsubscribe(): void };+ runAgent(input: AgentInput): Promise<unknown>;+ connectAgent(): Promise<unknown>;+ abortRun(): void;+ setCursor(cursor: number): void;+ setStatusListener?(+ listener?: (status: {+ runId: string;+ status: InAppAgentRunStatus;+ errorCode?: string | null;+ cancelRequested?: boolean;+ }) => void,+ ): void;+ setCursorListener?(listener?: (cursor: number) => void): void;+};++type BackgroundExecutionHydration = Omit<+ BackgroundExecutionView,+ "attachment" | "cancelStatus" | "liveMessageRevision"+>;++type BackgroundExecutionAgentSubscriber = Pick<+ AgentSubscriber,+ | "onRunStartedEvent"+ | "onEvent"+ | "onMessagesChanged"+ | "onStateChanged"+ | "onToolCallResultEvent"+ | "onRunErrorEvent"+>;++export class BackgroundExecutionSessionController implements BackgroundExecutionSession {+ private readonly agent: BackgroundExecutionAgent;+ private readonly hydrate: () => Promise<BackgroundExecutionHydration>;+ private readonly cancelRun: (runId: string) => Promise<unknown>;+ private readonly decideApproval: (+ input: ApprovalDecision,+ ) => Promise<unknown>;+ private readonly onSettled?: () => void;+ private readonly onError?: (error: unknown) => void;+ private readonly agentSubscription: { unsubscribe(): void };+ private readonly listeners = new Set<() => void>();+ private view: BackgroundExecutionView;+ private attachGeneration = 0;+ private isReplacingMessages = false;++ constructor(config: {+ agent: BackgroundExecutionAgent;+ hydrate: () => Promise<BackgroundExecutionHydration>;+ cancelRun: (runId: string) => Promise<unknown>;+ decideApproval: (input: ApprovalDecision) => Promise<unknown>;+ subscriber?: BackgroundExecutionAgentSubscriber;+ onSettled?: () => void;+ onError?: (error: unknown) => void;+ initialView?: Partial<BackgroundExecutionView>;+ }) {+ this.agent = config.agent;+ this.hydrate = config.hydrate;+ this.cancelRun = config.cancelRun;+ this.decideApproval = config.decideApproval;+ this.onSettled = config.onSettled;+ this.onError = config.onError;+ this.view = {+ messages: [],+ displayState: createInAppAgentDisplayState(),+ liveMessageRevision: 0,+ eventCursor: -1,+ currentRun: null,+ pendingToolApprovals: [],+ cancelStatus: "idle",+ attachment: { status: "detached" },+ ...config.initialView,+ };+ this.agent.setStatusListener?.((status) => {+ const currentRun = {+ id: status.runId,+ status: status.status,+ errorCode: status.errorCode ?? null,+ cancelRequested: status.cancelRequested === true,+ };+ const hasSettled = !isExecutingRun(currentRun);++ this.setView({+ ...this.view,+ currentRun,+ attachment: hasSettled ? { status: "detached" } : this.view.attachment,+ });+ if (hasSettled) {+ // Status follows all persisted events and is authoritative even if the+ // transport stalls before its final `done` frame.+ this.agent.abortRun();+ this.onSettled?.();+ }+ });+ this.agent.setCursorListener?.((eventCursor) => {+ this.setView({ ...this.view, eventCursor });+ });+ this.agentSubscription = this.agent.subscribe({+ ...config.subscriber,+ onMessagesChanged: (params) => {+ if (!this.isReplacingMessages) {+ this.observeMessages(params.messages);+ return config.subscriber?.onMessagesChanged?.(params);+ }+ },+ onStateChanged: (params) => {+ if (!this.isReplacingMessages) {+ this.observeMessages(params.messages);+ return config.subscriber?.onStateChanged?.(params);+ }+ },+ onCustomEvent: ({ event }) => {+ const approvalRequest = parseInAppAgentInterruptEvent(event);+ if (approvalRequest) {+ this.observeApproval({+ runId: approvalRequest.runId,+ approvalRequest,+ status: "pending",+ });+ }+ },+ onToolCallResultEvent: async (params) => {+ this.resolveApproval(params.event.toolCallId);+ return config.subscriber?.onToolCallResultEvent?.(params);+ },+ });+ }++ async hydrateAndAttach(): Promise<void> {+ if (+ this.view.attachment.status === "attaching" ||+ this.view.attachment.status === "attached"+ ) {+ return;+ }++ const generation = ++this.attachGeneration;+ this.setView({ ...this.view, attachment: { status: "attaching" } });++ try {+ const replaced = await this.replaceWithHydratedSnapshot(generation);+ if (!replaced) {+ return;+ }++ if (!isExecutingRun(this.view.currentRun)) {+ return;+ }++ this.setView({ ...this.view, attachment: { status: "attached" } });+ this.observeExecution(this.agent.connectAgent(), generation);+ } catch (error) {+ if (generation !== this.attachGeneration) {+ return;+ }++ this.setAttachmentError(error);+ throw error;+ }+ }++ async run(input: AgentInput): Promise<void> {+ if (+ this.view.attachment.status === "attaching" ||+ this.view.attachment.status === "attached"+ ) {+ return;+ }++ const generation = ++this.attachGeneration;+ this.setView({+ ...this.view,+ currentRun: null,+ attachment: { status: "attached" },+ });++ try {+ await this.agent.runAgent(input);+ } catch (error) {+ if (generation !== this.attachGeneration) {+ return;+ }++ if (error instanceof BackgroundExecutionConnectionError) {+ this.setAttachmentError(error);+ } else {+ this.setView({+ ...this.view,+ attachment: { status: "detached" },+ });+ }+ this.onError?.(error);+ this.onSettled?.();+ throw error;+ }++ await this.convergeAfterExecution(generation);+ }++ async cancel(): Promise<void> {+ const run = this.view.currentRun;+ if (!run || !isCancellableBackgroundRun(run.status)) {+ return;+ }++ const attachmentGeneration = this.attachGeneration;+ this.setView({ ...this.view, cancelStatus: "submitting" });+ try {+ await this.cancelRun(run.id);+ } catch (error) {+ this.setView({ ...this.view, cancelStatus: "idle" });+ throw error;+ }+ // The watch stream may have delivered a fresher status while the mutation+ // was in flight; only stamp the cancellation onto the same run.+ const currentRun = this.view.currentRun;+ this.setView({+ ...this.view,+ currentRun:+ currentRun?.id === run.id+ ? { ...currentRun, cancelRequested: true }+ : currentRun,+ cancelStatus: "idle",+ });+ await this.refreshAttachmentAfterCommand(attachmentGeneration);+ }++ async decide(input: ApprovalDecision): Promise<void> {+ const attachmentGeneration = this.attachGeneration;+ this.setApprovalStatus(input.toolCallId, "submitting");+ try {+ await this.decideApproval(input);+ } catch (error) {+ this.setApprovalStatus(input.toolCallId, "pending");+ throw error;+ }+ this.resolveApproval(input.toolCallId);+ await this.refreshAttachmentAfterCommand(attachmentGeneration);+ }++ detach(): void {+ this.attachGeneration += 1;+ this.agent.abortRun();+ this.setView({ ...this.view, attachment: { status: "detached" } });+ }++ dispose(): void {+ this.detach();+ this.agentSubscription.unsubscribe();+ this.agent.setStatusListener?.(undefined);+ this.agent.setCursorListener?.(undefined);+ this.listeners.clear();+ }++ getSnapshot(): BackgroundExecutionView {+ return this.view;+ }++ subscribe(listener: () => void): () => void {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }++ private observeMessages(messages: readonly unknown[]): void {+ const parsedMessages = messages.flatMap((message) => {+ const parsed = AgUiMessageSchema.safeParse(message);+ return parsed.success ? [parsed.data] : [];+ });+ let displayState = recordInAppAgentMessagesForDisplay(+ this.view.displayState,+ parsedMessages,+ );+ for (const message of parsedMessages) {+ if (message.role !== "assistant") {+ continue;+ }+ for (const toolCall of message.toolCalls ?? []) {+ displayState = recordInAppAgentToolCallForDisplay(+ displayState,+ toolCall.id,+ message.id,+ );+ }+ }+ this.setView({+ ...this.view,+ messages: parsedMessages,+ displayState,+ liveMessageRevision: this.view.liveMessageRevision + 1,+ });+ }++ private observeApproval(approval: BackgroundExecutionApprovalView): void {+ const pendingToolApprovals = this.view.pendingToolApprovals.filter(+ (pending) =>+ pending.approvalRequest.toolCallId !==+ approval.approvalRequest.toolCallId,+ );+ this.setView({+ ...this.view,+ pendingToolApprovals: [...pendingToolApprovals, approval],+ });+ }++ private resolveApproval(toolCallId: string): void {+ this.setView({+ ...this.view,+ pendingToolApprovals: this.view.pendingToolApprovals.filter(+ (pending) => pending.approvalRequest.toolCallId !== toolCallId,+ ),+ });+ }++ private setApprovalStatus(+ toolCallId: string,+ status: BackgroundExecutionApprovalView["status"],+ ): void {+ this.setView({+ ...this.view,+ pendingToolApprovals: this.view.pendingToolApprovals.map((pending) =>+ pending.approvalRequest.toolCallId === toolCallId+ ? { ...pending, status }+ : pending,+ ),+ });+ }++ private observeExecution(+ execution: Promise<unknown>,+ generation: number,+ ): void {+ execution.then(+ () => this.convergeAfterExecution(generation),+ (error: unknown) => {+ if (generation !== this.attachGeneration) {+ return;+ }++ this.setAttachmentError(error);+ this.onError?.(error);+ },+ );+ }++ private async convergeAfterExecution(generation: number): Promise<void> {+ if (generation !== this.attachGeneration) {+ return;+ }++ try {+ await this.replaceWithHydratedSnapshot(generation);+ } catch (error) {+ if (generation !== this.attachGeneration) {+ return;+ }++ const connectionError =+ error instanceof BackgroundExecutionConnectionError+ ? error+ : new BackgroundExecutionConnectionError(+ "Failed to refresh the completed assistant transcript",+ { retryable: true, cause: error },+ );+ this.setAttachmentError(connectionError);+ this.onError?.(connectionError);+ } finally {+ if (generation === this.attachGeneration) {+ this.onSettled?.();+ }+ }+ }++ private async replaceWithHydratedSnapshot(+ generation: number,+ ): Promise<boolean> {+ const hydrated = await this.hydrate();++ if (generation !== this.attachGeneration) {+ return false;+ }++ this.isReplacingMessages = true;+ try {+ this.agent.setMessages(hydrated.messages);+ } finally {+ this.isReplacingMessages = false;+ }+ this.agent.setCursor(hydrated.eventCursor);+ this.setView({+ ...hydrated,+ liveMessageRevision: this.view.liveMessageRevision,+ cancelStatus: "idle",+ attachment: { status: "detached" },+ });++ return true;+ }++ private async refreshAttachmentAfterCommand(+ attachmentGeneration: number,+ ): Promise<void> {+ if (attachmentGeneration !== this.attachGeneration) {+ return;+ }++ this.detach();+ try {+ await this.hydrateAndAttach();+ if (!isExecutingRun(this.view.currentRun)) {+ // A terminal snapshot does not attach a watch whose convergence could+ // otherwise publish the settled lifecycle notification.+ this.onSettled?.();+ }+ } catch {+ // The durable command already succeeded. Attachment failures are exposed+ // through the session snapshot and must not change the command outcome.+ }+ }++ private setAttachmentError(error: unknown): void {+ this.setView({+ ...this.view,+ attachment: {+ status: "error",+ error,+ retryable:+ error instanceof BackgroundExecutionConnectionError &&+ error.retryable,+ },+ });+ }++ private setView(view: BackgroundExecutionView): void {+ this.view = view;+ this.listeners.forEach((listener) => {+ listener();+ });+ }+}++const MastraSuspendEventSchema = z.object({+ type: z.literal("mastra_suspend"),+ toolCallId: z.string().min(1),+ toolName: z.string().min(1),+ args: z.unknown().optional(),+ runId: z.string().min(1),+});++export function parseInAppAgentInterruptEvent(+ event: unknown,+): InAppAgentToolApprovalRequest | null {+ if (+ !event ||+ typeof event !== "object" ||+ !("name" in event) ||+ event.name !== "on_interrupt"+ ) {+ return null;+ }++ const value = "value" in event ? event.value : undefined;+ const parsedValue = typeof value === "string" ? parseJson(value) : value;+ const interrupt = MastraSuspendEventSchema.safeParse(parsedValue);++ return interrupt.success+ ? {+ type: "tool_approval_request",+ toolCallId: interrupt.data.toolCallId,+ toolName: interrupt.data.toolName,+ args: interrupt.data.args,+ runId: interrupt.data.runId,+ }+ : null;+}++function parseJson(value: string): unknown {+ try {+ return JSON.parse(value) as unknown;+ } catch {+ return null;+ }+}++export function isCancellableBackgroundRun(+ status: InAppAgentRunStatus,+): boolean {+ return (+ status === InAppAgentRunStatus.QUEUED ||+ status === InAppAgentRunStatus.RUNNING ||+ status === InAppAgentRunStatus.AWAITING_APPROVAL+ );+}++export function getBackgroundRunFailureMessage(+ errorCode: string | null,+): string {+ return (+ BACKGROUND_RUN_FAILURE_MESSAGES[errorCode ?? ""] ??+ "The run failed. Try again."+ );+}++const BACKGROUND_RUN_FAILURE_MESSAGES: Readonly<Record<string, string>> = {+ [InAppAgentRunErrorCode.ENQUEUE_FAILED]: "Couldn't start the run. Try again.",+ [InAppAgentRunErrorCode.QUEUE_TIMEOUT]:+ "No worker picked this up. Try again.",+ [InAppAgentRunErrorCode.WORKER_LOST]: "The run was interrupted. Try again.",+ [InAppAgentRunErrorCode.STALE]: "The run was interrupted. Try again.",+ [InAppAgentRunErrorCode.RUN_TIMEOUT]:+ "The run exceeded the maximum duration.",+ [InAppAgentRunErrorCode.WORKER_SHUTDOWN]:+ "The run was interrupted by a deploy. Try again.",+ [InAppAgentRunErrorCode.OUTCOME_UNKNOWN]:+ "The approved action may have completed. Verify before retrying.",+ [InAppAgentRunErrorCode.APPROVAL_EXPIRED]: "The approval request expired.",+ [InAppAgentRunErrorCode.APPROVAL_SUPERSEDED]: "Replaced by a newer message.",+ [InAppAgentRunErrorCode.APPROVAL_CANCELLED]: "Approval cancelled.",+ [InAppAgentRunErrorCode.CANCELLED]: "You stopped this run.",+};++function isExecutingRun(+ run: BackgroundExecutionRunView | null,+): run is BackgroundExecutionRunView {+ return (+ run?.status === InAppAgentRunStatus.QUEUED ||+ run?.status === InAppAgentRunStatus.RUNNING+ );+}diff --git a/web/src/features/in-app-agent/lib/display.ts b/web/src/features/in-app-agent/lib/display.tsnew file mode 100644index 0000000000..3a9fec35de--- /dev/null+++ b/web/src/features/in-app-agent/lib/display.ts@@ -0,0 +1,373 @@+import { z } from "zod";++import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";++/**+ * Rendering-only derivation of the persisted event log. The canonical messages+ * stay untouched; this state records where interleaved reasoning and tool calls+ * landed so the projection can reproduce that ordering. It lives in web because+ * only the browser renders — the worker never does.+ *+ * The state is produced twice from the same events: once on the web server when+ * building a conversation snapshot, and once incrementally on the client as+ * live events arrive. Both use these same functions, so the two agree.+ */++type InAppAgentDisplayPlacement = {+ anchorMessageId: string;+ order: number;+};++export type InAppAgentDisplayState = {+ latestPlacement: InAppAgentDisplayPlacement | null;+ nativeToolCallParentMessageId: string | null;+ latestNewMessageId: string | null;+ nextOrder: number;+ seenMessageIds: ReadonlySet<string>;+ textByMessageId: Record<+ string,+ {+ nativeContent: string;+ publishedContent: string;+ segments: Array<+ InAppAgentDisplayPlacement & {+ id: string;+ content: string;+ }+ >;+ }+ >;+ toolCallPlacements: Record<string, InAppAgentDisplayPlacement | null>;+};++type InAppAgentDisplayMessage = AgUiMessage & {+ feedbackMessageId?: string;+};++const InAppAgentDisplayPlacementSchema = z.object({+ anchorMessageId: z.string(),+ order: z.number(),+});++/**+ * Wire form of {@link InAppAgentDisplayState}: identical except that the seen+ * message ids travel as an array. Validated rather than relying on the tRPC+ * transformer so the contract stays explicit and transport-independent.+ *+ * The sidecar duplicates assistant text, and `publishedContent` is always+ * `nativeContent` plus every segment's content joined in order, so it could be+ * dropped from the wire and recomputed on deserialize. Measured overhead on a+ * large real conversation is ~12% of the message payload, because tool results+ * dominate and are never duplicated here, so that optimization is not worth+ * its invariant today.+ */+export const SerializedInAppAgentDisplayStateSchema = z.object({+ latestPlacement: InAppAgentDisplayPlacementSchema.nullable(),+ nativeToolCallParentMessageId: z.string().nullable(),+ latestNewMessageId: z.string().nullable(),+ nextOrder: z.number(),+ seenMessageIds: z.array(z.string()),+ textByMessageId: z.record(+ z.string(),+ z.object({+ nativeContent: z.string(),+ publishedContent: z.string(),+ segments: z.array(+ InAppAgentDisplayPlacementSchema.extend({+ id: z.string(),+ content: z.string(),+ }),+ ),+ }),+ ),+ toolCallPlacements: z.record(+ z.string(),+ InAppAgentDisplayPlacementSchema.nullable(),+ ),+});++export type SerializedInAppAgentDisplayState = z.infer<+ typeof SerializedInAppAgentDisplayStateSchema+>;++export function serializeInAppAgentDisplayState(+ state: InAppAgentDisplayState,+): SerializedInAppAgentDisplayState {+ return { ...state, seenMessageIds: [...state.seenMessageIds] };+}++export function deserializeInAppAgentDisplayState(+ serialized: unknown,+): InAppAgentDisplayState {+ const parsed = SerializedInAppAgentDisplayStateSchema.safeParse(serialized);+ if (!parsed.success) {+ return createInAppAgentDisplayState();+ }++ return {+ ...parsed.data,+ seenMessageIds: new Set(parsed.data.seenMessageIds),+ };+}++export function createInAppAgentDisplayState(): InAppAgentDisplayState {+ return {+ latestPlacement: null,+ nativeToolCallParentMessageId: null,+ latestNewMessageId: null,+ nextOrder: 0,+ seenMessageIds: new Set(),+ textByMessageId: {},+ toolCallPlacements: {},+ };+}++export function recordInAppAgentMessagesForDisplay(+ state: InAppAgentDisplayState,+ messages: readonly AgUiMessage[],+): InAppAgentDisplayState {+ const seenMessageIds = new Set(state.seenMessageIds);+ const textByMessageId = { ...state.textByMessageId };+ let latestNewMessageId = state.latestNewMessageId;+ let latestPlacement = state.latestPlacement;+ let nativeToolCallParentMessageId = state.nativeToolCallParentMessageId;+ let nextOrder = state.nextOrder;++ for (const message of messages) {+ if (seenMessageIds.has(message.id)) {+ continue;+ }++ seenMessageIds.add(message.id);+ latestNewMessageId = message.id;+ latestPlacement = null;+ nativeToolCallParentMessageId = null;++ if (message.role === "assistant" && typeof message.content === "string") {+ textByMessageId[message.id] = {+ nativeContent: message.content,+ publishedContent: message.content,+ segments: [],+ };+ }+ }++ for (const message of messages) {+ if (message.role !== "assistant" || typeof message.content !== "string") {+ continue;+ }++ const textState = textByMessageId[message.id];+ if (!textState || textState.publishedContent === message.content) {+ continue;+ }++ nativeToolCallParentMessageId = null;+ if (!message.content.startsWith(textState.publishedContent)) {+ textByMessageId[message.id] = {+ nativeContent: message.content,+ publishedContent: message.content,+ segments: [],+ };+ continue;+ }++ const appendedContent = message.content.slice(+ textState.publishedContent.length,+ );+ const latestSegment = textState.segments.at(-1);+ if (latestPlacement && latestSegment?.order === latestPlacement.order) {+ textByMessageId[message.id] = {+ ...textState,+ publishedContent: message.content,+ segments: textState.segments.slice(0, -1).concat({+ ...latestSegment,+ content: latestSegment.content + appendedContent,+ }),+ };+ continue;+ }++ if (latestNewMessageId === message.id && latestPlacement === null) {+ textByMessageId[message.id] = {+ ...textState,+ nativeContent: textState.nativeContent + appendedContent,+ publishedContent: message.content,+ };+ continue;+ }++ const anchorMessageId =+ latestPlacement?.anchorMessageId ?? latestNewMessageId;+ if (!anchorMessageId) {+ textByMessageId[message.id] = {+ ...textState,+ nativeContent: textState.nativeContent + appendedContent,+ publishedContent: message.content,+ };+ continue;+ }++ const placement = { anchorMessageId, order: nextOrder };+ const segment = {+ ...placement,+ id: `display-text-${message.id}-${textState.segments.length + 1}`,+ content: appendedContent,+ };+ nextOrder += 1;+ latestPlacement = placement;+ textByMessageId[message.id] = {+ ...textState,+ publishedContent: message.content,+ segments: textState.segments.concat(segment),+ };+ }++ return {+ ...state,+ latestPlacement,+ nativeToolCallParentMessageId,+ latestNewMessageId,+ nextOrder,+ seenMessageIds,+ textByMessageId,+ };+}++export function recordInAppAgentToolCallForDisplay(+ state: InAppAgentDisplayState,+ toolCallId: string,+ parentMessageId: string | undefined,+): InAppAgentDisplayState {+ if (toolCallId in state.toolCallPlacements) {+ return state;+ }++ const anchorMessageId =+ state.latestPlacement?.anchorMessageId ?? state.latestNewMessageId;+ const placement = anchorMessageId+ ? { anchorMessageId, order: state.nextOrder }+ : null;+ const isNativePlacement =+ (state.latestPlacement === null && anchorMessageId === parentMessageId) ||+ state.nativeToolCallParentMessageId === parentMessageId;++ return {+ ...state,+ latestPlacement: placement,+ nativeToolCallParentMessageId: isNativePlacement ? anchorMessageId : null,+ nextOrder: state.nextOrder + 1,+ toolCallPlacements: {+ ...state.toolCallPlacements,+ [toolCallId]: isNativePlacement ? null : placement,+ },+ };+}++export function projectInAppAgentMessagesForDisplay(+ messages: readonly AgUiMessage[],+ state: InAppAgentDisplayState,+): InAppAgentDisplayMessage[] {+ // Canonical messages stay untouched for persistence and subsequent runs.+ const messageIds = new Set(messages.map((message) => message.id));+ const placementsByAnchor = new Map<+ string,+ Array<{ order: number; message: InAppAgentDisplayMessage }>+ >();++ const addPlacement = (+ placement: InAppAgentDisplayPlacement,+ message: InAppAgentDisplayMessage,+ ) => {+ if (!messageIds.has(placement.anchorMessageId)) {+ return;+ }++ placementsByAnchor.set(+ placement.anchorMessageId,+ (placementsByAnchor.get(placement.anchorMessageId) ?? []).concat({+ order: placement.order,+ message,+ }),+ );+ };++ for (const message of messages) {+ if (message.role !== "assistant") {+ continue;+ }++ for (const toolCall of message.toolCalls ?? []) {+ const placement = state.toolCallPlacements[toolCall.id];+ if (+ !placement ||+ toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME+ ) {+ continue;+ }++ addPlacement(placement, {+ id: `display-tool-${toolCall.id}`,+ role: "assistant",+ content: "",+ toolCalls: [toolCall],+ });+ }+ }++ for (const [sourceMessageId, textState] of Object.entries(+ state.textByMessageId,+ )) {+ const sourceMessage = messages.find(+ (message) =>+ message.role === "assistant" && message.id === sourceMessageId,+ );++ for (const segment of textState.segments) {+ addPlacement(segment, {+ id: segment.id,+ role: "assistant",+ content: segment.content,+ ...(sourceMessage?.role === "assistant"+ ? {+ runId: sourceMessage.runId,+ feedback: sourceMessage.feedback,+ feedbackMessageId: sourceMessage.id,+ }+ : {}),+ });+ }+ }++ return messages.flatMap<InAppAgentDisplayMessage>((message) => {+ const projectedMessage =+ message.role === "assistant"+ ? {+ ...message,+ content:+ state.textByMessageId[message.id]?.nativeContent ??+ message.content,+ toolCalls: message.toolCalls?.filter((toolCall) => {+ const placement = state.toolCallPlacements[toolCall.id];+ return (+ toolCall.function.name === IN_APP_AGENT_REDIRECT_TOOL_NAME ||+ !placement ||+ !messageIds.has(placement.anchorMessageId)+ );+ }),+ }+ : message;+ const placements = placementsByAnchor.get(message.id);+ if (!placements) {+ return [projectedMessage];+ }++ return [+ projectedMessage,+ ...placements+ .sort((left, right) => left.order - right.order)+ .map(({ message: placedMessage }) => placedMessage),+ ];+ });+}diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.tsindex 23bf5a50eb..00861f0296 100644--- a/web/src/features/in-app-agent/server/backgroundRunService.ts+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts@@ -7,7 +7,7 @@ import {InAppAgentRunStatus,LangfuseNotFoundError,} from "@langfuse/shared";-import type { PrismaClient } from "@langfuse/shared/src/db";+import { Prisma, type PrismaClient } from "@langfuse/shared/src/db";import {InAppAgentRunQueue,logger,@@ -25,7 +25,6 @@ import { parseInAppAgentInterruptEvent } from "@langfuse/shared/in-app-agent/serimport {ensureOwnedConversation,getConversationEvents,- getConversationMessagesForDisplayFromEvents,getOwnedConversationOrThrow,isInAppAgentConversationWriteLocked,maybeInferAndPersistConversationTitle,@@ -40,7 +39,9 @@ import {requestRunCancellation,} from "@langfuse/shared/in-app-agent/server/runLifecycle";+import { serializeInAppAgentDisplayState } from "@/src/features/in-app-agent/lib/display";import { resolveInAppAgentRunContext } from "@/src/features/in-app-agent/server/runContext";+import { getConversationSnapshotFromEvents } from "@/src/features/in-app-agent/server/conversationSnapshot";const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE ="Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";@@ -76,27 +77,33 @@ export async function getBackgroundConversationSnapshot(params: {},});- 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);+ // The worker commits terminal status and its final events atomically. Keep+ // both reads on one version so the cursor cannot describe an older prefix.+ const [events, runs] = await params.prisma.$transaction(+ (tx) =>+ Promise.all([+ getConversationEvents({+ prisma: tx,+ projectId: params.projectId,+ conversationId: params.conversationId,+ }),+ tx.inAppAgentRun.findMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ },+ orderBy: { createdAt: "asc" },+ select: {+ id: true,+ status: true,+ errorCode: true,+ cancelRequestedAt: true,+ },+ }),+ ]),+ { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },+ );+ const { messages, displayState } = getConversationSnapshotFromEvents(events);const latestRun = runs.at(-1) ?? null;@@ -108,6 +115,7 @@ export async function getBackgroundConversationSnapshot(params: {}),}),messages,+ displayState: serializeInAppAgentDisplayState(displayState),eventCursor: events.reduce((max, event) => Math.max(max, event.sequenceNumber),-1,diff --git a/web/src/features/in-app-agent/server/conversationSnapshot.ts b/web/src/features/in-app-agent/server/conversationSnapshot.tsnew file mode 100644index 0000000000..e2e76a275c--- /dev/null+++ b/web/src/features/in-app-agent/server/conversationSnapshot.ts@@ -0,0 +1,81 @@+import { EventType } from "@ag-ui/core";++import { createConversationMessageAccumulator } from "@langfuse/shared/in-app-agent/server/persistence";+import type { PersistedConversationEvent } from "@langfuse/shared/in-app-agent/server/persistence";++import {+ createInAppAgentDisplayState,+ recordInAppAgentMessagesForDisplay,+ recordInAppAgentToolCallForDisplay,+} from "@/src/features/in-app-agent/lib/display";++/**+ * Rebuilds both representations a browser needs from one read of the persisted+ * event log: the canonical AG-UI messages that seed the live agent, and the+ * display state that tells the client-side projection where interleaved+ * reasoning and tool calls belong.+ *+ * Deliberately does not project and does not prune. Projection happens once, at+ * render time. Pruning unpaired tool calls here would break a resumed run: the+ * arriving TOOL_CALL_RESULT needs its tool call present in the seed.+ */+export function getConversationSnapshotFromEvents(+ events: readonly PersistedConversationEvent[],+) {+ const accumulator = createConversationMessageAccumulator([]);+ let displayState = createInAppAgentDisplayState();+ const deferredToolCallParents = new Map<string, string | undefined>();++ for (const { event, runId } of events) {+ if (event.type === EventType.TOOL_CALL_START) {+ const toolCallId = getEventString(event, "toolCallId");+ if (toolCallId) {+ const parentMessageId = getEventString(event, "parentMessageId");+ if (+ parentMessageId &&+ accumulator+ .getMessages()+ .some((message) => message.id === parentMessageId)+ ) {+ displayState = recordInAppAgentToolCallForDisplay(+ displayState,+ toolCallId,+ parentMessageId,+ );+ } else {+ deferredToolCallParents.set(toolCallId, parentMessageId);+ }+ }+ }++ if (accumulator.processEvent(event, runId)) {+ displayState = recordInAppAgentMessagesForDisplay(+ displayState,+ accumulator.getMessages(),+ );+ }++ if (event.type === EventType.TOOL_CALL_END) {+ const toolCallId = getEventString(event, "toolCallId");+ if (toolCallId && deferredToolCallParents.has(toolCallId)) {+ displayState = recordInAppAgentToolCallForDisplay(+ displayState,+ toolCallId,+ deferredToolCallParents.get(toolCallId),+ );+ deferredToolCallParents.delete(toolCallId);+ }+ }+ }++ return { messages: accumulator.getMessages(), displayState };+}++function getEventString(event: unknown, key: string): string | undefined {+ if (typeof event !== "object" || event === null) {+ return undefined;+ }++ const value = (event as Record<string, unknown>)[key];+ return typeof value === "string" ? value : undefined;+}