Skip to content

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

feat(in-app-agent): track tool approval decisions (#15811)

Lysander Kiesel3ca69f848499
diff --git a/packages/shared/src/in-app-agent/server/agent.ts b/packages/shared/src/in-app-agent/server/agent.ts
index d5ffddf4f0..5e14f4da93 100644
--- a/packages/shared/src/in-app-agent/server/agent.ts
+++ b/packages/shared/src/in-app-agent/server/agent.ts
@@ -496,6 +496,7 @@ export async function createAgUiStream(params: {
params.options.onApprovedToolCallExecuted,
});
const pendingSyntheticEvents = [...runInput.syntheticEvents];
+ currentAdapter.setDeveloperGuidance(runInput.developerGuidance);
if (
forwardedProps?.command?.resume?.approved === true &&
@@ -539,6 +540,7 @@ export async function createAgUiStream(params: {
cleanupAdapter = currentAdapter.cleanup;
interruptAdapter = currentAdapter.interrupt;
+ currentAdapter.setDeveloperGuidance(runInput.developerGuidance);
}
subscription = currentAdapter.adapter.run(runInput.input).subscribe({
@@ -811,10 +813,17 @@ async function createMastraAdapter(params: {
params.options.awsBedrock.modelId,
);
+ // @ag-ui/mastra currently forwards only assistant, user, and tool
+ // messages. Keep approval outcomes as developer messages in the AG-UI
+ // transcript, while mirroring them through Mastra's model-facing
+ // instruction channel so the model receives the same higher-priority
+ // guidance on resumed runs.
+ let developerGuidance: string | undefined;
const agent = new Agent({
id: "langfuse-in-app-assistant",
name: ASSISTANT_TITLE,
- instructions: params.instructions,
+ instructions: () =>
+ [params.instructions, developerGuidance].filter(Boolean).join("\n\n"),
model: bedrock(
params.options.awsBedrock.modelId as Parameters<typeof bedrock>[0],
),
@@ -844,6 +853,9 @@ async function createMastraAdapter(params: {
return {
adapter,
+ setDeveloperGuidance: (guidance: string | undefined) => {
+ developerGuidance = guidance;
+ },
executeToolCall: async (
approvalRequest: InAppAgentToolApprovalRequest,
) => {
diff --git a/packages/shared/src/in-app-agent/server/human-in-the-loop.ts b/packages/shared/src/in-app-agent/server/human-in-the-loop.ts
index d893a29944..dd9672a054 100644
--- a/packages/shared/src/in-app-agent/server/human-in-the-loop.ts
+++ b/packages/shared/src/in-app-agent/server/human-in-the-loop.ts
@@ -24,6 +24,8 @@ const MANUAL_TOOL_APPROVAL_REJECTION_ERROR = JSON.stringify({
message: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
});
+type DeveloperGuidanceMessage = Extract<AgUiMessage, { role: "developer" }>;
+
export const IN_APP_AGENT_PENDING_TOOL_APPROVAL_TTL_SECONDS = 60 * 60;
const PendingToolApprovalSchema = z.object({
@@ -166,6 +168,7 @@ export function parseInAppAgentInterruptEvent(
export type ManualToolApprovalRunInput = {
input: AgUiRunAgentInput;
syntheticEvents: AgUiEvent[];
+ developerGuidance?: string;
toolCallApproval?: {
toolCallId: string;
status: "approved" | "rejected";
@@ -189,6 +192,7 @@ export async function createManualToolApprovalRunInput(params: {
if (!approved) {
const assistantMessage =
createManualToolCallAssistantMessage(approvalRequest);
+ const guidanceMessage = createToolRejectionGuidanceMessage(approvalRequest);
const toolMessage: AgUiMessage = {
id: createManualToolResultMessageId(approvalRequest),
role: "tool",
@@ -204,7 +208,7 @@ export async function createManualToolApprovalRunInput(params: {
...params.input.messages,
assistantMessage,
toolMessage,
- createToolRejectionGuidanceMessage(approvalRequest),
+ guidanceMessage,
],
forwardedProps: {},
},
@@ -213,6 +217,7 @@ export async function createManualToolApprovalRunInput(params: {
toolResultContent: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
toolError: MANUAL_TOOL_APPROVAL_REJECTION_ERROR,
}),
+ developerGuidance: guidanceMessage.content,
toolCallApproval: {
toolCallId: approvalRequest.toolCallId,
status: "rejected",
@@ -230,6 +235,12 @@ export async function createManualToolApprovalRunInput(params: {
const assistantMessage =
createManualToolCallAssistantMessage(approvalRequest);
const modelToolResultContent = serializeToolResultContent(modelToolResult);
+ // A successful tool call needs no guidance: the assistant tool call plus its
+ // tool result already carry the outcome. Only the error path needs to tell
+ // the model how to proceed.
+ const guidanceMessage = toolError
+ ? createToolExecutionErrorGuidanceMessage(approvalRequest, toolError)
+ : undefined;
const toolMessage: AgUiMessage = {
id: createManualToolResultMessageId(approvalRequest),
role: "tool",
@@ -250,18 +261,12 @@ export async function createManualToolApprovalRunInput(params: {
...params.input.messages,
assistantMessage,
toolMessage,
- ...(toolError
- ? [
- createToolExecutionErrorGuidanceMessage(
- approvalRequest,
- toolError,
- ),
- ]
- : []),
+ ...(guidanceMessage ? [guidanceMessage] : []),
],
forwardedProps: {},
},
syntheticEvents,
+ developerGuidance: guidanceMessage?.content,
toolCallApproval: {
toolCallId: approvalRequest.toolCallId,
status: "approved",
@@ -271,7 +276,7 @@ export async function createManualToolApprovalRunInput(params: {
function createToolRejectionGuidanceMessage(
approvalRequest: InAppAgentToolApprovalRequest,
-): AgUiMessage {
+): DeveloperGuidanceMessage {
return {
id: `${approvalRequest.toolCallId}-approval-rejection-guidance`,
role: "developer",
@@ -327,6 +332,7 @@ export function createManualToolCallAssistantMessage(
return {
id: createManualToolCallParentMessageId(approvalRequest),
role: "assistant",
+ content: "",
toolCalls: [
{
id: approvalRequest.toolCallId,
@@ -344,7 +350,7 @@ export function createManualToolCallAssistantMessage(
function createToolExecutionErrorGuidanceMessage(
approvalRequest: InAppAgentToolApprovalRequest,
toolError: string,
-): AgUiMessage {
+): DeveloperGuidanceMessage {
const args = serializeToolCallArgs(approvalRequest.args);
return {
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index ca70ad9423..aae0749ac3 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -741,10 +741,10 @@ describe("createAgUiStream", () => {
expect(promptMocks.compile.mock.calls[0]?.[0].screenContext).not.toContain(
'"user_name"',
);
- expect(Agent).toHaveBeenCalledWith(
- expect.objectContaining({
- instructions: "Prompt-managed assistant instructions",
- }),
+ const baseInstructions = vi.mocked(Agent).mock.calls[0]?.[0].instructions;
+ expect(baseInstructions).toEqual(expect.any(Function));
+ expect((baseInstructions as () => string)()).toBe(
+ "Prompt-managed assistant instructions",
);
expect(persistedEvents.map((event) => event.type)).toEqual([
EventType.RUN_STARTED,
@@ -947,9 +947,10 @@ describe("createAgUiStream", () => {
expect.objectContaining({
forwardedProps: {},
messages: expect.arrayContaining([
- {
+ expect.objectContaining({
id: "tool-call-1-approval-tool-call",
role: "assistant",
+ content: "",
runId: "interrupted-run-1",
toolCalls: [
{
@@ -966,8 +967,8 @@ describe("createAgUiStream", () => {
},
},
],
- },
- {
+ }),
+ expect.objectContaining({
id: "tool-call-1-approval-tool-result",
role: "tool",
toolCallId: "tool-call-1",
@@ -976,7 +977,7 @@ describe("createAgUiStream", () => {
name: "readiness",
dataType: "NUMERIC",
}),
- },
+ }),
]),
}),
]);
@@ -1488,6 +1489,12 @@ describe("createAgUiStream", () => {
expect(adapterEvents.createScoreConfigExecute).not.toHaveBeenCalled();
expect(vi.mocked(MCPClient)).toHaveBeenCalledOnce();
expect(vi.mocked(Agent)).toHaveBeenCalledOnce();
+ const rejectionInstructions =
+ vi.mocked(Agent).mock.calls[0]?.[0].instructions;
+ expect(rejectionInstructions).toEqual(expect.any(Function));
+ expect((rejectionInstructions as () => string)()).toContain(
+ "Do not retry this tool call",
+ );
expect(persistedEvents).toEqual([
{
type: EventType.RUN_STARTED,
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
index dff41a3e30..9081df6c51 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -50,7 +50,10 @@ import {
import styles from "./InAppAgentMessage.module.css";
import { InAppAgentToolPayload } from "./InAppAgentToolPayload";
import { InAppAgentToolResultPayload } from "./InAppAgentToolResultPayload";
-import { type InAppAgentToolCallContent } from "@/src/features/in-app-agent/components/utils/utils";
+import {
+ getInAppAgentToolDisplayName,
+ type InAppAgentToolCallContent,
+} from "@/src/features/in-app-agent/components/utils/utils";
export type InAppAgentMessageRole = "assistant" | "user";
@@ -718,11 +721,12 @@ function ToolCallDisclosure({
isCompact: boolean;
}) {
const status = tool.status;
+ const displayName = getInAppAgentToolDisplayName(tool.name);
return (
<details className="group/tool min-w-0">
<summary
- aria-label={`${tool.name}: ${status}`}
+ aria-label={`${displayName}: ${status}`}
className={cn(
"hover:text-foreground focus-visible:ring-ring flex cursor-pointer list-none items-center gap-1.5 rounded-md px-1 py-0.5 text-xs leading-4 font-bold outline-none focus-visible:ring-2 focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden",
isCompact && "px-0.5",
@@ -735,9 +739,9 @@ function ToolCallDisclosure({
status === "failed" && "text-destructive",
status === "denied" && "text-dark-yellow",
)}
- title={tool.name}
+ title={displayName}
>
- {tool.name}
+ {displayName}
</span>
</summary>
<div className={cn("mt-1.5 mb-1 ml-3 px-3", isCompact && "px-2.5")}>
diff --git a/web/src/features/in-app-agent/components/InAppAgentToolCallCard.tsx b/web/src/features/in-app-agent/components/InAppAgentToolCallCard.tsx
index 0babae7c78..b2b7e9b294 100644
--- a/web/src/features/in-app-agent/components/InAppAgentToolCallCard.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentToolCallCard.tsx
@@ -5,7 +5,10 @@ import { Button } from "@/src/components/ui/button";
import { cn } from "@/src/utils/tailwind";
import { InAppAgentToolPayload } from "./InAppAgentToolPayload";
import { InAppAgentToolResultPayload } from "./InAppAgentToolResultPayload";
-import { type InAppAgentToolCallContent } from "@/src/features/in-app-agent/components/utils/utils";
+import {
+ getInAppAgentToolDisplayName,
+ type InAppAgentToolCallContent,
+} from "@/src/features/in-app-agent/components/utils/utils";
export function InAppAgentToolCallCard({
tool,
@@ -23,8 +26,9 @@ export function InAppAgentToolCallCard({
const approval = tool.approval;
const isApprovalPending = approval?.status === "pending";
const isApprovalSubmitting = approval?.status === "submitting";
- const approveLabel = `Approve ${tool.name}?`;
- const usedLabel = `Used ${tool.name}`;
+ const displayName = getInAppAgentToolDisplayName(tool.name);
+ const approveLabel = `Approve ${displayName}?`;
+ const usedLabel = `Used ${displayName}`;
return (
<div
diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
index 573b4c82be..092d7c7cf7 100644
--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -1691,8 +1691,10 @@ function InAppAiAgentProviderInner({
toolCallId: params.approval.approvalRequest.toolCallId,
approved: params.approved,
});
+ return true;
} catch (error) {
setError(getInAppAgentError(error));
+ return false;
}
},
[conversationQuery.data, ensureSubscription, getOrCreateAgent],
@@ -1723,14 +1725,25 @@ function InAppAiAgentProviderInner({
}
if (backgroundExecutionEnabled) {
- await decideBackgroundToolApproval({
+ const decisionAccepted = await decideBackgroundToolApproval({
approval,
approved,
conversationId: selectedConversationId,
});
+ if (decisionAccepted) {
+ capture("in_app_agent:tool_approval_decided", {
+ isApproved: approved,
+ toolName: approval.approvalRequest.toolName,
+ });
+ }
return;
}
+ capture("in_app_agent:tool_approval_decided", {
+ isApproved: approved,
+ toolName: approval.approvalRequest.toolName,
+ });
+
const agent = agentRef.current;
if (!agent || agent.threadId !== selectedConversationId) {
showErrorToast(
@@ -1808,6 +1821,7 @@ function InAppAiAgentProviderInner({
},
[
backgroundExecutionEnabled,
+ capture,
decideBackgroundToolApproval,
effectivePendingToolApprovals,
ensureSubscription,
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.ts
index 8d36dfa239..7e5490f7e4 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
@@ -1,11 +1,24 @@
import type { AgUiMessage } from "@langfuse/shared/in-app-agent";
import {
extractLangfuseDocsSources,
+ getInAppAgentToolDisplayName,
getDrawerMessages,
getInAppAgentError,
isInAppAgentRateLimited,
type InAppAiAgentMessage,
} from "./utils";
+
+describe("getInAppAgentToolDisplayName", () => {
+ it.each([
+ ["docs_search", "search"],
+ ["langfuse_getTraces", "getTraces"],
+ ["langfuseDocs_search", "search"],
+ ["read", "read"],
+ ])("strips a display-only namespace from %s", (toolName, expected) => {
+ expect(getInAppAgentToolDisplayName(toolName)).toBe(expected);
+ });
+});
+
describe("getInAppAgentError", () => {
const now = new Date("2026-07-08T20:00:54.997Z").getTime();
const rateLimitError = {
diff --git a/web/src/features/in-app-agent/components/utils/utils.ts b/web/src/features/in-app-agent/components/utils/utils.ts
index 38c768bcf6..c1ca7ea343 100644
--- a/web/src/features/in-app-agent/components/utils/utils.ts
+++ b/web/src/features/in-app-agent/components/utils/utils.ts
@@ -43,6 +43,10 @@ export type InAppAgentToolCallContent = {
};
};
+export function getInAppAgentToolDisplayName(toolName: string): string {
+ return toolName.replace(/^(?:docs_|langfuseDocs_|langfuse_)/, "");
+}
+
const InAppAgentToolRejectionErrorSchema = z.object({
code: z.literal(IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE),
message: z.string(),
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 95355ad9b1..1677216082 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -309,6 +309,7 @@ export const events = {
"new_chat_started",
"new_chat_turn",
"quick_action_started",
+ "tool_approval_decided",
],
cmd_k_menu: ["opened", "search_entered", "navigated"],
spend_alert: ["created", "updated", "deleted"],