Skip to content

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

feat(in-app-agent): let the assistant ask the user a short questionnaire (#18828)

Tobias Wochingera51960b99f33
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.md
index 5602ad2237..a37385daae 100644
--- a/packages/shared/AGENTS.md
+++ b/packages/shared/AGENTS.md
@@ -186,7 +186,10 @@
- `@langfuse/shared/in-app-agent` via `src/in-app-agent/index.ts`:
client-safe durable in-app-agent contracts: AG-UI messages/events/context,
run requests/status/errors, approval events, constants, message helpers,
- and interrupt parsing. Never re-export server code here.
+ interrupt parsing, and the questionnaire tool contract (`questionnaire.ts`:
+ args, positional answers carried on `approvalDecision` requests, result, and
+ the shared resolver web and worker both validate with). Never re-export
+ server code here.
- In-app-agent server contracts use explicit subpaths only:
`persistence`, `runLifecycle`, `tunables`, `eventCompaction`, `mcpPolicy`,
`toolResults`, `toolErrors`, `systemPrompt`, and `modelProvider`. These are
diff --git a/packages/shared/src/features/inAppAgent/types.ts b/packages/shared/src/features/inAppAgent/types.ts
index d7e6fa2ab3..4d114ace81 100644
--- a/packages/shared/src/features/inAppAgent/types.ts
+++ b/packages/shared/src/features/inAppAgent/types.ts
@@ -1,5 +1,6 @@
import z from "zod";
import { AgUiContextSchema } from "../../in-app-agent/schema";
+import { InAppAgentToolInputsSchema } from "../../in-app-agent/toolInputs";
/**
* Lifecycle states of an in-app agent run (`in_app_agent_runs.status`).
@@ -20,6 +21,36 @@ export enum InAppAgentRunStatus {
export const InAppAgentRunStatusSchema = z.enum(InAppAgentRunStatus);
+/** Runs that are not yet in a terminal state, including parked approvals. */
+export const IN_APP_AGENT_UNSETTLED_RUN_STATUSES = [
+ InAppAgentRunStatus.QUEUED,
+ InAppAgentRunStatus.RUNNING,
+ InAppAgentRunStatus.AWAITING_APPROVAL,
+] as const;
+
+export type UnsettledInAppAgentRunStatus =
+ (typeof IN_APP_AGENT_UNSETTLED_RUN_STATUSES)[number];
+
+/** Complement of `IN_APP_AGENT_UNSETTLED_RUN_STATUSES`. */
+export type SettledInAppAgentRunStatus = Exclude<
+ InAppAgentRunStatus,
+ UnsettledInAppAgentRunStatus
+>;
+
+export function isUnsettledInAppAgentRunStatus(
+ status: InAppAgentRunStatus,
+): status is UnsettledInAppAgentRunStatus {
+ return (
+ IN_APP_AGENT_UNSETTLED_RUN_STATUSES as readonly InAppAgentRunStatus[]
+ ).includes(status);
+}
+
+export function isSettledInAppAgentRunStatus(
+ status: InAppAgentRunStatus,
+): status is SettledInAppAgentRunStatus {
+ return !isUnsettledInAppAgentRunStatus(status);
+}
+
/**
* Terminal error codes of an in-app agent run (`in_app_agent_runs.error_code`).
*
@@ -101,6 +132,8 @@ export const InAppAgentRunRequestSchema = z.discriminatedUnion("kind", [
continuationNumber: z.number().int().positive().optional(),
toolCallId: z.string(),
approved: z.boolean(),
+ /** User input for the approved tool, keyed by tool name. */
+ toolInputs: InAppAgentToolInputsSchema.optional(),
/** Inherited sanitized context; defaults for legacy continuation rows. */
context: z.array(AgUiContextSchema).default([]),
}),
diff --git a/packages/shared/src/in-app-agent/constants.ts b/packages/shared/src/in-app-agent/constants.ts
index 268bc80338..3dae466bed 100644
--- a/packages/shared/src/in-app-agent/constants.ts
+++ b/packages/shared/src/in-app-agent/constants.ts
@@ -1,43 +1,14 @@
-import { InAppAgentRunStatus } from "../features/inAppAgent/types";
-
// Avoid renaming this as the FE is aware of this when rendering, renaming it would cause history issues
export const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";
+// Persisted in transcripts like the redirect tool name; do not rename.
+export const IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME = "langfuse_askUserQuestions";
+
export const IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE = "tool_call_rejected";
export const IN_APP_AGENT_GENERIC_ERROR_MESSAGE =
"An error occurred. Please try again or start a new conversation.";
-/** Runs that are not yet in a terminal state, including parked approvals. */
-export const IN_APP_AGENT_UNSETTLED_RUN_STATUSES = [
- InAppAgentRunStatus.QUEUED,
- InAppAgentRunStatus.RUNNING,
- InAppAgentRunStatus.AWAITING_APPROVAL,
-] as const;
-
-export type UnsettledInAppAgentRunStatus =
- (typeof IN_APP_AGENT_UNSETTLED_RUN_STATUSES)[number];
-
-/** Complement of `IN_APP_AGENT_UNSETTLED_RUN_STATUSES`. */
-export type SettledInAppAgentRunStatus = Exclude<
- InAppAgentRunStatus,
- UnsettledInAppAgentRunStatus
->;
-
-export function isUnsettledInAppAgentRunStatus(
- status: InAppAgentRunStatus,
-): status is UnsettledInAppAgentRunStatus {
- return (
- IN_APP_AGENT_UNSETTLED_RUN_STATUSES as readonly InAppAgentRunStatus[]
- ).includes(status);
-}
-
-export function isSettledInAppAgentRunStatus(
- status: InAppAgentRunStatus,
-): status is SettledInAppAgentRunStatus {
- return !isUnsettledInAppAgentRunStatus(status);
-}
-
export const IN_APP_AGENT_SILENT_MCP_OUTPUT_TYPE = "silent-mcp-output";
export const IN_APP_AGENT_SILENT_MCP_OUTPUT_MESSAGE =
"Output saved to /workspace/tool_calls";
diff --git a/packages/shared/src/in-app-agent/index.ts b/packages/shared/src/in-app-agent/index.ts
index b558fa3d5e..7016e58fc7 100644
--- a/packages/shared/src/in-app-agent/index.ts
+++ b/packages/shared/src/in-app-agent/index.ts
@@ -6,4 +6,6 @@ export * from "./approvalEvents";
export * from "./constants";
export * from "./interrupts";
export * from "./messages";
+export * from "./questionnaire";
+export * from "./toolInputs";
export * from "../features/inAppAgent/types";
diff --git a/packages/shared/src/in-app-agent/questionnaire.test.ts b/packages/shared/src/in-app-agent/questionnaire.test.ts
new file mode 100644
index 0000000000..af3f5d4ad6
--- /dev/null
+++ b/packages/shared/src/in-app-agent/questionnaire.test.ts
@@ -0,0 +1,165 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ InAppAgentQuestionnaireArgsSchema,
+ resolveInAppAgentQuestionnaireAnswers,
+} from "./questionnaire";
+
+const args = {
+ questions: [
+ {
+ question: "Which evaluator type?",
+ options: [
+ {
+ label: "LLM-as-a-judge",
+ description: "Model-graded",
+ recommended: true,
+ },
+ { label: "Code", description: "Deterministic", recommended: false },
+ ],
+ allowMultiple: false,
+ },
+ {
+ question: "Which scores?",
+ options: [
+ {
+ label: "Helpfulness",
+ description: "Answers the ask",
+ recommended: false,
+ },
+ {
+ label: "Toxicity",
+ description: "Harmful content",
+ recommended: false,
+ },
+ ],
+ allowMultiple: true,
+ },
+ {
+ question: "Run it on a schedule?",
+ options: [
+ { label: "Yes", description: "Daily run", recommended: false },
+ { label: "No", description: "Manual only", recommended: false },
+ ],
+ allowMultiple: false,
+ },
+ ],
+};
+
+describe("resolveInAppAgentQuestionnaireAnswers", () => {
+ it("resolves selected options, custom text, and skipped questions", () => {
+ expect(
+ resolveInAppAgentQuestionnaireAnswers({
+ args,
+ answers: [
+ { selectedOptionIndexes: [], otherText: " Human review " },
+ { selectedOptionIndexes: [1, 0], otherText: "Latency" },
+ { selectedOptionIndexes: [], otherText: " " },
+ ],
+ }),
+ ).toEqual({
+ success: true,
+ result: {
+ type: "questionnaireAnswers",
+ answers: [
+ {
+ question: "Which evaluator type?",
+ answer: ["Human review"],
+ skipped: false,
+ },
+ {
+ question: "Which scores?",
+ answer: ["Toxicity", "Helpfulness", "Latency"],
+ skipped: false,
+ },
+ { question: "Run it on a schedule?", answer: [], skipped: true },
+ ],
+ },
+ });
+ });
+
+ it.each([
+ {
+ name: "missing answer entries",
+ answers: [{ selectedOptionIndexes: [0], otherText: null }],
+ },
+ {
+ name: "out-of-range option",
+ answers: [
+ { selectedOptionIndexes: [2], otherText: null },
+ { selectedOptionIndexes: [], otherText: null },
+ { selectedOptionIndexes: [], otherText: null },
+ ],
+ },
+ {
+ name: "multiple answers on a single-choice question",
+ answers: [
+ { selectedOptionIndexes: [0], otherText: "Other" },
+ { selectedOptionIndexes: [], otherText: null },
+ { selectedOptionIndexes: [], otherText: null },
+ ],
+ },
+ {
+ name: "duplicate selections",
+ answers: [
+ { selectedOptionIndexes: [], otherText: null },
+ { selectedOptionIndexes: [0, 0], otherText: null },
+ { selectedOptionIndexes: [], otherText: null },
+ ],
+ },
+ ])("rejects $name", ({ answers }) => {
+ expect(
+ resolveInAppAgentQuestionnaireAnswers({ args, answers }).success,
+ ).toBe(false);
+ });
+});
+
+describe("InAppAgentQuestionnaireArgsSchema", () => {
+ it("rejects a free-text question without options", () => {
+ expect(
+ InAppAgentQuestionnaireArgsSchema.safeParse({
+ questions: [{ ...args.questions[0], options: [] }],
+ }).success,
+ ).toBe(false);
+ });
+
+ it("rejects more than one recommended option per question", () => {
+ const [firstQuestion] = args.questions;
+ const result = InAppAgentQuestionnaireArgsSchema.safeParse({
+ questions: [
+ {
+ ...firstQuestion,
+ options: firstQuestion.options.map((option) => ({
+ ...option,
+ recommended: true,
+ })),
+ },
+ ],
+ });
+
+ expect(result.success).toBe(false);
+ expect(InAppAgentQuestionnaireArgsSchema.safeParse(args).success).toBe(
+ true,
+ );
+ });
+
+ it.each([
+ { name: "a missing description", description: null },
+ { name: "a blank description", description: " " },
+ ])("rejects an option with $name", ({ description }) => {
+ const [firstQuestion] = args.questions;
+ const result = InAppAgentQuestionnaireArgsSchema.safeParse({
+ questions: [
+ {
+ ...firstQuestion,
+ options: [
+ { ...firstQuestion.options[0], description },
+ firstQuestion.options[1],
+ ],
+ },
+ ],
+ });
+
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/packages/shared/src/in-app-agent/questionnaire.ts b/packages/shared/src/in-app-agent/questionnaire.ts
new file mode 100644
index 0000000000..f5be1675ff
--- /dev/null
+++ b/packages/shared/src/in-app-agent/questionnaire.ts
@@ -0,0 +1,200 @@
+import z from "zod";
+
+export const IN_APP_AGENT_QUESTIONNAIRE_MAX_QUESTIONS = 4;
+export const IN_APP_AGENT_QUESTIONNAIRE_MIN_OPTIONS = 2;
+export const IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS = 4;
+export const IN_APP_AGENT_QUESTIONNAIRE_MAX_ANSWER_LENGTH = 2000;
+
+// Every field is required (nullable instead of optional) so the schema stays
+// valid for OpenAI strict tool calling. Questions and options are addressed by
+// position, so the model never has to invent ids.
+const InAppAgentQuestionnaireOptionSchema = z.object({
+ label: z.string().min(1).max(200),
+ description: z
+ .string()
+ .max(500)
+ .refine((description) => description.trim().length > 0, {
+ message: "Give every option a description.",
+ })
+ .describe("One short sentence explaining the option."),
+ recommended: z
+ .boolean()
+ .describe("Mark at most one option per question as recommended."),
+});
+
+const InAppAgentQuestionnaireQuestionSchema = z.object({
+ question: z.string().min(1).max(500),
+ options: z
+ .array(InAppAgentQuestionnaireOptionSchema)
+ .min(IN_APP_AGENT_QUESTIONNAIRE_MIN_OPTIONS)
+ .max(IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS)
+ .refine(
+ (options) => options.filter((option) => option.recommended).length <= 1,
+ { message: "Mark at most one option per question as recommended." },
+ )
+ .describe(
+ `${IN_APP_AGENT_QUESTIONNAIRE_MIN_OPTIONS} to ${IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS} distinct answer options, each with a description. Do not add an "Other" option; the user can always type a custom answer.`,
+ ),
+ allowMultiple: z
+ .boolean()
+ .describe("Whether the user may select more than one option."),
+});
+
+export const InAppAgentQuestionnaireArgsSchema = z.object({
+ questions: z
+ .array(InAppAgentQuestionnaireQuestionSchema)
+ .min(1)
+ .max(IN_APP_AGENT_QUESTIONNAIRE_MAX_QUESTIONS),
+});
+
+export type InAppAgentQuestionnaireArgs = z.infer<
+ typeof InAppAgentQuestionnaireArgsSchema
+>;
+
+export type InAppAgentQuestionnaireQuestion =
+ InAppAgentQuestionnaireArgs["questions"][number];
+
+const InAppAgentQuestionnaireAnswerSchema = z.object({
+ selectedOptionIndexes: z
+ .array(z.number().int().nonnegative())
+ .max(IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS)
+ .refine((indexes) => new Set(indexes).size === indexes.length, {
+ message: "Select each option at most once.",
+ }),
+ otherText: z
+ .string()
+ .max(IN_APP_AGENT_QUESTIONNAIRE_MAX_ANSWER_LENGTH)
+ .nullable(),
+});
+
+/** One entry per question, in question order. An empty entry means skipped. */
+export const InAppAgentQuestionnaireAnswersSchema = z
+ .array(InAppAgentQuestionnaireAnswerSchema)
+ .max(IN_APP_AGENT_QUESTIONNAIRE_MAX_QUESTIONS);
+
+export type InAppAgentQuestionnaireAnswers = z.infer<
+ typeof InAppAgentQuestionnaireAnswersSchema
+>;
+
+export type InAppAgentQuestionnaireAnswer =
+ InAppAgentQuestionnaireAnswers[number];
+
+export const InAppAgentQuestionnaireResultSchema = z.object({
+ type: z.literal("questionnaireAnswers"),
+ answers: z.array(
+ z.object({
+ question: z.string(),
+ answer: z.array(z.string()),
+ skipped: z.boolean(),
+ }),
+ ),
+});
+
+export type InAppAgentQuestionnaireResult = z.infer<
+ typeof InAppAgentQuestionnaireResultSchema
+>;
+
+/**
+ * Answers schema bound to the questions the model asked. Parsing checks every
+ * answer against its question and outputs the tool result the model reads.
+ */
+export function createInAppAgentQuestionnaireAnswersSchema(
+ questions: readonly InAppAgentQuestionnaireQuestion[],
+) {
+ return InAppAgentQuestionnaireAnswersSchema.length(questions.length, {
+ message: "Expected exactly one answer entry per question.",
+ })
+ .superRefine((answers, ctx) => {
+ if (answers.length !== questions.length) {
+ return;
+ }
+ for (const [index, question] of questions.entries()) {
+ if (!isValidAnswer(question, answers[index])) {
+ ctx.addIssue({
+ code: "custom",
+ path: [index],
+ message: `Invalid answer for question ${index + 1}.`,
+ });
+ }
+ }
+ })
+ .transform(
+ (answers): InAppAgentQuestionnaireResult => ({
+ type: "questionnaireAnswers",
+ answers: questions.map((question, index) => {
+ const answer = toAnswerLabels(question, answers[index]);
+ return {
+ question: question.question,
+ answer,
+ skipped: answer.length === 0,
+ };
+ }),
+ }),
+ );
+}
+
+/**
+ * Validates user answers against the questions the model asked and turns
+ * them into the tool result the model reads. Shared by the decision endpoint
+ * (to reject bad input early) and the worker tool execution.
+ */
+export function resolveInAppAgentQuestionnaireAnswers({
+ args,
+ answers,
+}: {
+ args: unknown;
+ answers: unknown;
+}):
+ | { success: true; result: InAppAgentQuestionnaireResult }
+ | { success: false; error: string } {
+ const parsedArgs = InAppAgentQuestionnaireArgsSchema.safeParse(args);
+ if (!parsedArgs.success) {
+ return { success: false, error: "Invalid questionnaire questions." };
+ }
+
+ const parsedAnswers = createInAppAgentQuestionnaireAnswersSchema(
+ parsedArgs.data.questions,
+ ).safeParse(answers);
+ if (!parsedAnswers.success) {
+ return {
+ success: false,
+ error:
+ parsedAnswers.error.issues[0]?.message ??
+ "Invalid questionnaire answers.",
+ };
+ }
+
+ return { success: true, result: parsedAnswers.data };
+}
+
+function getOtherText(answer: InAppAgentQuestionnaireAnswer): string | null {
+ return answer.otherText?.trim() || null;
+}
+
+function isValidAnswer(
+ question: InAppAgentQuestionnaireQuestion,
+ answer: InAppAgentQuestionnaireAnswer,
+): boolean {
+ const { selectedOptionIndexes } = answer;
+ const isOutOfRange = selectedOptionIndexes.some(
+ (optionIndex) => optionIndex >= question.options.length,
+ );
+ if (isOutOfRange) {
+ return false;
+ }
+
+ const answerCount =
+ selectedOptionIndexes.length + (getOtherText(answer) ? 1 : 0);
+ return question.allowMultiple || answerCount <= 1;
+}
+
+function toAnswerLabels(
+ question: InAppAgentQuestionnaireQuestion,
+ answer: InAppAgentQuestionnaireAnswer,
+): string[] {
+ const labels = answer.selectedOptionIndexes.map(
+ (optionIndex) => question.options[optionIndex].label,
+ );
+ const otherText = getOtherText(answer);
+ return otherText === null ? labels : [...labels, otherText];
+}
diff --git a/packages/shared/src/in-app-agent/server/mcpPolicy.ts b/packages/shared/src/in-app-agent/server/mcpPolicy.ts
index 6e22ff28f7..50375535bd 100644
--- a/packages/shared/src/in-app-agent/server/mcpPolicy.ts
+++ b/packages/shared/src/in-app-agent/server/mcpPolicy.ts
@@ -590,13 +590,22 @@ export function withInAppAgentToolApproval<TTool extends InAppAgentTool>(
return Object.fromEntries(
Object.entries(tools).map(([toolName, tool]) => [
toolName,
- isInAppAgentAutoApprovedToolName(toolName, policy)
+ isInAppAgentAutoApprovedToolName(toolName, policy) ||
+ hasConditionalApproval(tool)
? tool
: { ...tool, requireApproval: true },
]),
) as Record<string, TTool | (TTool & { requireApproval: true })>;
}
+// A function-valued requireApproval decides per call; Mastra runs it before
+// pausing, so overwriting it would drop the tool's own decision.
+function hasConditionalApproval(tool: InAppAgentTool) {
+ return (
+ "requireApproval" in tool && typeof tool.requireApproval === "function"
+ );
+}
+
function isInAppAgentAutoApprovedToolName(
toolName: string,
policy: InAppAgentToolPolicy,
diff --git a/packages/shared/src/in-app-agent/server/persistence.ts b/packages/shared/src/in-app-agent/server/persistence.ts
index 07b7887595..4db85e0536 100644
--- a/packages/shared/src/in-app-agent/server/persistence.ts
+++ b/packages/shared/src/in-app-agent/server/persistence.ts
@@ -7,7 +7,7 @@ import {
InAppAgentRunStatus,
} from "../../features/inAppAgent/types";
import { ChatMessageRole, ChatMessageType, logger } from "../../server";
-import { isSettledInAppAgentRunStatus } from "../constants";
+import { isSettledInAppAgentRunStatus } from "../../features/inAppAgent/types";
import { recordRunTerminalOutcome } from "./runMetrics";
import { Prisma } from "../../db";
import type { InAppAgentConversation, PrismaClient } from "../../db";
diff --git a/packages/shared/src/in-app-agent/server/runLifecycle.ts b/packages/shared/src/in-app-agent/server/runLifecycle.ts
index d35a27a21d..a5d7ff90af 100644
--- a/packages/shared/src/in-app-agent/server/runLifecycle.ts
+++ b/packages/shared/src/in-app-agent/server/runLifecycle.ts
@@ -10,16 +10,15 @@ import { logger } from "../../server";
import { recordRunTerminalOutcome } from "./runMetrics";
import { buildInAppAgentApprovalDecisionEvent } from "../approvalEvents";
import type { AgUiEvent } from "../schema";
+import type { InAppAgentToolInputs } from "../toolInputs";
import type { InAppAgentPrefixedLangfuseMcpToolName } from "./mcpPolicy";
import {
+ IN_APP_AGENT_UNSETTLED_RUN_STATUSES,
InAppAgentRunRequestSchema,
+ isSettledInAppAgentRunStatus,
resolveInAppAgentRootRunId,
type InAppAgentRunRequest,
} from "../../features/inAppAgent/types";
-import {
- IN_APP_AGENT_UNSETTLED_RUN_STATUSES,
- isSettledInAppAgentRunStatus,
-} from "../constants";
import {
ACTIVE_RUN_CONFLICT_MESSAGE,
lockConversation,
@@ -230,6 +229,8 @@ export async function decideToolApproval(params: {
decidedByUserId: string;
/** Prefixed tool resolved from the persisted interrupt, never client input. */
alwaysAllowToolName?: InAppAgentPrefixedLangfuseMcpToolName;
+ /** Tool input, already validated against the persisted interrupt. */
+ toolInputs?: InAppAgentToolInputs;
model?: string;
}): Promise<InAppAgentRun> {
const outcome = await params.prisma.$transaction(async (tx) => {
@@ -379,6 +380,7 @@ export async function decideToolApproval(params: {
continuationNumber,
toolCallId: params.toolCallId,
approved: params.approved,
+ ...(params.toolInputs ? { toolInputs: params.toolInputs } : {}),
context: parentRequest.success ? parentRequest.data.context : [],
},
}),
diff --git a/packages/shared/src/in-app-agent/server/runMetrics.ts b/packages/shared/src/in-app-agent/server/runMetrics.ts
index 3f3916bf1d..5c634f9c35 100644
--- a/packages/shared/src/in-app-agent/server/runMetrics.ts
+++ b/packages/shared/src/in-app-agent/server/runMetrics.ts
@@ -1,6 +1,6 @@
import { InAppAgentRunErrorCode } from "../../features/inAppAgent/types";
import { recordIncrement } from "../../server";
-import type { SettledInAppAgentRunStatus } from "../constants";
+import type { SettledInAppAgentRunStatus } from "../../features/inAppAgent/types";
const RUN_COMPLETED_METRIC = "langfuse.in_app_agent.run.completed";
diff --git a/packages/shared/src/in-app-agent/toolInputs.ts b/packages/shared/src/in-app-agent/toolInputs.ts
new file mode 100644
index 0000000000..a6ce5fb93e
--- /dev/null
+++ b/packages/shared/src/in-app-agent/toolInputs.ts
@@ -0,0 +1,78 @@
+import z from "zod";
+
+import { IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME } from "./constants";
+import {
+ InAppAgentQuestionnaireAnswersSchema,
+ resolveInAppAgentQuestionnaireAnswers,
+} from "./questionnaire";
+
+/**
+ * User input sent with a tool approval, keyed by the tool that consumes it.
+ * The worker hands each tool its own entry as resume data.
+ */
+export const InAppAgentToolInputsSchema = z.strictObject({
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: z
+ .object({ answers: InAppAgentQuestionnaireAnswersSchema })
+ .optional(),
+});
+
+export type InAppAgentToolInputs = z.infer<typeof InAppAgentToolInputsSchema>;
+
+export type InAppAgentToolWithInputs = keyof InAppAgentToolInputs;
+
+type ToolInputValidationResult =
+ | { success: true }
+ | { success: false; error: string };
+
+type ToolInputValidators = {
+ [ToolName in InAppAgentToolWithInputs]: (params: {
+ args: unknown;
+ input: NonNullable<InAppAgentToolInputs[ToolName]>;
+ }) => ToolInputValidationResult;
+};
+
+// Checks the input against the tool call the model persisted, so the worker
+// never resumes a tool with input that does not fit its arguments.
+const toolInputValidators: ToolInputValidators = {
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: ({ args, input }) =>
+ resolveInAppAgentQuestionnaireAnswers({ args, answers: input.answers }),
+};
+
+export function isInAppAgentToolWithInputs(
+ toolName: string,
+): toolName is InAppAgentToolWithInputs {
+ return Object.hasOwn(toolInputValidators, toolName);
+}
+
+/**
+ * Tool inputs are only accepted for an approved call of a tool that takes
+ * input, and such a tool cannot be approved without them.
+ */
+export function validateInAppAgentToolInputs(params: {
+ toolName: string;
+ args: unknown;
+ approved: boolean;
+ toolInputs: InAppAgentToolInputs | undefined;
+}): ToolInputValidationResult {
+ const { toolName, args, approved, toolInputs } = params;
+ const providedToolNames = Object.entries(toolInputs ?? {}).flatMap(
+ ([name, input]) => (input === undefined ? [] : [name]),
+ );
+ const acceptsInput = approved && isInAppAgentToolWithInputs(toolName);
+
+ if (providedToolNames.some((name) => !acceptsInput || name !== toolName)) {
+ return {
+ success: false,
+ error: "Tool inputs are only accepted for the approved tool",
+ };
+ }
+ if (!acceptsInput) {
+ return { success: true };
+ }
+
+ const input = toolInputs?.[toolName];
+ if (input === undefined) {
+ return { success: false, error: "This tool requires input to approve" };
+ }
+ return toolInputValidators[toolName]({ args, input });
+}
diff --git a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
index 901decc26f..125e29289c 100644
--- a/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-background-run.servertest.ts
@@ -17,8 +17,11 @@ import { LANGFUSE_AI_MODEL_UNCONFIGURED_MESSAGE } from "@langfuse/shared/in-app-
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
import {
IN_APP_AGENT_APPROVAL_DECISION_EVENT_NAME,
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
InAppAgentRunErrorCode,
InAppAgentRunStatus,
+ type InAppAgentQuestionnaireAnswers,
+ type InAppAgentToolInputs,
} from "@langfuse/shared/in-app-agent";
import {
createInAppAgentConversationId,
@@ -343,6 +346,8 @@ describe("in-app agent background runs", () => {
toolCallId: string;
context?: Array<{ description: string; value: string }>;
parkedAt?: Date;
+ toolName?: string;
+ args?: unknown;
}) => {
const runId = createInAppAgentRunId();
@@ -374,8 +379,8 @@ describe("in-app agent background runs", () => {
value: {
type: "mastra_suspend",
toolCallId: params.toolCallId,
- toolName: "langfuse_createTextPrompt",
- args: { name: "from-persisted-event" },
+ toolName: params.toolName ?? "langfuse_createTextPrompt",
+ args: params.args ?? { name: "from-persisted-event" },
runId,
},
},
@@ -851,6 +856,98 @@ describe("in-app agent background runs", () => {
).toBe(1);
});
+ it("validates questionnaire answers against the persisted questions", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-1",
+ toolName: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ args: {
+ questions: [
+ {
+ question: "Which evaluator type?",
+ options: [
+ {
+ label: "LLM-as-a-judge",
+ description: "Model-graded",
+ recommended: true,
+ },
+ {
+ label: "Code",
+ description: "Deterministic",
+ recommended: false,
+ },
+ ],
+ allowMultiple: false,
+ },
+ ],
+ },
+ });
+ const decide = (toolInputs?: InAppAgentToolInputs) =>
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ toolInputs,
+ });
+ const withAnswers = (answers: InAppAgentQuestionnaireAnswers) => ({
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: { answers },
+ });
+
+ await expect(decide()).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ await expect(
+ decide(withAnswers([{ selectedOptionIndexes: [2], otherText: null }])),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ expect(
+ (
+ await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: parkedRunId, projectId },
+ })
+ ).status,
+ ).toBe(InAppAgentRunStatus.AWAITING_APPROVAL);
+
+ const toolInputs = withAnswers([
+ { selectedOptionIndexes: [1], otherText: null },
+ ]);
+ const { runId: continuationRunId } = await decide(toolInputs);
+
+ const continuation = await prisma.inAppAgentRun.findFirstOrThrow({
+ where: { id: continuationRunId, projectId },
+ });
+ expect(continuation.request).toMatchObject({
+ kind: "approvalDecision",
+ approved: true,
+ toolInputs,
+ });
+ });
+
+ it("rejects tool inputs for a tool that does not take input", async () => {
+ const { caller, projectId, userId } = await createCaller();
+ const conversation = await createConversation({ projectId, userId });
+ const parkedRunId = await parkRunForApproval({
+ projectId,
+ conversationId: conversation.id,
+ userId,
+ toolCallId: "tool-call-1",
+ });
+
+ await expect(
+ caller.decideToolApproval({
+ projectId,
+ conversationId: conversation.id,
+ runId: parkedRunId,
+ toolCallId: "tool-call-1",
+ approved: true,
+ toolInputs: { [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: { answers: [] } },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
it("preserves context through an approved then rejected chained continuation", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-08-14T10:01:00.000Z"));
diff --git a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index 4a3939a9dc..2ea391b96f 100644
--- a/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -69,6 +69,7 @@ export function ControlledInAppAgentWindow(
pendingToolApprovals,
approveToolCall,
alwaysAllowToolCall,
+ answerQuestionnaire,
rejectToolCall,
selectConversation,
selectedConversationId,
@@ -222,6 +223,7 @@ export function ControlledInAppAgentWindow(
executionUi={windowExecutionUi}
onApproveToolCall={approveToolCall}
onAlwaysAllowToolCall={alwaysAllowToolCall}
+ onAnswerQuestionnaire={answerQuestionnaire}
onRejectToolCall={rejectToolCall}
onSubmitFeedback={submitFeedback}
{...closeButtonProps}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.stories.tsx
new file mode 100644
index 0000000000..944d14cf19
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.stories.tsx
@@ -0,0 +1,95 @@
+import preview from "../../../../../.storybook/preview";
+import { fn } from "storybook/test";
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+import { InAppAgentQuestionnaireCard } from "./InAppAgentQuestionnaireCard";
+
+const environmentQuestion: InAppAgentQuestionnaireQuestion = {
+ question: "Which environment should the evaluator run on?",
+ options: [
+ {
+ label: "Production",
+ description: "Score live traffic as it arrives.",
+ recommended: true,
+ },
+ {
+ label: "Staging",
+ description: "Try it on pre-release traces first.",
+ recommended: false,
+ },
+ ],
+ allowMultiple: false,
+};
+
+const failureSignalsQuestion: InAppAgentQuestionnaireQuestion = {
+ question: "Which signals should count as a failure?",
+ options: [
+ {
+ label: "Tool errors",
+ description: "Any tool call that returned an error.",
+ recommended: true,
+ },
+ {
+ label: "Empty output",
+ description: "The model returned no text.",
+ recommended: false,
+ },
+ {
+ label: "High latency",
+ description: "The trace took longer than 30 seconds.",
+ recommended: false,
+ },
+ ],
+ allowMultiple: true,
+};
+
+const scheduleQuestion: InAppAgentQuestionnaireQuestion = {
+ question: "How often should it run?",
+ options: [
+ {
+ label: "Every hour",
+ description: "Catches regressions fastest.",
+ recommended: false,
+ },
+ {
+ label: "Every 6 hours",
+ description: "A few runs per working day.",
+ recommended: false,
+ },
+ {
+ label: "Once a day",
+ description: "Enough for slow-moving traffic.",
+ recommended: false,
+ },
+ {
+ label: "Once a week",
+ description: "Lowest cost, slowest signal.",
+ recommended: false,
+ },
+ ],
+ allowMultiple: false,
+};
+
+const multiStepQuestions = [
+ environmentQuestion,
+ failureSignalsQuestion,
+ scheduleQuestion,
+];
+
+const meta = preview.meta({
+ component: InAppAgentQuestionnaireCard,
+ args: {
+ questions: [environmentQuestion],
+ isSubmitting: false,
+ onSubmit: fn().mockResolvedValue(undefined),
+ },
+});
+
+export const SingleChoice = meta.story({});
+
+export const MultipleChoice = meta.story({
+ args: { questions: [failureSignalsQuestion] },
+});
+
+export const MultiStep = meta.story({
+ args: { questions: multiStepQuestions },
+});
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.tsx
new file mode 100644
index 0000000000..e4c98f97ef
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import {
+ useId,
+ useState,
+ type KeyboardEvent,
+ type SyntheticEvent,
+} from "react";
+import { useForm } from "react-hook-form";
+import { ChevronLeft, ChevronRight, X } from "lucide-react";
+import type {
+ InAppAgentQuestionnaireAnswers,
+ InAppAgentQuestionnaireQuestion,
+} from "@langfuse/shared/in-app-agent";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { QuestionnaireStep } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/QuestionnaireStep";
+import { createQuestionnaireFormValues } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues";
+import { toQuestionnaireAnswers } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/toQuestionnaireAnswers";
+
+export type InAppAgentQuestionnaireCardProps = {
+ questions: readonly InAppAgentQuestionnaireQuestion[];
+ isSubmitting: boolean;
+ isDisabled?: boolean;
+ onSubmit: (answers: InAppAgentQuestionnaireAnswers) => Promise<void>;
+};
+
+/**
+ * Answers stay local until the final step, so the model receives every
+ * answer in one approval decision. Dismissing submits every question as
+ * skipped, so the model reads it as "no answer" rather than a declined call.
+ */
+export function InAppAgentQuestionnaireCard({
+ questions,
+ isSubmitting,
+ isDisabled = false,
+ onSubmit,
+}: InAppAgentQuestionnaireCardProps) {
+ const titleId = useId();
+ const [stepIndex, setStepIndex] = useState(0);
+ const [isDismissing, setIsDismissing] = useState(false);
+ const form = useForm({
+ defaultValues: createQuestionnaireFormValues(questions),
+ });
+
+ const question = questions[stepIndex];
+ const stepCount = questions.length;
+ const isLastStep = stepIndex === stepCount - 1;
+ const isBusy =
+ isSubmitting || isDismissing || form.formState.isSubmitting || isDisabled;
+
+ const currentAnswer = form.watch(`answers.${stepIndex}`);
+ const hasAnswer =
+ currentAnswer.selectedOptionIndexes.length > 0 ||
+ currentAnswer.otherText.trim().length > 0;
+
+ const submitAnswers = form.handleSubmit(async (values) => {
+ await onSubmit(toQuestionnaireAnswers(values));
+ });
+
+ const goToNextStep = () => {
+ if (isBusy) {
+ return;
+ }
+ if (isLastStep) {
+ submitAnswers().catch(() => undefined);
+ return;
+ }
+ setStepIndex(stepIndex + 1);
+ };
+
+ // Next and Submit confirm a choice; Skip advances without one.
+ const confirmStep = () => {
+ if (hasAnswer) {
+ goToNextStep();
+ }
+ };
+
+ const handleFormSubmit = (event: SyntheticEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ confirmStep();
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLFormElement>) => {
+ if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) {
+ return;
+ }
+ event.preventDefault();
+ confirmStep();
+ };
+
+ const handlePreviousStep = () => {
+ setStepIndex(Math.max(stepIndex - 1, 0));
+ };
+
+ const handleNextStep = () => {
+ setStepIndex(Math.min(stepIndex + 1, stepCount - 1));
+ };
+
+ const handleSkip = () => {
+ form.resetField(`answers.${stepIndex}`);
+ goToNextStep();
+ };
+
+ const handleDismiss = () => {
+ setIsDismissing(true);
+ // The provider surfaces decision errors; the card only resets its state.
+ onSubmit(toQuestionnaireAnswers(createQuestionnaireFormValues(questions)))
+ .catch(() => undefined)
+ .finally(() => {
+ setIsDismissing(false);
+ });
+ };
+
+ const nextLabel = isLastStep ? "Submit" : "Next";
+ return (
+ <form
+ aria-labelledby={titleId}
+ className="bg-card text-foreground border-border overflow-hidden rounded-md border shadow-xs"
+ onSubmit={handleFormSubmit}
+ onKeyDown={handleKeyDown}
+ >
+ <div className="bg-muted flex items-start gap-2 py-2 pr-2 pl-4">
+ <h3
+ id={titleId}
+ className="min-w-0 flex-1 py-0.5 text-xs leading-5 font-bold"
+ >
+ {question.question}
+ </h3>
+ {stepCount > 1 ? (
+ <div className="flex shrink-0 items-center">
+ <IconButton
+ icon={ChevronLeft}
+ label="Previous question"
+ size="sm"
+ disabled={isBusy || stepIndex === 0}
+ onClick={handlePreviousStep}
+ />
+ <span className="text-muted-foreground px-0.5 text-xs whitespace-nowrap tabular-nums">
+ {stepIndex + 1} of {stepCount}
+ </span>
+ <IconButton
+ icon={ChevronRight}
+ label="Next question"
+ size="sm"
+ disabled={isBusy || isLastStep}
+ onClick={handleNextStep}
+ />
+ </div>
+ ) : null}
+ <IconButton
+ icon={X}
+ label="Dismiss questions"
+ size="sm"
+ disabled={isBusy}
+ onClick={handleDismiss}
+ />
+ </div>
+ <QuestionnaireStep
+ key={stepIndex}
+ control={form.control}
+ question={question}
+ questionIndex={stepIndex}
+ submitLabel={nextLabel}
+ isDisabled={isBusy}
+ onAdvance={goToNextStep}
+ onSkip={handleSkip}
+ />
+ </form>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/QuestionnaireStep.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/QuestionnaireStep.tsx
new file mode 100644
index 0000000000..b2c15376d8
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/QuestionnaireStep.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import { useRef, useState, type KeyboardEvent } from "react";
+import { flushSync } from "react-dom";
+import { useController, type Control } from "react-hook-form";
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+import type { QuestionnaireFormValues } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues";
+import { updateQuestionnaireAnswer } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/updateQuestionnaireAnswer";
+import { SingleChoiceOptions } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/SingleChoiceOptions/SingleChoiceOptions";
+import { MultipleChoiceOptions } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/MultipleChoiceOptions/MultipleChoiceOptions";
+import { QuestionnaireStepFooter } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/QuestionnaireStepFooter/QuestionnaireStepFooter";
+
+type QuestionnaireAnswerAction = Parameters<
+ typeof updateQuestionnaireAnswer
+>[2];
+
+export type QuestionnaireStepProps = {
+ control: Control<QuestionnaireFormValues>;
+ question: InAppAgentQuestionnaireQuestion;
+ questionIndex: number;
+ submitLabel: string;
+ isDisabled: boolean;
+ /** Moves to the next step, or submits on the last one. */
+ onAdvance: () => void;
+ onSkip: () => void;
+};
+
+/**
+ * Options and the custom answer form one divided list, picked with a radio or
+ * a checkbox. Pressing an option's number picks it, and on a single-choice
+ * question moves on. A typed answer turns Skip into Submit; multiple choice
+ * confirms from the footer.
+ */
+export function QuestionnaireStep({
+ control,
+ question,
+ questionIndex,
+ submitLabel,
+ isDisabled,
+ onAdvance,
+ onSkip,
+}: QuestionnaireStepProps) {
+ const otherInputRef = useRef<HTMLInputElement>(null);
+ const { field } = useController({
+ control,
+ name: `answers.${questionIndex}`,
+ });
+ const answer = field.value;
+ const hasOtherText = answer.otherText.trim().length > 0;
+ const [isOtherOpen, setIsOtherOpen] = useState(hasOtherText);
+ const selectedCount =
+ answer.selectedOptionIndexes.length + (hasOtherText ? 1 : 0);
+
+ const updateAnswer = (action: QuestionnaireAnswerAction) => {
+ field.onChange(updateQuestionnaireAnswer(answer, question, action));
+ };
+
+ const openOther = () => {
+ flushSync(() => {
+ setIsOtherOpen(true);
+ });
+ otherInputRef.current?.focus();
+ };
+
+ const handleSelectOption = (optionIndex: number) => {
+ updateAnswer({ type: "selectOption", optionIndex });
+ setIsOtherOpen(false);
+ };
+
+ const handleToggleOption = (optionIndex: number) => {
+ updateAnswer({ type: "toggleOption", optionIndex });
+ };
+
+ const handleSelectOther = () => {
+ updateAnswer({ type: "selectOther" });
+ openOther();
+ };
+
+ const handleToggleOther = () => {
+ if (!isOtherOpen) {
+ openOther();
+ return;
+ }
+ updateAnswer({ type: "setOtherText", otherText: "" });
+ setIsOtherOpen(false);
+ };
+
+ const handleOtherTextChange = (otherText: string) => {
+ updateAnswer({ type: "setOtherText", otherText });
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const isTyping = event.target instanceof HTMLInputElement;
+ const hasModifier = event.metaKey || event.ctrlKey || event.altKey;
+ const optionIndex = Number(event.key) - 1;
+ if (
+ isTyping ||
+ hasModifier ||
+ isDisabled ||
+ !Number.isInteger(optionIndex) ||
+ optionIndex < 0 ||
+ optionIndex >= question.options.length
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (question.allowMultiple) {
+ handleToggleOption(optionIndex);
+ return;
+ }
+ handleSelectOption(optionIndex);
+ onAdvance();
+ };
+
+ return (
+ <div onKeyDown={handleKeyDown}>
+ {question.allowMultiple ? (
+ <MultipleChoiceOptions
+ question={question}
+ answer={answer}
+ isOtherOpen={isOtherOpen}
+ isDisabled={isDisabled}
+ otherInputRef={otherInputRef}
+ onToggleOption={handleToggleOption}
+ onToggleOther={handleToggleOther}
+ onOtherTextChange={handleOtherTextChange}
+ />
+ ) : (
+ <SingleChoiceOptions
+ question={question}
+ answer={answer}
+ isOtherOpen={isOtherOpen}
+ isDisabled={isDisabled}
+ otherInputRef={otherInputRef}
+ onSelectOption={handleSelectOption}
+ onSelectOther={handleSelectOther}
+ onOtherTextChange={handleOtherTextChange}
+ onAdvance={onAdvance}
+ />
+ )}
+ <QuestionnaireStepFooter
+ actions={getFooterActions(question.allowMultiple, hasOtherText)}
+ submitLabel={submitLabel}
+ isDisabled={isDisabled}
+ isSubmitDisabled={selectedCount === 0}
+ onSkip={onSkip}
+ />
+ </div>
+ );
+}
+
+// Single choice shows Skip until a custom answer is typed, then Submit.
+function getFooterActions(allowMultiple: boolean, hasOtherText: boolean) {
+ if (allowMultiple) {
+ return "skipAndSubmit";
+ }
+ return hasOtherText ? "submit" : "skip";
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/MultipleChoiceOptions/MultipleChoiceOptions.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/MultipleChoiceOptions/MultipleChoiceOptions.tsx
new file mode 100644
index 0000000000..ba7c982051
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/MultipleChoiceOptions/MultipleChoiceOptions.tsx
@@ -0,0 +1,156 @@
+import { useId, type Ref } from "react";
+import { PencilLine } from "lucide-react";
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+import { Checkbox } from "@/src/components/design-system/Checkbox/Checkbox";
+import type { QuestionnaireFormAnswer } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues";
+import { OtherAnswerInput } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OtherAnswerInput/OtherAnswerInput";
+import { OptionList } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionList/OptionList";
+import { OptionRowFrame } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionRowFrame/OptionRowFrame";
+import {
+ OTHER_ANSWER_LABEL,
+ withRecommended,
+} from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow";
+
+export type MultipleChoiceOptionsProps = {
+ question: InAppAgentQuestionnaireQuestion;
+ answer: QuestionnaireFormAnswer;
+ isOtherOpen: boolean;
+ isDisabled: boolean;
+ otherInputRef: Ref<HTMLInputElement>;
+ onToggleOption: (optionIndex: number) => void;
+ onToggleOther: () => void;
+ onOtherTextChange: (otherText: string) => void;
+};
+
+export function MultipleChoiceOptions({
+ question,
+ answer,
+ isOtherOpen,
+ isDisabled,
+ otherInputRef,
+ onToggleOption,
+ onToggleOther,
+ onOtherTextChange,
+}: MultipleChoiceOptionsProps) {
+ const idPrefix = useId();
+
+ return (
+ <OptionList>
+ <div>
+ {question.options.map((option, optionIndex) => (
+ <CheckboxOptionRow
+ key={optionIndex}
+ id={`${idPrefix}-${optionIndex}`}
+ optionIndex={optionIndex}
+ option={option}
+ isChecked={answer.selectedOptionIndexes.includes(optionIndex)}
+ isDisabled={isDisabled}
+ onToggleOption={onToggleOption}
+ />
+ ))}
+ <CheckboxOtherAnswerRow
+ id={`${idPrefix}-other`}
+ isOtherOpen={isOtherOpen}
+ otherText={answer.otherText}
+ isDisabled={isDisabled}
+ otherInputRef={otherInputRef}
+ onToggleOther={onToggleOther}
+ onOtherTextChange={onOtherTextChange}
+ />
+ </div>
+ </OptionList>
+ );
+}
+
+type CheckboxOptionRowProps = Pick<
+ MultipleChoiceOptionsProps,
+ "isDisabled" | "onToggleOption"
+> & {
+ id: string;
+ optionIndex: number;
+ option: InAppAgentQuestionnaireQuestion["options"][number];
+ isChecked: boolean;
+};
+
+function CheckboxOptionRow({
+ id,
+ optionIndex,
+ option,
+ isChecked,
+ isDisabled,
+ onToggleOption,
+}: CheckboxOptionRowProps) {
+ return (
+ <OptionRowFrame>
+ <label htmlFor={id}>
+ <span className="flex h-5 shrink-0 items-center">
+ <Checkbox
+ id={id}
+ checked={isChecked}
+ disabled={isDisabled}
+ onCheckedChange={() => {
+ onToggleOption(optionIndex);
+ }}
+ />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="leading-5">
+ {withRecommended(option.label, option.recommended)}
+ </span>
+ <span className="text-muted-foreground">{option.description}</span>
+ </span>
+ </label>
+ </OptionRowFrame>
+ );
+}
+
+type CheckboxOtherAnswerRowProps = Pick<
+ MultipleChoiceOptionsProps,
+ | "isOtherOpen"
+ | "isDisabled"
+ | "otherInputRef"
+ | "onToggleOther"
+ | "onOtherTextChange"
+> & {
+ id: string;
+ otherText: string;
+};
+
+function CheckboxOtherAnswerRow({
+ id,
+ isOtherOpen,
+ otherText,
+ isDisabled,
+ otherInputRef,
+ onToggleOther,
+ onOtherTextChange,
+}: CheckboxOtherAnswerRowProps) {
+ return (
+ <OptionRowFrame>
+ <label htmlFor={id}>
+ <span className="flex h-5 shrink-0 items-center">
+ <Checkbox
+ id={id}
+ checked={isOtherOpen || otherText.trim().length > 0}
+ disabled={isDisabled}
+ onCheckedChange={onToggleOther}
+ />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="flex items-center gap-1.5 leading-5">
+ {OTHER_ANSWER_LABEL}
+ <PencilLine aria-hidden className="text-muted-foreground icon-sm" />
+ </span>
+ {isOtherOpen ? (
+ <OtherAnswerInput
+ ref={otherInputRef}
+ value={otherText}
+ isDisabled={isDisabled}
+ onChange={onOtherTextChange}
+ />
+ ) : null}
+ </span>
+ </label>
+ </OptionRowFrame>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionList/OptionList.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionList/OptionList.tsx
new file mode 100644
index 0000000000..81df907e08
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionList/OptionList.tsx
@@ -0,0 +1,17 @@
+import { Slot } from "@radix-ui/react-slot";
+import type { ComponentPropsWithoutRef } from "react";
+
+export type OptionListProps = Omit<
+ ComponentPropsWithoutRef<typeof Slot>,
+ "className"
+>;
+
+/** Applies the divided option-list layout to its single child element. */
+export function OptionList(props: OptionListProps) {
+ return (
+ <Slot
+ className="divide-border border-border divide-y border-b"
+ {...props}
+ />
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionRowFrame/OptionRowFrame.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionRowFrame/OptionRowFrame.tsx
new file mode 100644
index 0000000000..9a483d5403
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionRowFrame/OptionRowFrame.tsx
@@ -0,0 +1,20 @@
+import { Slot } from "@radix-ui/react-slot";
+import type { ComponentPropsWithoutRef } from "react";
+
+export type OptionRowFrameProps = Omit<
+ ComponentPropsWithoutRef<typeof Slot>,
+ "className"
+>;
+
+/**
+ * Applies the clickable option-row layout to its single child, usually the
+ * `<label>` that wraps the row's radio or checkbox.
+ */
+export function OptionRowFrame(props: OptionRowFrameProps) {
+ return (
+ <Slot
+ className="hover:bg-muted/50 has-focus-visible:bg-muted/50 flex cursor-pointer items-start gap-3 px-4 py-2 text-xs has-disabled:cursor-not-allowed"
+ {...props}
+ />
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OtherAnswerInput/OtherAnswerInput.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OtherAnswerInput/OtherAnswerInput.tsx
new file mode 100644
index 0000000000..9b22903f8d
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OtherAnswerInput/OtherAnswerInput.tsx
@@ -0,0 +1,34 @@
+import type { Ref } from "react";
+import { IN_APP_AGENT_QUESTIONNAIRE_MAX_ANSWER_LENGTH } from "@langfuse/shared/in-app-agent";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { OTHER_ANSWER_LABEL } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow";
+
+export type OtherAnswerInputProps = {
+ ref: Ref<HTMLInputElement>;
+ value: string;
+ isDisabled: boolean;
+ onChange: (value: string) => void;
+};
+
+export function OtherAnswerInput({
+ ref,
+ value,
+ isDisabled,
+ onChange,
+}: OtherAnswerInputProps) {
+ return (
+ <div className="pt-1.5">
+ <Input
+ ref={ref}
+ aria-label="Custom answer"
+ placeholder={OTHER_ANSWER_LABEL}
+ maxLength={IN_APP_AGENT_QUESTIONNAIRE_MAX_ANSWER_LENGTH}
+ value={value}
+ disabled={isDisabled}
+ onChange={(event) => {
+ onChange(event.target.value);
+ }}
+ />
+ </div>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/QuestionnaireStepFooter/QuestionnaireStepFooter.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/QuestionnaireStepFooter/QuestionnaireStepFooter.tsx
new file mode 100644
index 0000000000..9f4a3d3e9b
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/QuestionnaireStepFooter/QuestionnaireStepFooter.tsx
@@ -0,0 +1,39 @@
+import { Button } from "@/src/components/design-system/Button/Button";
+
+export type QuestionnaireStepFooterProps = {
+ actions: "skip" | "submit" | "skipAndSubmit";
+ submitLabel: string;
+ isDisabled: boolean;
+ isSubmitDisabled: boolean;
+ onSkip: () => void;
+};
+
+export function QuestionnaireStepFooter({
+ actions,
+ submitLabel,
+ isDisabled,
+ isSubmitDisabled,
+ onSkip,
+}: QuestionnaireStepFooterProps) {
+ return (
+ <div className="flex items-center justify-end gap-2 px-4 py-2">
+ {actions === "submit" ? null : (
+ <Button
+ text="Skip"
+ variant="secondary"
+ size="sm"
+ disabled={isDisabled}
+ onClick={onSkip}
+ />
+ )}
+ {actions === "skip" ? null : (
+ <Button
+ text={submitLabel}
+ size="sm"
+ type="submit"
+ disabled={isDisabled || isSubmitDisabled}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/SingleChoiceOptions/SingleChoiceOptions.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/SingleChoiceOptions/SingleChoiceOptions.tsx
new file mode 100644
index 0000000000..f4ca88c715
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/SingleChoiceOptions/SingleChoiceOptions.tsx
@@ -0,0 +1,171 @@
+import { useId, useRef, type Ref } from "react";
+import { PencilLine } from "lucide-react";
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+import { RadioGroup } from "@/src/components/design-system/RadioGroup/RadioGroup";
+import type { QuestionnaireFormAnswer } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues";
+import { OtherAnswerInput } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OtherAnswerInput/OtherAnswerInput";
+import { OptionList } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionList/OptionList";
+import { OptionRowFrame } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/components/OptionRowFrame/OptionRowFrame";
+import {
+ OTHER_ANSWER_LABEL,
+ withRecommended,
+} from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow";
+
+const OTHER_VALUE = "other";
+
+export type SingleChoiceOptionsProps = {
+ question: InAppAgentQuestionnaireQuestion;
+ answer: QuestionnaireFormAnswer;
+ isOtherOpen: boolean;
+ isDisabled: boolean;
+ otherInputRef: Ref<HTMLInputElement>;
+ onSelectOption: (optionIndex: number) => void;
+ onSelectOther: () => void;
+ onOtherTextChange: (otherText: string) => void;
+ onAdvance: () => void;
+};
+
+/**
+ * Clicking an option moves on right away; arrow keys only move the
+ * selection, so keyboard users confirm from the footer.
+ */
+export function SingleChoiceOptions({
+ question,
+ answer,
+ isOtherOpen,
+ isDisabled,
+ otherInputRef,
+ onSelectOption,
+ onSelectOther,
+ onOtherTextChange,
+ onAdvance,
+}: SingleChoiceOptionsProps) {
+ const idPrefix = useId();
+ const isPointerPickRef = useRef(false);
+
+ const handleValueChange = (value: string) => {
+ if (value === OTHER_VALUE) {
+ onSelectOther();
+ return;
+ }
+ onSelectOption(Number(value));
+ if (isPointerPickRef.current) {
+ onAdvance();
+ }
+ };
+
+ const handlePointerDown = () => {
+ isPointerPickRef.current = true;
+ };
+
+ const handleKeyDown = () => {
+ isPointerPickRef.current = false;
+ };
+
+ return (
+ <RadioGroup
+ value={radioValue(answer.selectedOptionIndexes, isOtherOpen)}
+ onValueChange={handleValueChange}
+ >
+ <OptionList>
+ <div onPointerDown={handlePointerDown} onKeyDown={handleKeyDown}>
+ {question.options.map((option, optionIndex) => (
+ <RadioOptionRow
+ key={optionIndex}
+ id={`${idPrefix}-${optionIndex}`}
+ value={String(optionIndex)}
+ option={option}
+ isDisabled={isDisabled}
+ />
+ ))}
+ <RadioOtherAnswerRow
+ id={`${idPrefix}-${OTHER_VALUE}`}
+ isOtherOpen={isOtherOpen}
+ otherText={answer.otherText}
+ isDisabled={isDisabled}
+ otherInputRef={otherInputRef}
+ onOtherTextChange={onOtherTextChange}
+ />
+ </div>
+ </OptionList>
+ </RadioGroup>
+ );
+}
+
+function radioValue(selectedOptionIndexes: number[], isOtherOpen: boolean) {
+ if (isOtherOpen) {
+ return OTHER_VALUE;
+ }
+ const [selected] = selectedOptionIndexes;
+ return selected === undefined ? "" : String(selected);
+}
+
+type RadioOptionRowProps = Pick<SingleChoiceOptionsProps, "isDisabled"> & {
+ id: string;
+ value: string;
+ option: InAppAgentQuestionnaireQuestion["options"][number];
+};
+
+function RadioOptionRow({
+ id,
+ value,
+ option,
+ isDisabled,
+}: RadioOptionRowProps) {
+ return (
+ <OptionRowFrame>
+ <label htmlFor={id}>
+ <span className="flex h-5 shrink-0 items-center">
+ <RadioGroup.Item id={id} value={value} disabled={isDisabled} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="leading-5">
+ {withRecommended(option.label, option.recommended)}
+ </span>
+ <span className="text-muted-foreground">{option.description}</span>
+ </span>
+ </label>
+ </OptionRowFrame>
+ );
+}
+
+type RadioOtherAnswerRowProps = Pick<
+ SingleChoiceOptionsProps,
+ "isOtherOpen" | "isDisabled" | "otherInputRef" | "onOtherTextChange"
+> & {
+ id: string;
+ otherText: string;
+};
+
+function RadioOtherAnswerRow({
+ id,
+ isOtherOpen,
+ otherText,
+ isDisabled,
+ otherInputRef,
+ onOtherTextChange,
+}: RadioOtherAnswerRowProps) {
+ return (
+ <OptionRowFrame>
+ <label htmlFor={id}>
+ <span className="flex h-5 shrink-0 items-center">
+ <RadioGroup.Item id={id} value={OTHER_VALUE} disabled={isDisabled} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="flex items-center gap-1.5 leading-5">
+ {OTHER_ANSWER_LABEL}
+ <PencilLine aria-hidden className="text-muted-foreground icon-sm" />
+ </span>
+ {isOtherOpen ? (
+ <OtherAnswerInput
+ ref={otherInputRef}
+ value={otherText}
+ isDisabled={isDisabled}
+ onChange={onOtherTextChange}
+ />
+ ) : null}
+ </span>
+ </label>
+ </OptionRowFrame>
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow.ts b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow.ts
new file mode 100644
index 0000000000..5b705c43e2
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/components/QuestionnaireStep/optionRow.ts
@@ -0,0 +1,5 @@
+export const OTHER_ANSWER_LABEL = "Type your answer";
+
+export function withRecommended(label: string, isRecommended: boolean) {
+ return isRecommended ? `${label} (Recommended)` : label;
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues.ts b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues.ts
new file mode 100644
index 0000000000..e9340bcf35
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/createQuestionnaireFormValues.ts
@@ -0,0 +1,19 @@
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+
+export function createQuestionnaireFormValues(
+ questions: readonly InAppAgentQuestionnaireQuestion[],
+) {
+ return {
+ answers: questions.map(() => ({
+ selectedOptionIndexes: [] as number[],
+ otherText: "",
+ })),
+ };
+}
+
+export type QuestionnaireFormValues = ReturnType<
+ typeof createQuestionnaireFormValues
+>;
+
+export type QuestionnaireFormAnswer =
+ QuestionnaireFormValues["answers"][number];
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/parseQuestionnaireQuestions.ts b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/parseQuestionnaireQuestions.ts
new file mode 100644
index 0000000000..5943c08e0b
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/parseQuestionnaireQuestions.ts
@@ -0,0 +1,10 @@
+import { safeJsonParse } from "@langfuse/shared";
+import { InAppAgentQuestionnaireArgsSchema } from "@langfuse/shared/in-app-agent";
+
+export function parseQuestionnaireQuestions(args: string) {
+ const parsed = InAppAgentQuestionnaireArgsSchema.safeParse(
+ safeJsonParse(args),
+ );
+
+ return parsed.success ? parsed.data.questions : null;
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/toQuestionnaireAnswers.ts b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/toQuestionnaireAnswers.ts
new file mode 100644
index 0000000000..28016047b6
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/toQuestionnaireAnswers.ts
@@ -0,0 +1,17 @@
+import type { InAppAgentQuestionnaireAnswers } from "@langfuse/shared/in-app-agent";
+import type { QuestionnaireFormValues } from "./createQuestionnaireFormValues";
+
+export function toQuestionnaireAnswers(
+ values: QuestionnaireFormValues,
+): InAppAgentQuestionnaireAnswers {
+ return values.answers.map((answer) => {
+ const otherText = answer.otherText.trim();
+
+ return {
+ selectedOptionIndexes: [...answer.selectedOptionIndexes].sort(
+ (a, b) => a - b,
+ ),
+ otherText: otherText.length > 0 ? otherText : null,
+ };
+ });
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/updateQuestionnaireAnswer.ts b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/updateQuestionnaireAnswer.ts
new file mode 100644
index 0000000000..b39b080d34
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/updateQuestionnaireAnswer.ts
@@ -0,0 +1,66 @@
+import type { InAppAgentQuestionnaireQuestion } from "@langfuse/shared/in-app-agent";
+import { assertUnreachable } from "@/src/utils/types";
+import type { QuestionnaireFormAnswer } from "./createQuestionnaireFormValues";
+
+type QuestionnaireAnswerAction =
+ | { type: "selectOption"; optionIndex: number }
+ | { type: "toggleOption"; optionIndex: number }
+ | { type: "selectOther" }
+ | { type: "setOtherText"; otherText: string };
+
+/**
+ * Single-choice questions hold one answer at a time, so choosing an option
+ * clears the custom answer, and choosing or typing a custom answer clears the
+ * chosen option.
+ * Multi-choice questions keep every toggled option next to the custom answer.
+ */
+export function updateQuestionnaireAnswer(
+ answer: QuestionnaireFormAnswer,
+ question: InAppAgentQuestionnaireQuestion,
+ action: QuestionnaireAnswerAction,
+): QuestionnaireFormAnswer {
+ if (action.type === "selectOption") {
+ return { selectedOptionIndexes: [action.optionIndex], otherText: "" };
+ }
+ if (action.type === "toggleOption") {
+ return toggleOption(answer, action.optionIndex);
+ }
+ if (action.type === "selectOther") {
+ return question.allowMultiple
+ ? answer
+ : { selectedOptionIndexes: [], otherText: answer.otherText };
+ }
+ if (action.type === "setOtherText") {
+ return setOtherText(answer, question, action.otherText);
+ }
+
+ return assertUnreachable(action);
+}
+
+function toggleOption(
+ answer: QuestionnaireFormAnswer,
+ optionIndex: number,
+): QuestionnaireFormAnswer {
+ const isSelected = answer.selectedOptionIndexes.includes(optionIndex);
+
+ return {
+ ...answer,
+ selectedOptionIndexes: isSelected
+ ? answer.selectedOptionIndexes.filter((index) => index !== optionIndex)
+ : [...answer.selectedOptionIndexes, optionIndex],
+ };
+}
+
+function setOtherText(
+ answer: QuestionnaireFormAnswer,
+ question: InAppAgentQuestionnaireQuestion,
+ otherText: string,
+): QuestionnaireFormAnswer {
+ const clearsSelection =
+ !question.allowMultiple && otherText.trim().length > 0;
+
+ return {
+ selectedOptionIndexes: clearsSelection ? [] : answer.selectedOptionIndexes,
+ otherText,
+ };
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.stories.tsx
new file mode 100644
index 0000000000..4943003c92
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.stories.tsx
@@ -0,0 +1,35 @@
+import preview from "../../../../../.storybook/preview";
+import { InAppAgentQuestionnaireSummary } from "./InAppAgentQuestionnaireSummary";
+
+const meta = preview.meta({
+ component: InAppAgentQuestionnaireSummary,
+ decorators: [
+ (Story) => (
+ <div className="max-w-md">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Answered = meta.story({
+ args: {
+ answers: [
+ {
+ question: "Which environment should the evaluator run on?",
+ answer: ["Preview environment"],
+ skipped: false,
+ },
+ {
+ question: "Which signals should count as a failure?",
+ answer: ["Tool errors", "High latency"],
+ skipped: false,
+ },
+ {
+ question: "Anything else the evaluator should know?",
+ answer: [],
+ skipped: true,
+ },
+ ],
+ },
+});
diff --git a/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.tsx b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.tsx
new file mode 100644
index 0000000000..ac0eba0baa
--- /dev/null
+++ b/web/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary.tsx
@@ -0,0 +1,32 @@
+import type { InAppAgentQuestionnaireResult } from "@langfuse/shared/in-app-agent";
+
+export type InAppAgentQuestionnaireSummaryProps = {
+ answers: InAppAgentQuestionnaireResult["answers"];
+};
+
+export function InAppAgentQuestionnaireSummary({
+ answers,
+}: InAppAgentQuestionnaireSummaryProps) {
+ return (
+ <dl className="border-border bg-muted flex flex-col gap-2 rounded-md border p-2.5 text-xs">
+ {answers.map((answer, index) => (
+ <div key={index} className="flex flex-col gap-0.5">
+ <dt className="text-foreground font-bold">{answer.question}</dt>
+ <QuestionnaireSummaryAnswer answer={answer} />
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+function QuestionnaireSummaryAnswer({
+ answer,
+}: {
+ answer: InAppAgentQuestionnaireResult["answers"][number];
+}) {
+ if (answer.skipped) {
+ return <dd className="text-muted-foreground italic">Skipped</dd>;
+ }
+
+ return <dd className="text-foreground">{answer.answer.join(", ")}</dd>;
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
index 3d818ab117..c4d37b21dc 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.clienttest.tsx
@@ -135,6 +135,7 @@ function windowElement(
onNewConversation: vi.fn(),
onOpenConversationHistory: vi.fn(),
onRejectToolCall: vi.fn(),
+ onAnswerQuestionnaire: vi.fn(),
onSelectConversation: vi.fn(),
onSubmit: vi.fn().mockResolvedValue(true),
onSubmitFeedback: vi.fn(),
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
index d25b3eb1eb..97e0f53c41 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.stories.tsx
@@ -3,6 +3,7 @@ import { type ReactNode, useEffect, useRef, useState } from "react";
import { expect, fn, screen, userEvent, waitFor, within } from "storybook/test";
import {
IN_APP_AGENT_GENERIC_ERROR_MESSAGE,
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
InAppAgentRunErrorCode,
InAppAgentRunStatus,
type AgUiMessage,
@@ -713,6 +714,7 @@ const meta = preview.meta({
onApproveToolCall: fn(),
onAlwaysAllowToolCall: fn(),
onRejectToolCall: fn(),
+ onAnswerQuestionnaire: fn(),
onSelectConversation: fn(),
onClose: fn(),
onExpandedChange: fn(),
@@ -776,6 +778,155 @@ export const ToolApprovalRequired = meta.story({
},
});
+export const PendingQuestionnaire = meta.story({
+ args: {
+ isAssistantTurnInProgress: true,
+ isAwaitingApproval: true,
+ selectedConversationId: "conversation-1",
+ messages: [
+ {
+ id: "user-1",
+ role: "user",
+ content: { type: "text", text: "Set up a hallucination evaluator." },
+ },
+ {
+ id: "assistant-intro",
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "A few quick questions before I set it up.",
+ },
+ },
+ {
+ id: "assistant-questionnaire",
+ role: "assistant",
+ content: {
+ type: "toolGroup",
+ tools: [
+ {
+ type: "tool",
+ name: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ status: "running",
+ args: JSON.stringify({
+ questions: [
+ {
+ question: "Which environment should it run on?",
+ options: [
+ {
+ label: "Production",
+ description: "Score live traffic as it arrives.",
+ recommended: true,
+ },
+ {
+ label: "Staging",
+ description: "Try it on pre-release traces first.",
+ recommended: false,
+ },
+ ],
+ allowMultiple: false,
+ },
+ {
+ question: "Which signals count as a failure?",
+ options: [
+ {
+ label: "Unsupported claims",
+ description: "Statements the context does not back.",
+ recommended: true,
+ },
+ {
+ label: "Made-up citations",
+ description: "Sources that do not exist.",
+ recommended: false,
+ },
+ ],
+ allowMultiple: true,
+ },
+ ],
+ }),
+ approval: { id: "approval-questionnaire-1", status: "pending" },
+ },
+ ],
+ },
+ },
+ ],
+ },
+});
+
+export const AnsweredQuestionnaire = meta.story({
+ name: "(Test) Answered questionnaire",
+ args: {
+ selectedConversationId: "conversation-1",
+ messages: [
+ {
+ id: "user-1",
+ role: "user",
+ content: { type: "text", text: "Set up a hallucination evaluator." },
+ },
+ {
+ id: "assistant-intro",
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "A few quick questions before I set it up.",
+ },
+ },
+ {
+ id: "assistant-questionnaire",
+ role: "assistant",
+ content: {
+ type: "toolGroup",
+ tools: [
+ {
+ type: "tool",
+ name: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ status: "succeeded",
+ args: "{}",
+ result: JSON.stringify({
+ type: "questionnaireAnswers",
+ answers: [
+ {
+ question: "Which environment should it run on?",
+ answer: ["Staging"],
+ skipped: false,
+ },
+ {
+ question: "Which signals count as a failure?",
+ answer: ["Unsupported claims", "Made-up citations"],
+ skipped: false,
+ },
+ ],
+ }),
+ },
+ ],
+ },
+ },
+ {
+ id: "assistant-answer",
+ role: "assistant",
+ content: {
+ type: "text",
+ text: "The evaluator now runs on staging and flags unsupported claims and made-up citations.",
+ },
+ },
+ ],
+ },
+ play: async ({ canvasElement }: { canvasElement: HTMLElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByText("A few quick questions before I set it up."),
+ ).toBeVisible();
+ await expect(
+ canvas.getByText("Which environment should it run on?"),
+ ).toBeVisible();
+ await expect(canvas.getByText("Staging")).toBeVisible();
+ // Only the reply after the questionnaire is the turn's answer.
+ await expect(
+ canvas.getAllByRole("button", { name: "Copy message" }),
+ ).toHaveLength(1);
+ },
+});
+
export const Empty = meta.story({
args: {
messages: [],
diff --git a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
index 54a555ff62..6b947ea101 100644
--- a/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -50,11 +50,13 @@ import {
type InAppAgentMessageContent,
type InAppAgentMessageRole,
} from "./InAppAgentMessage";
-import type {
- InAppAgentMessageFeedbackValue,
- InAppAgentMessageSource,
-} from "../schema";
-import { IN_APP_AGENT_GENERIC_ERROR_MESSAGE } from "@langfuse/shared/in-app-agent";
+import type { InAppAgentMessageFeedbackValue } from "../schema";
+import {
+ IN_APP_AGENT_GENERIC_ERROR_MESSAGE,
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ type InAppAgentQuestionnaireAnswers,
+ type InAppAgentQuestionnaireQuestion,
+} from "@langfuse/shared/in-app-agent";
import type { InAppAgentScreenContextDescription } from "@/src/features/in-app-agent/context";
import type { InAppAgentActivityByConversationId } from "@/src/features/in-app-agent/lib/inAppAgentActivity";
import type { SettledActivityOutcome } from "@/src/features/in-app-agent/lib/backgroundExecutionSession";
@@ -63,12 +65,19 @@ import { InAppAgentBackgroundHint } from "@/src/features/in-app-agent/components
import { InAppAgentNotice } from "@/src/features/in-app-agent/components/InAppAgentNotice";
import { useInAppAgentBackgroundHint } from "@/src/features/in-app-agent/lib/useInAppAgentBackgroundHint";
import { InAppAgentToolCallCard } from "@/src/features/in-app-agent/components/InAppAgentToolCallCard";
+import { InAppAgentQuestionnaireCard } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/InAppAgentQuestionnaireCard";
+import { parseQuestionnaireQuestions } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireCard/fns/parseQuestionnaireQuestions";
+import { InAppAgentQuestionnaireSummary } from "@/src/features/in-app-agent/components/InAppAgentQuestionnaireSummary/InAppAgentQuestionnaireSummary";
+import {
+ buildConversationDisplayItems,
+ type ConversationDisplayItem,
+} from "@/src/features/in-app-agent/fns/buildConversationDisplayItems";
import {
getInAppAgentActivityProgressLabel,
type InAppAgentError,
+ type InAppAgentToolCallContent,
isInAppAgentRateLimited,
} from "@/src/features/in-app-agent/components/utils/utils";
-import { deduplicateBy } from "@/src/utils/arrays";
import styles from "./InAppAgentWindow.module.css";
import { assertUnreachable } from "@/src/utils/types";
import {
@@ -270,242 +279,6 @@ export type InAppAgentWindowMessage = {
content: InAppAgentMessageContent;
};
-type ConversationDisplayItem =
- | {
- type: "user";
- message: InAppAgentWindowMessage;
- hasPreviousMessage: boolean;
- }
- | {
- type: "activity";
- /** Identifies the turn, not its contents: the drawer must survive both
- * the first activity arriving and the run settling without remounting,
- * or an expanded drawer collapses under the user. */
- key: string;
- messages: InAppAgentWindowMessage[];
- startTimestamp?: number;
- endTimestamp?: number;
- followsUser: boolean;
- isInProgress: boolean;
- }
- | {
- type: "assistant";
- message: InAppAgentWindowMessage;
- followsUser: boolean;
- isFinalAnswer: boolean;
- };
-
-type InAppAgentTextMessage = InAppAgentWindowMessage & {
- content: Extract<InAppAgentMessageContent, { type: "text" }>;
-};
-
-type InAppAgentRedirectActionContent = Extract<
- InAppAgentMessageContent,
- { type: "redirectAction" }
->;
-
-/**
- * Fold a turn's answer blocks into the single bubble the user reads. Each field
- * takes the last block that defined it, except `sources`, which arrive already
- * unioned across the whole turn so a citation earned mid-turn is not lost.
- */
-function joinAnswerMessages(
- messages: InAppAgentWindowMessage[],
- turnSources: InAppAgentMessageSource[],
- turnRedirectAction: InAppAgentRedirectActionContent | undefined,
-): InAppAgentWindowMessage | null {
- const textMessages = messages.filter(
- (message): message is InAppAgentTextMessage =>
- message.content.type === "text",
- );
- const lastText = textMessages.at(-1);
-
- // A turn can end on a bare redirect with no text to attach it to.
- if (!lastText) {
- return messages.at(-1) ?? null;
- }
-
- const lastDefined = <T,>(
- pick: (message: InAppAgentTextMessage) => T | undefined,
- ): T | undefined =>
- textMessages.reduce<T | undefined>(
- (found, message) => pick(message) ?? found,
- undefined,
- );
- const runId = lastDefined((message) => message.runId);
- const feedbackMessageId = lastDefined((message) => message.feedbackMessageId);
- const feedback = lastDefined((message) => message.content.feedback);
-
- return {
- ...lastText,
- ...(runId ? { runId } : {}),
- ...(feedbackMessageId ? { feedbackMessageId } : {}),
- content: {
- type: "text",
- text: textMessages.map((message) => message.content.text).join("\n\n"),
- ...(textMessages.some((message) => message.content.isStreaming)
- ? { isStreaming: true }
- : {}),
- ...(turnSources.length > 0 ? { sources: turnSources } : {}),
- ...(feedback ? { feedback } : {}),
- ...(turnRedirectAction ? { redirectAction: turnRedirectAction } : {}),
- },
- };
-}
-
-function buildConversationDisplayItems(
- messages: InAppAgentWindowMessage[],
- isRunUnsettled: boolean,
-): ConversationDisplayItem[] {
- const items: ConversationDisplayItem[] = [];
- // A tool call awaiting approval is hoisted into its own card above the
- // composer, and the drawer speaks for a turn that has produced nothing yet,
- // so neither belongs in the transcript.
- const visibleMessages = messages.flatMap((message) => {
- if (message.content.type === "loading") {
- return [];
- }
-
- if (message.content.type !== "toolGroup") {
- return [message];
- }
-
- const visibleTools = message.content.tools.filter((tool) => !tool.approval);
- if (visibleTools.length === 0) {
- return [];
- }
-
- return [
- {
- ...message,
- content: { ...message.content, tools: visibleTools },
- } satisfies InAppAgentWindowMessage,
- ];
- });
-
- for (let index = 0; index < visibleMessages.length; ) {
- const message = visibleMessages[index];
- if (!message) {
- break;
- }
-
- if (message.role === "user") {
- items.push({
- type: "user",
- message,
- hasPreviousMessage: index > 0,
- });
- index++;
- continue;
- }
-
- const turnStartIndex = index;
- while (
- index < visibleMessages.length &&
- visibleMessages[index]?.role === "assistant"
- ) {
- index++;
- }
-
- const turnMessages = visibleMessages.slice(turnStartIndex, index);
- const isInProgress = isRunUnsettled && index === visibleMessages.length;
- const lastReasoningIndex = turnMessages.findLastIndex(
- (turnMessage) => turnMessage.content.type === "reasoning",
- );
- // Trailing text is the answer; text before the turn's last thought is still
- // work. A proposed redirect is always actionable, so it never stays behind
- // in the drawer. Declared once, with the activity bucket as its exact
- // complement, so no message can fall out of both.
- const isAnswerPart = (
- turnMessage: InAppAgentWindowMessage,
- turnIndex: number,
- ) =>
- !isInProgress &&
- (turnMessage.content.type === "redirectAction" ||
- (turnMessage.content.type === "text" &&
- turnIndex > lastReasoningIndex));
- const answerMessages = turnMessages.filter(isAnswerPart);
- const activityMessages = turnMessages.filter(
- (turnMessage, turnIndex) => !isAnswerPart(turnMessage, turnIndex),
- );
- const turnSources = deduplicateBy(
- turnMessages.flatMap((turnMessage) =>
- turnMessage.content.type === "text"
- ? (turnMessage.content.sources ?? [])
- : [],
- ),
- (source) => source.url,
- );
- // A proposed redirect belongs to the turn, not to whichever block carried
- // it: the tool result is merged into a preceding text message when there is
- // one and emitted standalone when there is not, and either can land in the
- // drawer.
- const turnRedirectAction = turnMessages.reduce<
- InAppAgentRedirectActionContent | undefined
- >(
- (found, turnMessage) =>
- (turnMessage.content.type === "redirectAction"
- ? turnMessage.content
- : turnMessage.content.type === "text"
- ? turnMessage.content.redirectAction
- : undefined) ?? found,
- undefined,
- );
- const joinedAnswer = joinAnswerMessages(
- answerMessages,
- turnSources,
- turnRedirectAction,
- );
- const precedingMessage = visibleMessages[turnStartIndex - 1];
- const followsUser = precedingMessage?.role === "user";
-
- if (activityMessages.length > 0) {
- items.push({
- type: "activity",
- key: getActivityKey(
- followsUser ? precedingMessage?.id : turnMessages[0]?.id,
- ),
- messages: activityMessages,
- startTimestamp: turnMessages.find(
- (turnMessage) => turnMessage.timestamp !== undefined,
- )?.timestamp,
- endTimestamp:
- joinedAnswer?.timestamp ?? activityMessages.at(-1)?.timestamp,
- followsUser,
- isInProgress,
- });
- }
-
- if (joinedAnswer) {
- items.push({
- type: "assistant",
- message: joinedAnswer,
- followsUser: activityMessages.length === 0 && followsUser,
- isFinalAnswer: !isInProgress,
- });
- }
- }
-
- const lastItem = items.at(-1);
- if (isRunUnsettled && lastItem?.type === "user") {
- // Same key the turn will claim once its first message lands, so the caret
- // the user may already have opened is not torn down underneath them.
- items.push({
- type: "activity",
- key: getActivityKey(lastItem.message.id),
- messages: [],
- followsUser: true,
- isInProgress: true,
- });
- }
-
- return items;
-}
-
-function getActivityKey(turnAnchorMessageId: string | undefined) {
- return `activity-${turnAnchorMessageId ?? "start"}`;
-}
-
function formatWorkedDuration(totalSeconds: number) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
@@ -887,6 +660,10 @@ export type InAppAgentWindowProps = {
onApproveToolCall: (approvalId: string) => Promise<void>;
onAlwaysAllowToolCall?: (approvalId: string) => Promise<void>;
onRejectToolCall: (approvalId: string) => Promise<void>;
+ onAnswerQuestionnaire: (
+ approvalId: string,
+ answers: InAppAgentQuestionnaireAnswers,
+ ) => Promise<void>;
onOpenConversationHistory: () => void;
onSelectConversation: (conversationId: string) => void;
onSubmit: (
@@ -991,6 +768,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
onApproveToolCall,
onAlwaysAllowToolCall,
onRejectToolCall,
+ onAnswerQuestionnaire,
onOpenConversationHistory,
onSelectConversation,
onSubmit,
@@ -1465,6 +1243,14 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
);
}
+ if (item.type === "questionnaire") {
+ return (
+ <li key={item.key} className="w-full">
+ <InAppAgentQuestionnaireSummary answers={item.answers} />
+ </li>
+ );
+ }
+
const message = item.message;
const feedbackRunId =
message.content.type === "text" && item.isFinalAnswer
@@ -1502,12 +1288,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
</div>
</ConversationScroller>
{pendingToolCalls.length > 0 ? (
- <div
- className={cn(
- "shrink-0 pt-1.5",
- isExpanded ? "px-1.5 pb-2" : "px-3 pb-2",
- )}
- >
+ <div className="shrink-0 px-1.5 pt-1.5 pb-2">
<div
className={cn(
"flex flex-col gap-2",
@@ -1515,13 +1296,14 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
)}
>
{pendingToolCalls.map((tool, index) => (
- <InAppAgentToolCallCard
+ <PendingToolCallCard
key={`${tool.approval?.id ?? tool.name}-${index}`}
tool={tool}
isCompact={!isExpanded}
isDisabled={isRateLimited}
onApproveToolCall={onApproveToolCall}
onAlwaysAllowToolCall={onAlwaysAllowToolCall}
+ onAnswerQuestionnaire={onAnswerQuestionnaire}
onRejectToolCall={onRejectToolCall}
/>
))}
@@ -1592,7 +1374,7 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
rounded corners. */}
<form
className={cn(
- "border-border bg-card focus-within:border-border-contrast relative flex w-full cursor-text flex-col overflow-hidden rounded-xl border shadow-sm transition-colors",
+ "border-border bg-card focus-within:border-border-contrast relative flex w-full cursor-text flex-col overflow-hidden rounded-md border shadow-sm transition-colors",
isExpanded && "mx-auto max-w-3xl",
)}
onClick={() => {
@@ -1671,3 +1453,90 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
</section>
);
}
+
+type PendingToolCallCardProps = {
+ tool: InAppAgentToolCallContent;
+ isCompact: boolean;
+ isDisabled: boolean;
+} & Pick<
+ InAppAgentWindowProps,
+ | "onApproveToolCall"
+ | "onAlwaysAllowToolCall"
+ | "onAnswerQuestionnaire"
+ | "onRejectToolCall"
+>;
+
+function PendingToolCallCard({
+ tool,
+ isCompact,
+ isDisabled,
+ onApproveToolCall,
+ onAlwaysAllowToolCall,
+ onAnswerQuestionnaire,
+ onRejectToolCall,
+}: PendingToolCallCardProps) {
+ const isQuestionnaire = tool.name === IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME;
+ const questions = useMemo(
+ () => (isQuestionnaire ? parseQuestionnaireQuestions(tool.args) : null),
+ [isQuestionnaire, tool.args],
+ );
+
+ if (tool.approval && questions) {
+ return (
+ <PendingQuestionnaireCard
+ approval={tool.approval}
+ questions={questions}
+ isDisabled={isDisabled}
+ onAnswerQuestionnaire={onAnswerQuestionnaire}
+ />
+ );
+ }
+
+ // A questionnaire with malformed questions cannot be answered, only declined.
+ if (isQuestionnaire) {
+ return (
+ <InAppAgentToolCallCard
+ tool={tool}
+ isCompact={isCompact}
+ isDisabled={isDisabled}
+ onRejectToolCall={onRejectToolCall}
+ />
+ );
+ }
+
+ return (
+ <InAppAgentToolCallCard
+ tool={tool}
+ isCompact={isCompact}
+ isDisabled={isDisabled}
+ onApproveToolCall={onApproveToolCall}
+ onAlwaysAllowToolCall={onAlwaysAllowToolCall}
+ onRejectToolCall={onRejectToolCall}
+ />
+ );
+}
+
+type PendingQuestionnaireCardProps = {
+ approval: NonNullable<InAppAgentToolCallContent["approval"]>;
+ questions: readonly InAppAgentQuestionnaireQuestion[];
+ isDisabled: boolean;
+} & Pick<InAppAgentWindowProps, "onAnswerQuestionnaire">;
+
+function PendingQuestionnaireCard({
+ approval,
+ questions,
+ isDisabled,
+ onAnswerQuestionnaire,
+}: PendingQuestionnaireCardProps) {
+ const handleSubmit = (answers: InAppAgentQuestionnaireAnswers) =>
+ onAnswerQuestionnaire(approval.id, answers);
+
+ return (
+ <InAppAgentQuestionnaireCard
+ questions={questions}
+ isSubmitting={approval.status === "submitting"}
+ isDisabled={isDisabled}
+ onSubmit={handleSubmit}
+ />
+ );
+}
diff --git a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
index a457916d0c..683ad51df8 100644
--- a/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -18,11 +18,14 @@ import { useRouter } from "next/router";
import useSessionStorage from "@/src/components/useSessionStorage";
import { createInAppAgentConversationId } from "../ids";
import {
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
IN_APP_AGENT_REDIRECT_TOOL_NAME,
AgUiMessageSchema,
dropEmptyAssistantMessages,
dropUnpairedAssistantToolCalls,
type AgUiMessage,
+ type InAppAgentQuestionnaireAnswers,
+ type InAppAgentToolInputs,
type InAppAgentToolApprovalRequest,
} from "@langfuse/shared/in-app-agent";
import { isActiveInAppAgentRunStatus } from "../watchFrames";
@@ -145,6 +148,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
deleteConversation: async () => undefined,
submit: async () => false,
approveToolCall: async () => undefined,
+ answerQuestionnaire: async () => undefined,
rejectToolCall: async () => undefined,
submitFeedback: async () => undefined,
};
@@ -212,6 +216,10 @@ type InAppAiAgentContextType = {
) => Promise<boolean>;
approveToolCall: (approvalId: string) => Promise<void>;
alwaysAllowToolCall?: (approvalId: string) => Promise<void>;
+ answerQuestionnaire: (
+ approvalId: string,
+ answers: InAppAgentQuestionnaireAnswers,
+ ) => Promise<void>;
rejectToolCall: (approvalId: string) => Promise<void>;
submitFeedback: (params: {
messageId: string;
@@ -888,6 +896,7 @@ function InAppAiAgentProviderInner({
toolCallId: input.toolCallId,
approved: input.approved,
approvalScope: input.approvalScope,
+ toolInputs: input.toolInputs,
}),
onHydratedSnapshot: ({ messages }) => {
performToolSideEffectsForCompletedToolCalls({
@@ -1334,6 +1343,7 @@ function InAppAiAgentProviderInner({
approval: InAppAgentPendingToolApproval;
approved: boolean;
approvalScope: "once" | "conversation";
+ toolInputs?: InAppAgentToolInputs;
conversationId: string;
}) => {
const runId =
@@ -1356,6 +1366,7 @@ function InAppAiAgentProviderInner({
toolCallId: params.approval.approvalRequest.toolCallId,
approved: params.approved,
approvalScope: params.approvalScope,
+ toolInputs: params.toolInputs,
});
return true;
} catch (error) {
@@ -1371,6 +1382,7 @@ function InAppAiAgentProviderInner({
approvalId: string,
approved: boolean,
approvalScope: "once" | "conversation" = "once",
+ toolInputs?: InAppAgentToolInputs,
) => {
const approval = effectivePendingToolApprovals.find(
(approval) => approval.id === approvalId,
@@ -1389,6 +1401,7 @@ function InAppAiAgentProviderInner({
approval,
approved,
approvalScope,
+ toolInputs,
conversationId: selectedConversationId,
});
if (decisionAccepted) {
@@ -1453,6 +1466,14 @@ function InAppAiAgentProviderInner({
[resumeToolApproval],
);
+ const answerQuestionnaire = useCallback(
+ (approvalId: string, answers: InAppAgentQuestionnaireAnswers) =>
+ resumeToolApproval(approvalId, true, "once", {
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: { answers },
+ }),
+ [resumeToolApproval],
+ );
+
const rejectToolCall = useCallback(
(approvalId: string) => resumeToolApproval(approvalId, false),
[resumeToolApproval],
@@ -1493,12 +1514,14 @@ function InAppAiAgentProviderInner({
submit,
approveToolCall,
alwaysAllowToolCall,
+ answerQuestionnaire,
rejectToolCall,
submitFeedback,
}),
[
activityByConversationId,
approveToolCall,
+ answerQuestionnaire,
attentionCount,
alwaysAllowToolCall,
isExpanded,
diff --git a/web/src/features/in-app-agent/fns/buildConversationDisplayItems.clienttest.ts b/web/src/features/in-app-agent/fns/buildConversationDisplayItems.clienttest.ts
new file mode 100644
index 0000000000..d63b1bbdfb
--- /dev/null
+++ b/web/src/features/in-app-agent/fns/buildConversationDisplayItems.clienttest.ts
@@ -0,0 +1,168 @@
+import { IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME } from "@langfuse/shared/in-app-agent";
+import type { InAppAgentWindowMessage } from "@/src/features/in-app-agent/components/InAppAgentWindow";
+import type { InAppAgentToolCallContent } from "@/src/features/in-app-agent/components/utils/utils";
+import {
+ buildConversationDisplayItems,
+ type ConversationDisplayItem,
+} from "./buildConversationDisplayItems";
+
+const userMessage: InAppAgentWindowMessage = {
+ id: "user-1",
+ role: "user",
+ content: { type: "text", text: "Set up an evaluator." },
+};
+
+const introMessage: InAppAgentWindowMessage = {
+ id: "assistant-intro",
+ role: "assistant",
+ content: { type: "text", text: "A few quick questions before I set it up." },
+};
+
+const answerMessage: InAppAgentWindowMessage = {
+ id: "assistant-answer",
+ role: "assistant",
+ content: { type: "text", text: "The evaluator runs on staging." },
+};
+
+const searchTool: InAppAgentToolCallContent = {
+ type: "tool",
+ name: "langfuse_searchDocs",
+ status: "succeeded",
+ args: "{}",
+ result: "[]",
+};
+
+const answers = [
+ { question: "Which environment?", answer: ["Staging"], skipped: false },
+];
+
+function questionnaireTool(
+ state: Pick<InAppAgentToolCallContent, "status" | "approval" | "result">,
+): InAppAgentToolCallContent {
+ return {
+ type: "tool",
+ name: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ args: "{}",
+ ...state,
+ };
+}
+
+function toolGroupMessage(
+ id: string,
+ tools: InAppAgentToolCallContent[],
+): InAppAgentWindowMessage {
+ return { id, role: "assistant", content: { type: "toolGroup", tools } };
+}
+
+const answeredQuestionnaire = questionnaireTool({
+ status: "succeeded",
+ result: JSON.stringify({ type: "questionnaireAnswers", answers }),
+});
+
+/** The shape of the transcript, without the message payloads. */
+function outline(items: ConversationDisplayItem[]) {
+ return items.map((item) => {
+ if (item.type === "user") {
+ return `user ${item.message.id}`;
+ }
+ if (item.type === "activity") {
+ return `activity ${item.key} [${item.messages.map((message) => message.id).join(", ")}]`;
+ }
+ if (item.type === "assistant") {
+ return `${item.isFinalAnswer ? "answer" : "assistant"} ${item.message.id}`;
+ }
+ return `questionnaire ${item.key}`;
+ });
+}
+
+describe("buildConversationDisplayItems", () => {
+ it.each([
+ ["pending", { id: "approval-1", status: "pending" }],
+ ["submitting", { id: "approval-1", status: "submitting" }],
+ ] as const)(
+ "ends the turn at a %s questionnaire so its intro is not hidden in the drawer",
+ (_, approval) => {
+ const items = buildConversationDisplayItems(
+ [
+ userMessage,
+ introMessage,
+ toolGroupMessage("assistant-questionnaire", [
+ questionnaireTool({ status: "running", approval }),
+ ]),
+ ],
+ true,
+ );
+
+ expect(outline(items)).toEqual([
+ "user user-1",
+ "assistant assistant-intro",
+ ]);
+ },
+ );
+
+ it("places an answered questionnaire between the text around it", () => {
+ const items = buildConversationDisplayItems(
+ [
+ userMessage,
+ introMessage,
+ toolGroupMessage("assistant-questionnaire", [answeredQuestionnaire]),
+ answerMessage,
+ ],
+ false,
+ );
+
+ expect(outline(items)).toEqual([
+ "user user-1",
+ "assistant assistant-intro",
+ "questionnaire assistant-questionnaire-questionnaire-0",
+ "answer assistant-answer",
+ ]);
+ expect(items[2]).toEqual({
+ type: "questionnaire",
+ key: "assistant-questionnaire-questionnaire-0",
+ answers,
+ });
+ });
+
+ it("splits the tools around a questionnaire into the turns on either side", () => {
+ const items = buildConversationDisplayItems(
+ [
+ userMessage,
+ toolGroupMessage("assistant-tools", [
+ searchTool,
+ answeredQuestionnaire,
+ { ...searchTool, name: "langfuse_listEvaluators" },
+ ]),
+ answerMessage,
+ ],
+ false,
+ );
+
+ expect(outline(items)).toEqual([
+ "user user-1",
+ "activity activity-user-1 [assistant-tools]",
+ "questionnaire assistant-tools-questionnaire-1",
+ "activity activity-assistant-tools-questionnaire-1 [assistant-tools-tools-2]",
+ "answer assistant-answer",
+ ]);
+ });
+
+ it("waits in a drawer keyed to the questionnaire until the next turn starts", () => {
+ const items = buildConversationDisplayItems(
+ [
+ userMessage,
+ introMessage,
+ toolGroupMessage("assistant-questionnaire", [answeredQuestionnaire]),
+ ],
+ true,
+ );
+
+ expect(items.at(-1)).toEqual({
+ type: "activity",
+ key: "activity-assistant-questionnaire-questionnaire-0",
+ messages: [],
+ followsUser: true,
+ isInProgress: true,
+ });
+ });
+});
diff --git a/web/src/features/in-app-agent/fns/buildConversationDisplayItems.ts b/web/src/features/in-app-agent/fns/buildConversationDisplayItems.ts
new file mode 100644
index 0000000000..aaa3dc5cfa
--- /dev/null
+++ b/web/src/features/in-app-agent/fns/buildConversationDisplayItems.ts
@@ -0,0 +1,358 @@
+import {
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ type InAppAgentQuestionnaireResult,
+} from "@langfuse/shared/in-app-agent";
+import type { InAppAgentMessageContent } from "@/src/features/in-app-agent/components/InAppAgentMessage";
+import type { InAppAgentWindowMessage } from "@/src/features/in-app-agent/components/InAppAgentWindow";
+import type { InAppAgentMessageSource } from "@/src/features/in-app-agent/schema";
+import type { InAppAgentToolCallContent } from "@/src/features/in-app-agent/components/utils/utils";
+import { parseQuestionnaireToolResult } from "@/src/features/in-app-agent/fns/parseQuestionnaireToolResult";
+import { deduplicateBy } from "@/src/utils/arrays";
+
+export type ConversationDisplayItem =
+ | {
+ type: "user";
+ message: InAppAgentWindowMessage;
+ hasPreviousMessage: boolean;
+ }
+ | {
+ type: "activity";
+ /** Identifies the turn, not its contents: the drawer must survive both
+ * the first activity arriving and the run settling without remounting,
+ * or an expanded drawer collapses under the user. */
+ key: string;
+ messages: InAppAgentWindowMessage[];
+ startTimestamp?: number;
+ endTimestamp?: number;
+ followsUser: boolean;
+ isInProgress: boolean;
+ }
+ | {
+ type: "assistant";
+ message: InAppAgentWindowMessage;
+ followsUser: boolean;
+ isFinalAnswer: boolean;
+ }
+ | {
+ type: "questionnaire";
+ key: string;
+ answers: InAppAgentQuestionnaireResult["answers"];
+ };
+
+type QuestionnaireDisplayItem = Extract<
+ ConversationDisplayItem,
+ { type: "questionnaire" }
+>;
+
+type InAppAgentTextMessage = InAppAgentWindowMessage & {
+ content: Extract<InAppAgentMessageContent, { type: "text" }>;
+};
+
+type InAppAgentRedirectActionContent = Extract<
+ InAppAgentMessageContent,
+ { type: "redirectAction" }
+>;
+
+/**
+ * Group the transcript into what the window renders: user bubbles, a drawer of
+ * work per assistant turn, the turn's answer, and the summary of each answered
+ * questionnaire. A questionnaire hands the turn to the user, so it ends the
+ * turn before it.
+ */
+export function buildConversationDisplayItems(
+ messages: InAppAgentWindowMessage[],
+ isRunUnsettled: boolean,
+): ConversationDisplayItem[] {
+ const items: ConversationDisplayItem[] = [];
+ // The drawer speaks for a turn that has produced nothing yet, so a loading
+ // placeholder does not belong in the transcript.
+ const visibleMessages = messages.flatMap((message) =>
+ message.content.type === "loading"
+ ? []
+ : splitToolGroupAtQuestionnaires(message),
+ );
+
+ for (let index = 0; index < visibleMessages.length; ) {
+ const message = visibleMessages[index];
+ if (!message) {
+ break;
+ }
+
+ if (message.role === "user") {
+ items.push({
+ type: "user",
+ message,
+ hasPreviousMessage: index > 0,
+ });
+ index++;
+ continue;
+ }
+
+ if (getQuestionnaireBoundaryTool(message)) {
+ const questionnaireItem = toQuestionnaireItem(message);
+ if (questionnaireItem) {
+ items.push(questionnaireItem);
+ }
+ index++;
+ continue;
+ }
+
+ const turnStartIndex = index;
+ while (
+ index < visibleMessages.length &&
+ visibleMessages[index]?.role === "assistant" &&
+ !getQuestionnaireBoundaryTool(visibleMessages[index])
+ ) {
+ index++;
+ }
+
+ const turnMessages = visibleMessages.slice(turnStartIndex, index);
+ const endsAtQuestionnaire = Boolean(
+ getQuestionnaireBoundaryTool(visibleMessages[index]),
+ );
+ const isInProgress = isRunUnsettled && index === visibleMessages.length;
+ const lastReasoningIndex = turnMessages.findLastIndex(
+ (turnMessage) => turnMessage.content.type === "reasoning",
+ );
+ // Trailing text is the answer; text before the turn's last thought is still
+ // work. A proposed redirect is always actionable, so it never stays behind
+ // in the drawer. Declared once, with the activity bucket as its exact
+ // complement, so no message can fall out of both.
+ const isAnswerPart = (
+ turnMessage: InAppAgentWindowMessage,
+ turnIndex: number,
+ ) =>
+ !isInProgress &&
+ (turnMessage.content.type === "redirectAction" ||
+ (turnMessage.content.type === "text" &&
+ turnIndex > lastReasoningIndex));
+ const answerMessages = turnMessages.filter(isAnswerPart);
+ const activityMessages = turnMessages.filter(
+ (turnMessage, turnIndex) => !isAnswerPart(turnMessage, turnIndex),
+ );
+ const turnSources = deduplicateBy(
+ turnMessages.flatMap((turnMessage) =>
+ turnMessage.content.type === "text"
+ ? (turnMessage.content.sources ?? [])
+ : [],
+ ),
+ (source) => source.url,
+ );
+ // A proposed redirect belongs to the turn, not to whichever block carried
+ // it: the tool result is merged into a preceding text message when there is
+ // one and emitted standalone when there is not, and either can land in the
+ // drawer.
+ const turnRedirectAction = turnMessages.reduce<
+ InAppAgentRedirectActionContent | undefined
+ >(
+ (found, turnMessage) => getRedirectAction(turnMessage) ?? found,
+ undefined,
+ );
+ const joinedAnswer = joinAnswerMessages(
+ answerMessages,
+ turnSources,
+ turnRedirectAction,
+ );
+ const precedingMessage = visibleMessages[turnStartIndex - 1];
+ const followsUser =
+ precedingMessage?.role === "user" ||
+ Boolean(getQuestionnaireBoundaryTool(precedingMessage));
+
+ if (activityMessages.length > 0) {
+ items.push({
+ type: "activity",
+ key: getActivityKey(
+ followsUser ? precedingMessage?.id : turnMessages[0]?.id,
+ ),
+ messages: activityMessages,
+ startTimestamp: turnMessages.find(
+ (turnMessage) => turnMessage.timestamp !== undefined,
+ )?.timestamp,
+ endTimestamp:
+ joinedAnswer?.timestamp ?? activityMessages.at(-1)?.timestamp,
+ followsUser,
+ isInProgress,
+ });
+ }
+
+ if (joinedAnswer) {
+ items.push({
+ type: "assistant",
+ message: joinedAnswer,
+ followsUser: activityMessages.length === 0 && followsUser,
+ isFinalAnswer: !isInProgress && !endsAtQuestionnaire,
+ });
+ }
+ }
+
+ const lastItem = items.at(-1);
+ if (
+ isRunUnsettled &&
+ (lastItem?.type === "user" || lastItem?.type === "questionnaire")
+ ) {
+ // Same key the turn will claim once its first message lands, so the caret
+ // the user may already have opened is not torn down underneath them.
+ items.push({
+ type: "activity",
+ key: getActivityKey(
+ lastItem.type === "user" ? lastItem.message.id : lastItem.key,
+ ),
+ messages: [],
+ followsUser: true,
+ isInProgress: true,
+ });
+ }
+
+ return items;
+}
+
+/**
+ * A tool call awaiting approval is hoisted into its own card above the
+ * composer, so it leaves the transcript. A questionnaire gets a message of its
+ * own, splitting the tools around it into separate groups.
+ */
+function splitToolGroupAtQuestionnaires(
+ message: InAppAgentWindowMessage,
+): InAppAgentWindowMessage[] {
+ if (message.content.type !== "toolGroup") {
+ return [message];
+ }
+
+ const splitMessages: InAppAgentWindowMessage[] = [];
+ let pendingTools: InAppAgentToolCallContent[] = [];
+ const flushPendingTools = () => {
+ if (pendingTools.length === 0) {
+ return;
+ }
+ splitMessages.push({
+ ...message,
+ id:
+ splitMessages.length === 0
+ ? message.id
+ : `${message.id}-tools-${splitMessages.length}`,
+ content: { type: "toolGroup", tools: pendingTools },
+ });
+ pendingTools = [];
+ };
+
+ message.content.tools.forEach((tool, toolIndex) => {
+ if (isQuestionnaireBoundaryTool(tool)) {
+ flushPendingTools();
+ splitMessages.push({
+ ...message,
+ id: `${message.id}-questionnaire-${toolIndex}`,
+ content: { type: "toolGroup", tools: [tool] },
+ });
+ } else if (!tool.approval) {
+ pendingTools.push(tool);
+ }
+ });
+ flushPendingTools();
+
+ return splitMessages;
+}
+
+/** A pending questionnaire is answered in its hoisted card, not here. */
+function toQuestionnaireItem(
+ message: InAppAgentWindowMessage,
+): QuestionnaireDisplayItem | null {
+ const questionnaireResult = parseQuestionnaireToolResult(
+ getQuestionnaireBoundaryTool(message)?.result,
+ );
+
+ return questionnaireResult
+ ? {
+ type: "questionnaire",
+ key: message.id,
+ answers: questionnaireResult.answers,
+ }
+ : null;
+}
+
+function getRedirectAction(
+ message: InAppAgentWindowMessage,
+): InAppAgentRedirectActionContent | undefined {
+ if (message.content.type === "redirectAction") {
+ return message.content;
+ }
+
+ return message.content.type === "text"
+ ? message.content.redirectAction
+ : undefined;
+}
+
+/**
+ * Fold a turn's answer blocks into the single bubble the user reads. Each field
+ * takes the last block that defined it, except `sources`, which arrive already
+ * unioned across the whole turn so a citation earned mid-turn is not lost.
+ */
+function joinAnswerMessages(
+ messages: InAppAgentWindowMessage[],
+ turnSources: InAppAgentMessageSource[],
+ turnRedirectAction: InAppAgentRedirectActionContent | undefined,
+): InAppAgentWindowMessage | null {
+ const textMessages = messages.filter(
+ (message): message is InAppAgentTextMessage =>
+ message.content.type === "text",
+ );
+ const lastText = textMessages.at(-1);
+
+ // A turn can end on a bare redirect with no text to attach it to.
+ if (!lastText) {
+ return messages.at(-1) ?? null;
+ }
+
+ const lastDefined = <T>(
+ pick: (message: InAppAgentTextMessage) => T | undefined,
+ ): T | undefined =>
+ textMessages.reduce<T | undefined>(
+ (found, message) => pick(message) ?? found,
+ undefined,
+ );
+ const runId = lastDefined((message) => message.runId);
+ const feedbackMessageId = lastDefined((message) => message.feedbackMessageId);
+ const feedback = lastDefined((message) => message.content.feedback);
+
+ return {
+ ...lastText,
+ ...(runId ? { runId } : {}),
+ ...(feedbackMessageId ? { feedbackMessageId } : {}),
+ content: {
+ type: "text",
+ text: textMessages.map((message) => message.content.text).join("\n\n"),
+ ...(textMessages.some((message) => message.content.isStreaming)
+ ? { isStreaming: true }
+ : {}),
+ ...(turnSources.length > 0 ? { sources: turnSources } : {}),
+ ...(feedback ? { feedback } : {}),
+ ...(turnRedirectAction ? { redirectAction: turnRedirectAction } : {}),
+ },
+ };
+}
+
+function isQuestionnaireBoundaryTool(tool: InAppAgentToolCallContent) {
+ return (
+ tool.name === IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME &&
+ (tool.approval !== undefined ||
+ parseQuestionnaireToolResult(tool.result) !== null)
+ );
+}
+
+function getQuestionnaireBoundaryTool(
+ message: InAppAgentWindowMessage | undefined,
+) {
+ if (message?.content.type !== "toolGroup") {
+ return undefined;
+ }
+
+ const [tool, ...otherTools] = message.content.tools;
+ if (!tool || otherTools.length > 0 || !isQuestionnaireBoundaryTool(tool)) {
+ return undefined;
+ }
+
+ return tool;
+}
+
+function getActivityKey(turnAnchorMessageId: string | undefined) {
+ return `activity-${turnAnchorMessageId ?? "start"}`;
+}
diff --git a/web/src/features/in-app-agent/fns/parseQuestionnaireToolResult.ts b/web/src/features/in-app-agent/fns/parseQuestionnaireToolResult.ts
new file mode 100644
index 0000000000..9a91e0249f
--- /dev/null
+++ b/web/src/features/in-app-agent/fns/parseQuestionnaireToolResult.ts
@@ -0,0 +1,14 @@
+import { safeJsonParse } from "@langfuse/shared";
+import { InAppAgentQuestionnaireResultSchema } from "@langfuse/shared/in-app-agent";
+
+export function parseQuestionnaireToolResult(result: string | undefined) {
+ if (result === undefined) {
+ return null;
+ }
+
+ const parsed = InAppAgentQuestionnaireResultSchema.safeParse(
+ safeJsonParse(result),
+ );
+
+ return parsed.success ? parsed.data : null;
+}
diff --git a/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts b/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts
index 249dadcbb3..617b78563b 100644
--- a/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts
+++ b/web/src/features/in-app-agent/lib/backgroundExecutionSession.ts
@@ -3,6 +3,7 @@ import type { AgentSubscriber } from "@ag-ui/client";
import {
type AgUiContext,
type AgUiMessage,
+ type InAppAgentToolInputs,
type InAppAgentToolApprovalRequest,
AgUiMessageSchema,
InAppAgentRunErrorCode,
@@ -28,6 +29,7 @@ export type ApprovalDecision = {
toolCallId: string;
approved: boolean;
approvalScope?: "once" | "conversation";
+ toolInputs?: InAppAgentToolInputs;
};
export type BackgroundExecutionRunView = {
diff --git a/web/src/features/in-app-agent/server/backgroundRunService.ts b/web/src/features/in-app-agent/server/backgroundRunService.ts
index 75e1ce7190..cf85103a99 100644
--- a/web/src/features/in-app-agent/server/backgroundRunService.ts
+++ b/web/src/features/in-app-agent/server/backgroundRunService.ts
@@ -1,7 +1,12 @@
import { EventType } from "@ag-ui/core";
import { randomUUID } from "crypto";
-import { BaseError, LangfuseNotFoundError, type Plan } from "@langfuse/shared";
+import {
+ BaseError,
+ InvalidRequestError,
+ LangfuseNotFoundError,
+ type Plan,
+} from "@langfuse/shared";
import { Prisma, type PrismaClient } from "@langfuse/shared/src/db";
import {
InAppAgentRunQueue,
@@ -16,7 +21,9 @@ import {
InAppAgentRunStatusSchema,
parseInAppAgentApprovalDecisionEvent,
parseInAppAgentInterruptEvent,
+ validateInAppAgentToolInputs,
type AgUiContext,
+ type InAppAgentToolInputs,
} from "@langfuse/shared/in-app-agent";
import { getInAppAgentPrefixedToolName } from "@langfuse/shared/in-app-agent/server/mcpPolicy";
import { createInAppAgentMessageId, createInAppAgentRunId } from "../ids";
@@ -360,6 +367,7 @@ export async function decideBackgroundApproval(params: {
toolCallId: string;
approved: boolean;
approvalScope?: "once" | "conversation";
+ toolInputs?: InAppAgentToolInputs;
userId: string;
model: string | undefined;
}) {
@@ -393,6 +401,16 @@ export async function decideBackgroundApproval(params: {
throw new LangfuseNotFoundError("Approval request not found");
}
+ const toolInputsValidation = validateInAppAgentToolInputs({
+ toolName: approvalRequest.toolName,
+ args: approvalRequest.args,
+ approved: params.approved,
+ toolInputs: params.toolInputs,
+ });
+ if (!toolInputsValidation.success) {
+ throw new InvalidRequestError(toolInputsValidation.error);
+ }
+
// Resolve the granted tool from the persisted interrupt, never client input.
const alwaysAllowToolName =
params.approvalScope === "conversation" && params.approved
@@ -408,6 +426,7 @@ export async function decideBackgroundApproval(params: {
toolCallId: params.toolCallId,
approved: params.approved,
alwaysAllowToolName,
+ toolInputs: params.toolInputs,
decidedByUserId: params.userId,
model: params.model,
});
diff --git a/web/src/features/in-app-agent/server/router.ts b/web/src/features/in-app-agent/server/router.ts
index 883bfe4151..eb4ad726d2 100644
--- a/web/src/features/in-app-agent/server/router.ts
+++ b/web/src/features/in-app-agent/server/router.ts
@@ -18,6 +18,7 @@ import {
getInAppAgentInstrumentationObservationId,
getInAppAgentInstrumentationTraceId,
IN_APP_AGENT_PRODUCT_ENVIRONMENT,
+ InAppAgentToolInputsSchema,
} from "@langfuse/shared/in-app-agent";
import { InAppAgentMessageFeedbackValueSchema } from "../schema";
import {
@@ -85,10 +86,17 @@ const DecideToolApprovalInput = ConversationIdInput.extend({
approved: z.boolean(),
// "conversation" also approves this call; it never means approve-without-run.
approvalScope: z.enum(["once", "conversation"]).default("once"),
-}).refine((input) => input.approved || input.approvalScope === "once", {
- message: "A rejection cannot grant a tool",
- path: ["approvalScope"],
-});
+ /** Validated against the persisted tool call in the service. */
+ toolInputs: InAppAgentToolInputsSchema.optional(),
+})
+ .refine((input) => input.approved || input.approvalScope === "once", {
+ message: "A rejection cannot grant a tool",
+ path: ["approvalScope"],
+ })
+ .refine((input) => input.approved || input.toolInputs === undefined, {
+ message: "A rejection cannot carry tool inputs",
+ path: ["toolInputs"],
+ });
const SubmitFeedbackInput = ConversationIdInput.extend({
messageId: z.string(),
@@ -302,6 +310,7 @@ export const inAppAgentRouter = createTRPCRouter({
toolCallId: input.toolCallId,
approved: input.approved,
approvalScope: input.approvalScope,
+ toolInputs: input.toolInputs,
userId: ctx.session.user.id,
model: modelConfig.modelId,
});
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index e2b64fd3ae..650419e385 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -324,6 +324,9 @@ export async function executeInAppAgentRun(params: {
: {}),
approvalDecidedAt: run.createdAt.toISOString(),
approvalRequest,
+ ...(request.toolInputs
+ ? { toolInputs: request.toolInputs }
+ : {}),
},
},
}
diff --git a/worker/src/features/in-app-agent/runtime/agent.ts b/worker/src/features/in-app-agent/runtime/agent.ts
index 15aa9bd153..3fb9824db9 100644
--- a/worker/src/features/in-app-agent/runtime/agent.ts
+++ b/worker/src/features/in-app-agent/runtime/agent.ts
@@ -17,7 +17,10 @@ import {
import { getToolFailureMessage } from "@langfuse/shared/in-app-agent/server/toolErrors";
import { IN_APP_AGENT_MAX_STEPS } from "@langfuse/shared/in-app-agent/server/tunables";
import type { AgUiRunAgentInput, ResumeForwardedProps } from "./types";
-import { createManualToolApprovalRunInput } from "./human-in-the-loop";
+import {
+ createManualToolApprovalRunInput,
+ type ManualToolApprovalResumeData,
+} from "./human-in-the-loop";
import type {
InAppAgentPromptMetadata,
InAppAgentTracingConfig,
@@ -29,6 +32,7 @@ import {
} from "./mcpRateLimitWait";
import {
createSandboxTools,
+ createQuestionnaireTool,
createRedirectActionTool,
getToolCallId,
hasCallableExecute,
@@ -53,6 +57,7 @@ import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
import {
IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER,
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
IN_APP_AGENT_REDIRECT_TOOL_NAME,
} from "@langfuse/shared/in-app-agent";
import type { InAppAgentModelConfig } from "@langfuse/shared/in-app-agent/server/modelProvider";
@@ -1236,6 +1241,7 @@ async function createMastraAdapter(params: {
projectId: params.options.redirectAction.projectId,
isV4Enabled: params.options.redirectAction.isV4Enabled,
}),
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: createQuestionnaireTool(),
...(params.options.sandbox
? createSandboxTools(params.options.sandbox)
: {}),
@@ -1320,6 +1326,7 @@ async function createMastraAdapter(params: {
},
executeToolCall: async (
approvalRequest: InAppAgentToolApprovalRequest,
+ resumeData: ManualToolApprovalResumeData,
) => {
const tool = tools[approvalRequest.toolName] as
| ExecutableInAppAgentTool
@@ -1344,6 +1351,7 @@ async function createMastraAdapter(params: {
threadId: params.input.threadId,
resourceId: params.input.threadId,
suspend: async () => undefined,
+ resumeData,
},
});
diff --git a/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts b/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts
index a28cd21f0b..a37ad01944 100644
--- a/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts
+++ b/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts
@@ -1,7 +1,15 @@
import { EventType } from "@ag-ui/core";
+import { Agent } from "@mastra/core/agent";
+import type { MastraModelConfig } from "@mastra/core/llm";
import { describe, expect, it } from "vitest";
+import { IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME } from "@langfuse/shared/in-app-agent";
+import {
+ createInAppAgentToolPolicy,
+ withInAppAgentToolApproval,
+} from "@langfuse/shared/in-app-agent/server/mcpPolicy";
import { createManualToolApprovalRunInput } from "./human-in-the-loop";
+import { createQuestionnaireTool } from "./tools";
import type { AgUiRunAgentInput } from "./types";
const approvalRequest = {
@@ -12,7 +20,9 @@ const approvalRequest = {
runId: "interrupted-run-1",
};
-function resumeInput(): AgUiRunAgentInput {
+function resumeInput(
+ resume: Record<string, unknown> = { approved: true, approvalRequest },
+): AgUiRunAgentInput {
return {
threadId: "conversation-1",
runId: "run-2",
@@ -26,12 +36,7 @@ function resumeInput(): AgUiRunAgentInput {
tools: [],
context: [],
forwardedProps: {
- command: {
- resume: {
- approved: true,
- approvalRequest,
- },
- },
+ command: { resume },
},
};
}
@@ -90,4 +95,192 @@ describe("createManualToolApprovalRunInput", () => {
JSON.stringify(envelope),
);
});
+
+ it("hands questionnaire answers to the tool and returns them to the model", async () => {
+ const toolMessage = await approveQuestionnaire({
+ toolInputs: {
+ [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: {
+ answers: [
+ { selectedOptionIndexes: [1], otherText: null },
+ { selectedOptionIndexes: [], otherText: null },
+ ],
+ },
+ },
+ });
+
+ expect(toolMessage).not.toHaveProperty("error");
+ expect(JSON.parse(String(toolMessage?.content))).toEqual({
+ type: "questionnaireAnswers",
+ answers: [
+ { question: "Which evaluator type?", answer: ["Code"], skipped: false },
+ { question: "Anything else?", answer: [], skipped: true },
+ ],
+ });
+ });
+
+ it("returns every question as skipped when an approval carries no answers", async () => {
+ const toolMessage = await approveQuestionnaire({});
+
+ expect(JSON.parse(String(toolMessage?.content))).toEqual({
+ type: "questionnaireAnswers",
+ answers: [
+ { question: "Which evaluator type?", answer: [], skipped: true },
+ { question: "Anything else?", answer: [], skipped: true },
+ ],
+ });
+ });
});
+
+describe("questionnaire approval pause", () => {
+ it("pauses for the user when the questionnaire args are valid", async () => {
+ const chunks = await streamQuestionnaireCall(questionnaireRequest.args);
+
+ expect(chunks.map((chunk) => chunk.type)).toContain("tool-call-approval");
+ });
+
+ it("returns invalid questionnaire args to the model instead of pausing", async () => {
+ const [firstQuestion, secondQuestion] = questionnaireRequest.args.questions;
+ const chunks = await streamQuestionnaireCall({
+ questions: [
+ {
+ ...firstQuestion,
+ options: firstQuestion.options.map((option) => ({
+ ...option,
+ recommended: true,
+ })),
+ },
+ secondQuestion,
+ ],
+ });
+
+ const toolResult = chunks.find((chunk) => chunk.type === "tool-result");
+
+ expect(chunks.map((chunk) => chunk.type)).not.toContain(
+ "tool-call-approval",
+ );
+ expect(JSON.stringify(toolResult?.payload)).toContain(
+ "Mark at most one option per question as recommended.",
+ );
+ });
+});
+
+type ScriptedModel = Extract<MastraModelConfig, { specificationVersion: "v3" }>;
+
+const emptyUsage = {
+ inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
+ outputTokens: { total: 0, text: 0, reasoning: 0 },
+};
+
+// Calls the questionnaire tool once, then stops on the next step.
+async function streamQuestionnaireCall(args: unknown) {
+ let step = 0;
+ const respond = async () => {
+ const isFirstStep = step++ === 0;
+
+ return {
+ stream: new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: "stream-start", warnings: [] });
+ if (isFirstStep) {
+ controller.enqueue({
+ type: "tool-call",
+ toolCallId: "tool-call-3",
+ toolName: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ input: JSON.stringify(args),
+ });
+ }
+ controller.enqueue({
+ type: "finish",
+ finishReason: isFirstStep
+ ? { unified: "tool-calls", raw: "tool_calls" }
+ : { unified: "stop", raw: "stop" },
+ usage: emptyUsage,
+ });
+ controller.close();
+ },
+ }),
+ };
+ };
+ const model = {
+ specificationVersion: "v3",
+ provider: "openai.responses",
+ modelId: "gpt-4.1",
+ supportedUrls: {},
+ doGenerate: respond,
+ doStream: respond,
+ } satisfies ScriptedModel;
+ const agent = new Agent({
+ id: "questionnaire-approval-probe",
+ name: "questionnaire-approval-probe",
+ instructions: "probe",
+ model,
+ tools: withInAppAgentToolApproval(
+ { [IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME]: createQuestionnaireTool() },
+ createInAppAgentToolPolicy({}),
+ ),
+ });
+
+ const result = await agent.stream("ask me");
+ const chunks: { type: string; payload?: unknown }[] = [];
+ for await (const chunk of result.fullStream) {
+ chunks.push(chunk);
+ }
+
+ return chunks;
+}
+
+const questionnaireRequest = {
+ type: "tool_approval_request" as const,
+ toolCallId: "tool-call-2",
+ toolName: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ args: {
+ questions: [
+ {
+ question: "Which evaluator type?",
+ options: [
+ {
+ label: "LLM-as-a-judge",
+ description: "Model-graded",
+ recommended: true,
+ },
+ { label: "Code", description: "Deterministic", recommended: false },
+ ],
+ allowMultiple: false,
+ },
+ {
+ question: "Anything else?",
+ options: [
+ { label: "Yes", description: "Daily run", recommended: false },
+ { label: "No", description: "Manual only", recommended: false },
+ ],
+ allowMultiple: false,
+ },
+ ],
+ },
+ runId: "interrupted-run-1",
+};
+
+async function approveQuestionnaire(resume: Record<string, unknown>) {
+ const tool = createQuestionnaireTool();
+ const { input } = await createManualToolApprovalRunInput({
+ input: resumeInput({
+ approved: true,
+ approvalRequest: questionnaireRequest,
+ ...resume,
+ }),
+ executeToolCall: async (request, resumeData) => {
+ const result = await tool.execute?.(request.args as never, {
+ agent: {
+ agentId: "test",
+ toolCallId: request.toolCallId,
+ messages: [],
+ suspend: async () => undefined,
+ resumeData,
+ },
+ });
+ return { result, modelResult: result };
+ },
+ });
+
+ return input.messages.find((message) => message.role === "tool");
+}
diff --git a/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts b/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts
index d15b0bd7d6..307f3a9a5d 100644
--- a/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts
+++ b/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts
@@ -4,6 +4,9 @@ import {
type AgUiEvent,
type AgUiMessage,
type InAppAgentToolApprovalRequest,
+ type InAppAgentToolInputs,
+ type InAppAgentToolWithInputs,
+ isInAppAgentToolWithInputs,
} from "@langfuse/shared/in-app-agent";
import { toAgUiToolResultContent } from "@langfuse/shared/in-app-agent/server/toolResults";
import type { AgUiRunAgentInput, ResumeForwardedProps } from "./types";
@@ -17,6 +20,19 @@ const MANUAL_TOOL_APPROVAL_REJECTION_ERROR = JSON.stringify({
type DeveloperGuidanceMessage = Extract<AgUiMessage, { role: "developer" }>;
+/**
+ * The approved tool's own entry of the decision's tool inputs, which the tool
+ * reads as Mastra's `context.agent.resumeData`.
+ */
+export type ManualToolApprovalResumeData =
+ | InAppAgentToolInputs[InAppAgentToolWithInputs]
+ | undefined;
+
+type ExecuteApprovedToolCall = (
+ approvalRequest: InAppAgentToolApprovalRequest,
+ resumeData: ManualToolApprovalResumeData,
+) => Promise<{ result: unknown; modelResult: unknown }>;
+
export type ManualToolApprovalRunInput = {
input: AgUiRunAgentInput;
syntheticEvents: AgUiEvent[];
@@ -29,9 +45,7 @@ export type ManualToolApprovalRunInput = {
export async function createManualToolApprovalRunInput(params: {
input: AgUiRunAgentInput;
- executeToolCall: (
- approvalRequest: InAppAgentToolApprovalRequest,
- ) => Promise<{ result: unknown; modelResult: unknown }>;
+ executeToolCall: ExecuteApprovedToolCall;
onApprovedToolCallExecuted?: () => void | Promise<void>;
}): Promise<ManualToolApprovalRunInput> {
const forwardedProps = getResumeForwardedProps(params.input);
@@ -40,7 +54,8 @@ export async function createManualToolApprovalRunInput(params: {
return { input: params.input, syntheticEvents: [] };
}
- const { approved, approvalRequest } = forwardedProps.command.resume;
+ const { approved, approvalRequest, toolInputs } =
+ forwardedProps.command.resume;
if (!approved) {
const assistantMessage =
createManualToolCallAssistantMessage(approvalRequest);
@@ -80,6 +95,7 @@ export async function createManualToolApprovalRunInput(params: {
const { toolResult, modelToolResult, toolError } =
await executeApprovedToolCall({
approvalRequest,
+ resumeData: getToolResumeData(approvalRequest.toolName, toolInputs),
executeToolCall: params.executeToolCall,
});
await params.onApprovedToolCallExecuted?.();
@@ -143,9 +159,8 @@ function createToolRejectionGuidanceMessage(
async function executeApprovedToolCall(params: {
approvalRequest: InAppAgentToolApprovalRequest;
- executeToolCall: (
- approvalRequest: InAppAgentToolApprovalRequest,
- ) => Promise<{ result: unknown; modelResult: unknown }>;
+ resumeData: ManualToolApprovalResumeData;
+ executeToolCall: ExecuteApprovedToolCall;
}): Promise<{
toolResult: unknown;
modelToolResult: unknown;
@@ -154,6 +169,7 @@ async function executeApprovedToolCall(params: {
try {
const { result, modelResult } = await params.executeToolCall(
params.approvalRequest,
+ params.resumeData,
);
return { toolResult: result, modelToolResult: modelResult };
@@ -164,6 +180,15 @@ async function executeApprovedToolCall(params: {
}
}
+function getToolResumeData(
+ toolName: string,
+ toolInputs: InAppAgentToolInputs | undefined,
+): ManualToolApprovalResumeData {
+ return isInAppAgentToolWithInputs(toolName)
+ ? toolInputs?.[toolName]
+ : undefined;
+}
+
function getResumeForwardedProps(
input: AgUiRunAgentInput,
): ResumeForwardedProps | undefined {
diff --git a/worker/src/features/in-app-agent/runtime/tools.openaiSchema.test.ts b/worker/src/features/in-app-agent/runtime/tools.openaiSchema.test.ts
index 65cb05739b..27a2a44a42 100644
--- a/worker/src/features/in-app-agent/runtime/tools.openaiSchema.test.ts
+++ b/worker/src/features/in-app-agent/runtime/tools.openaiSchema.test.ts
@@ -2,8 +2,11 @@ import { Agent } from "@mastra/core/agent";
import type { MastraModelConfig } from "@mastra/core/llm";
import { describe, expect, it } from "vitest";
-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@langfuse/shared/in-app-agent";
-import { createRedirectActionTool } from "./tools";
+import {
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ IN_APP_AGENT_REDIRECT_TOOL_NAME,
+} from "@langfuse/shared/in-app-agent";
+import { createQuestionnaireTool, createRedirectActionTool } from "./tools";
type OpenAIResponsesModel = Extract<
MastraModelConfig,
@@ -77,40 +80,46 @@ function maxOptionalNesting(node: unknown): number {
);
}
-describe("in-app agent redirect tool schema on OpenAI", () => {
+describe("in-app agent local tool schemas on OpenAI", () => {
// Nesting 3 (~23 KB) makes OpenAI Responses return `incomplete` /
// `max_output_tokens` with zero usage; nesting 2 (~12 KB) is accepted.
- it("stays within the optional nesting OpenAI accepts", async () => {
- const { model, calls } = createRecordingOpenAIModel();
- const agent = new Agent({
- id: "redirect-schema-probe",
- name: "redirect-schema-probe",
- instructions: "probe",
- model,
- tools: {
- [IN_APP_AGENT_REDIRECT_TOOL_NAME]: createRedirectActionTool({
- projectId: "project-id",
- isV4Enabled: true,
- }),
- },
- });
+ it.each([
+ {
+ toolName: IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ tool: createRedirectActionTool({
+ projectId: "project-id",
+ isV4Enabled: true,
+ }),
+ },
+ {
+ toolName: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ tool: createQuestionnaireTool(),
+ },
+ ])(
+ "keeps $toolName within the optional nesting OpenAI accepts",
+ async ({ toolName, tool }) => {
+ const { model, calls } = createRecordingOpenAIModel();
+ const agent = new Agent({
+ id: "tool-schema-probe",
+ name: "tool-schema-probe",
+ instructions: "probe",
+ model,
+ tools: { [toolName]: tool },
+ });
- const result = await agent.stream("hi");
- await result.text;
+ const result = await agent.stream("hi");
+ await result.text;
- const redirectTool = calls
- .flatMap((call) => call.tools ?? [])
- .find(
- (tool) =>
- tool.type === "function" &&
- tool.name === IN_APP_AGENT_REDIRECT_TOOL_NAME,
- );
- if (redirectTool?.type !== "function") {
- throw new Error("redirect tool was not sent to the model");
- }
+ const sentTool = calls
+ .flatMap((call) => call.tools ?? [])
+ .find((tool) => tool.type === "function" && tool.name === toolName);
+ if (sentTool?.type !== "function") {
+ throw new Error(`${toolName} was not sent to the model`);
+ }
- const schema = redirectTool.inputSchema;
- expect(maxOptionalNesting(schema)).toBeLessThanOrEqual(2);
- expect(JSON.stringify(schema).length).toBeLessThan(16_000);
- });
+ const schema = sentTool.inputSchema;
+ expect(maxOptionalNesting(schema)).toBeLessThanOrEqual(2);
+ expect(JSON.stringify(schema).length).toBeLessThan(16_000);
+ },
+ );
});
diff --git a/worker/src/features/in-app-agent/runtime/tools.ts b/worker/src/features/in-app-agent/runtime/tools.ts
index 4a4dd6a3bc..6307446be6 100644
--- a/worker/src/features/in-app-agent/runtime/tools.ts
+++ b/worker/src/features/in-app-agent/runtime/tools.ts
@@ -37,6 +37,13 @@ import {
InAppAgentSandboxWriteArgsSchema,
IN_APP_AGENT_REDIRECT_TOOL_NAME,
IN_APP_AGENT_SILENT_MCP_OUTPUT_TYPE,
+ IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS,
+ IN_APP_AGENT_QUESTIONNAIRE_MAX_QUESTIONS,
+ IN_APP_AGENT_QUESTIONNAIRE_MIN_OPTIONS,
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ InAppAgentQuestionnaireArgsSchema,
+ resolveInAppAgentQuestionnaireAnswers,
+ InAppAgentToolInputsSchema,
} from "@langfuse/shared/in-app-agent";
import {
isSilentInAppAgentMcpToolOutput,
@@ -466,6 +473,55 @@ export function createRedirectActionTool({
});
}
+// Always gated behind a human decision: the answers arrive as the tool's
+// entry of the approval's tool inputs, so the tool only turns them into a model-facing result.
+export function createQuestionnaireTool() {
+ return createTool({
+ id: IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME,
+ description: [
+ `Ask the user up to ${IN_APP_AGENT_QUESTIONNAIRE_MAX_QUESTIONS} short questions in one form when you need decisions you cannot infer from context.`,
+ `Give each question ${IN_APP_AGENT_QUESTIONNAIRE_MIN_OPTIONS} to ${IN_APP_AGENT_QUESTIONNAIRE_MAX_OPTIONS} concrete options and mark the best default as recommended. The user can always type a custom answer instead, so do not add an "Other" option. Ask open-ended questions in plain chat instead.`,
+ "Batch related questions into a single call instead of asking one at a time.",
+ "Before calling, write one short sentence in chat that tells the user why you are asking, so the form does not appear without context.",
+ "The user may skip individual questions or dismiss the form, which skips every question (skipped: true); respect that and do not ask the same questions again.",
+ ].join(" "),
+ inputSchema: InAppAgentQuestionnaireArgsSchema,
+ // Invalid args skip the approval pause so execute's input validation
+ // returns the error to the model instead of showing an unanswerable form.
+ requireApproval: (input) =>
+ InAppAgentQuestionnaireArgsSchema.safeParse(input).success,
+ execute: async (input, context) => {
+ // An approval without answers (e.g. from a client that predates the
+ // questionnaire card) counts as skipping every question, so the model
+ // moves on instead of retrying the tool.
+ const answers =
+ getQuestionnaireResumeAnswers(context?.agent?.resumeData) ??
+ input.questions.map(() => ({
+ selectedOptionIndexes: [],
+ otherText: null,
+ }));
+ const resolved = resolveInAppAgentQuestionnaireAnswers({
+ args: input,
+ answers,
+ });
+
+ if (!resolved.success) {
+ throw new Error(resolved.error);
+ }
+
+ return resolved.result;
+ },
+ });
+}
+
+function getQuestionnaireResumeAnswers(resumeData: unknown) {
+ const parsed =
+ InAppAgentToolInputsSchema.shape[
+ IN_APP_AGENT_QUESTIONNAIRE_TOOL_NAME
+ ].safeParse(resumeData);
+ return parsed.success ? parsed.data?.answers : undefined;
+}
+
function getRedirectActionToolResult({
input,
projectId,
diff --git a/worker/src/features/in-app-agent/runtime/types.ts b/worker/src/features/in-app-agent/runtime/types.ts
index a135a2d8c8..9cf08d0cd6 100644
--- a/worker/src/features/in-app-agent/runtime/types.ts
+++ b/worker/src/features/in-app-agent/runtime/types.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
import type { AgUiContext, AgUiMessage } from "@langfuse/shared/in-app-agent";
-import { InAppAgentToolApprovalRequestSchema } from "@langfuse/shared/in-app-agent";
+import {
+ InAppAgentToolApprovalRequestSchema,
+ InAppAgentToolInputsSchema,
+} from "@langfuse/shared/in-app-agent";
type AgUiTool = {
name: string;
@@ -19,6 +22,7 @@ export const ResumeForwardedPropsSchema = z.object({
approvalRequestedAt: z.iso.datetime({ offset: true }).optional(),
approvalDecidedAt: z.iso.datetime({ offset: true }).optional(),
approvalRequest: InAppAgentToolApprovalRequestSchema,
+ toolInputs: InAppAgentToolInputsSchema.optional(),
}),
}),
});