🪢 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
fix(agent): replay background tool side effects (#15783)
Lysander Kiesel5cb736465070
diff --git a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsxindex 5813acd31f..02f8bdb95a 100644--- a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx+++ b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx@@ -12,7 +12,7 @@ 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 { InAppAiAgentProvider, useInAppAiAgent } from "./InAppAiAgentProvider";import styles from "./InAppAgentWindow.module.css";const providerMocks = vi.hoisted(() => {@@ -67,6 +67,12 @@ const providerMocks = vi.hoisted(() => {isLoading: false,},utils: {+ dashboard: {+ invalidate: vi.fn(),+ },+ dashboardWidgets: {+ invalidate: vi.fn(),+ },inAppAgent: {getConversation: {fetch: vi.fn(),@@ -76,6 +82,9 @@ const providerMocks = vi.hoisted(() => {invalidate: vi.fn(),},},+ prompts: {+ invalidate: vi.fn(),+ },},};});@@ -145,18 +154,40 @@ function sseFrame(frame: unknown): string {return `data: ${JSON.stringify(frame)}\n\n`;}-function renderExecutionUi() {+function ReopenAssistantButton() {+ const { setOpen } = useInAppAiAgent();++ return (+ <button+ type="button"+ onClick={() => {+ setOpen(true);+ }}+ >+ Reopen assistant+ </button>+ );+}++function renderExecutionUi({+ defaultOpen = true,+ includeReopenButton = false,+}: {+ defaultOpen?: boolean;+ includeReopenButton?: boolean;+} = {}) {return render(- <TooltipProvider>- <InAppAiAgentProvider defaultOpen>+ <InAppAiAgentProvider defaultOpen={defaultOpen}>+ <TooltipProvider>+ {includeReopenButton ? <ReopenAssistantButton /> : null}<ControlledInAppAgentWindowisExpanded={false}onDeleteConversation={vi.fn()}onExpandedChange={vi.fn()}showCloseButton={false}/>- </InAppAiAgentProvider>- </TooltipProvider>,+ </TooltipProvider>+ </InAppAiAgentProvider>,);}@@ -302,6 +333,92 @@ describe("in-app agent execution", () => {).toBeInTheDocument();});+ it("replays prompt invalidations after a detached run completes", async () => {+ providerMocks.backgroundExecutionEnabled = true;+ const completedSnapshot = {+ conversation: {+ id: "conversation-1",+ isWriteLocked: false,+ },+ messages: [+ {+ id: "prompt-call",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "prompt-tool-call",+ type: "function",+ function: {+ name: "langfuse_createTextPrompt",+ arguments: "{}",+ },+ },+ ],+ },+ {+ id: "prompt-result",+ role: "tool",+ toolCallId: "prompt-tool-call",+ content: '{"id":"prompt-1"}',+ },+ {+ id: "prompt-call-2",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "prompt-tool-call-2",+ type: "function",+ function: {+ name: "langfuse_createTextPrompt",+ arguments: "{}",+ },+ },+ ],+ },+ {+ id: "prompt-result-2",+ role: "tool",+ toolCallId: "prompt-tool-call-2",+ content: '{"id":"prompt-2"}',+ },+ ],+ eventCursor: 14,+ latestRun: {+ id: "run-1",+ status: InAppAgentRunStatus.SUCCEEDED,+ errorCode: null,+ cancelRequested: false,+ },+ pendingToolApprovals: [],+ } satisfies NonNullable<typeof providerMocks.conversationQuery.data>;+ providerMocks.conversationQuery.data = completedSnapshot;+ providerMocks.utils.inAppAgent.getConversation.fetch.mockResolvedValueOnce(+ completedSnapshot,+ );+ window.sessionStorage.setItem(+ "langfuse:in-app-ai-agent-selected-conversation:project-1",+ JSON.stringify("conversation-1"),+ );++ renderExecutionUi({+ defaultOpen: false,+ includeReopenButton: true,+ });++ fireEvent.click(screen.getByRole("button", { name: "Reopen assistant" }));++ // Two completed prompt tool calls must union into a single invalidation.+ await waitFor(() => {+ expect(providerMocks.utils.prompts.invalidate).toHaveBeenCalledOnce();+ });+ expect(providerMocks.utils.dashboard.invalidate).not.toHaveBeenCalled();+ expect(+ providerMocks.utils.dashboardWidgets.invalidate,+ ).not.toHaveBeenCalled();+ });+it("keeps a hydrated in-flight tool call visibly running", async () => {providerMocks.backgroundExecutionEnabled = true;providerMocks.conversationQuery.data = {diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 8bda7245eb..5f7219bf9f 100644--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -84,8 +84,8 @@ import {import { evaluateSetStateAction } from "@/src/utils/evaluate-set-state-action";import { InAppAgentDisabledDialog } from "@/src/features/in-app-agent/components/InAppAgentDisabledDialog";import {- performToolSideEffects,- shouldPerformToolSideEffects,+ getCompletedToolCalls,+ performToolSideEffectsForCompletedToolCalls,} from "@/src/features/in-app-agent/components/utils/side-effects";const SELECTED_CONVERSATION_STORAGE_KEY_PREFIX =@@ -345,6 +345,7 @@ function InAppAiAgentProviderInner({useState<BackgroundExecutionSession | null>(null);const activeRunIdRef = useRef<string | null>(null);const toolCallNamesRef = useRef(new Map<string, string>());+ const handledToolCallIdsRef = useRef(new Set<string>());const backgroundExecutionEnabled = useInAppAgentBackgroundExecutionEnabled();const intentionalAbortRef = useRef(false);const submitInFlightRef = useRef(false);@@ -739,6 +740,7 @@ function InAppAiAgentProviderInner({agentRef.current = null;activeRunIdRef.current = null;toolCallNamesRef.current.clear();+ handledToolCallIdsRef.current.clear();setDisplayState(createInAppAgentDisplayState());foregroundPendingToolApprovalsRef.current = [];setForegroundPendingToolApprovals([]);@@ -864,17 +866,20 @@ function InAppAiAgentProviderInner({}},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 },- );- },- );+ const toolCallId = String(event.toolCallId);+ const toolName = toolCallNamesRef.current.get(toolCallId);+ toolCallNamesRef.current.delete(toolCallId);+ if (toolName) {+ performToolSideEffectsForCompletedToolCalls({+ toolCalls: [{ toolCallId, toolName, toolError: event.error }],+ handledToolCallIds: handledToolCallIdsRef.current,+ utils,+ }).catch((error: unknown) => {+ console.error(+ "Failed to invalidate tRPC routes after in-app agent tool call",+ { error, toolName },+ );+ });}},onRunErrorEvent: ({ event }) => {@@ -1077,6 +1082,18 @@ function InAppAiAgentProviderInner({toolCallId: input.toolCallId,approved: input.approved,}),+ onHydratedSnapshot: ({ messages }) => {+ performToolSideEffectsForCompletedToolCalls({+ toolCalls: getCompletedToolCalls(messages),+ handledToolCallIds: handledToolCallIdsRef.current,+ utils,+ }).catch((error: unknown) => {+ console.error(+ "Failed to replay tRPC invalidations after hydrated in-app agent tool calls",+ error,+ );+ });+ },onSettled: () => {clearLoadingEvents();utils.inAppAgent.listConversations.invalidate({ projectId });@@ -1106,8 +1123,7 @@ function InAppAiAgentProviderInner({releaseSubmitLock,resetAgent,startRunMutation,- utils.inAppAgent.getConversation,- utils.inAppAgent.listConversations,+ utils,],);diff --git a/web/src/features/in-app-agent/components/utils/side-effects.ts b/web/src/features/in-app-agent/components/utils/side-effects.tsindex c8f1f17684..8aba0dbe21 100644--- a/web/src/features/in-app-agent/components/utils/side-effects.ts+++ b/web/src/features/in-app-agent/components/utils/side-effects.ts@@ -1,6 +1,7 @@import type { InAppAgentLangfuseMcpToolName } from "@langfuse/shared/in-app-agent/server/tools";import { safeJsonParse } from "@langfuse/shared";import { IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE } from "@langfuse/shared/in-app-agent";+import type { AgUiMessage } from "@langfuse/shared/in-app-agent";import type { api } from "@/src/utils/api";import { assertUnreachable } from "@/src/utils/types";@@ -131,7 +132,7 @@ export function getInAppAgentTrpcInvalidationTargets(toolName: string) {);}-export function shouldPerformToolSideEffects(toolError: unknown) {+function shouldPerformToolSideEffects(toolError: unknown) {const parsedError =typeof toolError === "string" ? safeJsonParse(toolError) : toolError;@@ -146,7 +147,7 @@ export function shouldPerformToolSideEffects(toolError: unknown) {return parsedError.code !== IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE;}-export function performTargetInvalidation(+function performTargetInvalidation(target: InAppAgentTrpcInvalidationTarget,utils: ReturnType<typeof api.useUtils>,) {@@ -196,16 +197,81 @@ export function performTargetInvalidation(return assertUnreachable(target);}-export function performToolSideEffects({- toolName,+export type CompletedToolCall = {+ toolCallId: string;+ toolName: string;+ toolError?: unknown;+};++/**+ * Reconstruct completed tool calls from the durable conversation messages.+ * Background runs can finish while the drawer is detached, so the browser+ * cannot rely on having observed the live TOOL_CALL_RESULT event.+ */+export function getCompletedToolCalls(+ messages: readonly AgUiMessage[],+): CompletedToolCall[] {+ const toolCalls = new Map<string, Omit<CompletedToolCall, "toolError">>();+ const toolResults = new Map<string, Extract<AgUiMessage, { role: "tool" }>>();++ for (const message of messages) {+ if (message.role === "assistant") {+ for (const toolCall of message.toolCalls ?? []) {+ toolCalls.set(toolCall.id, {+ toolCallId: toolCall.id,+ toolName: toolCall.function.name,+ });+ }+ continue;+ }++ if (message.role === "tool") {+ toolResults.set(message.toolCallId, message);+ }+ }++ return Array.from(toolCalls.values()).flatMap((toolCall) => {+ const result = toolResults.get(toolCall.toolCallId);+ // No result message means the call never completed, so nothing was written.+ return result ? [{ ...toolCall, toolError: result.error }] : [];+ });+}++/**+ * Single entrypoint for both execution paths: live TOOL_CALL_RESULT events pass+ * one call, snapshot replay passes every completed call in the transcript.+ * `handledToolCallIds` makes the two idempotent against each other, and the+ * targets are unioned so a long transcript still invalidates each route once.+ */+export function performToolSideEffectsForCompletedToolCalls({+ toolCalls,+ handledToolCallIds,utils,}: {- toolName: string;+ toolCalls: readonly CompletedToolCall[];+ handledToolCallIds: Set<string>;utils: ReturnType<typeof api.useUtils>;}) {- const targets = getInAppAgentTrpcInvalidationTargets(toolName);+ const targets = new Set<InAppAgentTrpcInvalidationTarget>();++ for (const toolCall of toolCalls) {+ if (handledToolCallIds.has(toolCall.toolCallId)) {+ continue;+ }++ handledToolCallIds.add(toolCall.toolCallId);+ if (!shouldPerformToolSideEffects(toolCall.toolError)) {+ continue;+ }++ for (const target of getInAppAgentTrpcInvalidationTargets(+ toolCall.toolName,+ )) {+ targets.add(target);+ }+ }return Promise.all(- targets.map((target) => performTargetInvalidation(target, utils)),+ Array.from(targets, (target) => performTargetInvalidation(target, utils)),);}diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts b/web/src/features/in-app-agent/lib/backgroundExecutionSession.tsindex b8d2d0d9d2..d9d13a4c3c 100644--- a/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts+++ b/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts@@ -111,6 +111,9 @@ export class BackgroundExecutionSessionController implements BackgroundExecutioninput: ApprovalDecision,) => Promise<unknown>;private readonly onSettled?: () => void;+ private readonly onHydratedSnapshot?: (+ snapshot: BackgroundExecutionHydration,+ ) => void;private readonly onError?: (error: unknown) => void;private readonly agentSubscription: { unsubscribe(): void };private readonly listeners = new Set<() => void>();@@ -125,6 +128,12 @@ export class BackgroundExecutionSessionController implements BackgroundExecutiondecideApproval: (input: ApprovalDecision) => Promise<unknown>;subscriber?: BackgroundExecutionAgentSubscriber;onSettled?: () => void;+ /**+ * A durable snapshot has replaced the local message list, so every+ * completed tool call it contains is authoritative regardless of run+ * status. Fires on every hydration, so the consumer must be idempotent.+ */+ onHydratedSnapshot?: (snapshot: BackgroundExecutionHydration) => void;onError?: (error: unknown) => void;initialView?: Partial<BackgroundExecutionView>;}) {@@ -133,6 +142,7 @@ export class BackgroundExecutionSessionController implements BackgroundExecutionthis.cancelRun = config.cancelRun;this.decideApproval = config.decideApproval;this.onSettled = config.onSettled;+ this.onHydratedSnapshot = config.onHydratedSnapshot;this.onError = config.onError;this.view = {messages: [],@@ -469,6 +479,8 @@ export class BackgroundExecutionSessionController implements BackgroundExecutionattachment: { status: "detached" },});+ this.onHydratedSnapshot?.(hydrated);+return true;}