diff --git a/apps/backend/cmd/mock-agent/scenarios.go b/apps/backend/cmd/mock-agent/scenarios.go
index 68e3eb9316..81e67b5010 100644
--- a/apps/backend/cmd/mock-agent/scenarios.go
+++ b/apps/backend/cmd/mock-agent/scenarios.go
@@ -32,6 +32,7 @@ var scenarioRegistry = map[string]func(e *emitter){
"untracked-file-setup": scenarioUntrackedFileSetup,
"untracked-file-modify": scenarioUntrackedFileModify,
"clarification": scenarioClarification,
+ "clarification-markdown": scenarioClarificationMarkdown,
"clarification-multi": scenarioClarificationMulti,
"clarification-timeout": scenarioClarificationTimeout,
"multi-permission": scenarioMultiPermission,
@@ -699,6 +700,7 @@ const (
clarificationDescKey = "description"
clarificationPromptKey = "prompt"
clarificationIDKey = "id"
+ clarificationTitleKey = "title"
)
func mockOption(label, description string) map[string]any {
@@ -724,6 +726,27 @@ func clarificationQuestionArgs() map[string]any {
}
}
+// clarificationMarkdownQuestionArgs keeps a permanent real-protocol fixture
+// for the lightweight Markdown supported by clarification question fields.
+func clarificationMarkdownQuestionArgs() map[string]any {
+ return map[string]any{
+ "context": "Keep `context` literal.\n\nNo Markdown rendering here.",
+ "questions": []map[string]any{
+ {
+ clarificationIDKey: "markdown",
+ clarificationTitleKey: "Use `DB`",
+ clarificationPromptKey: "Choose **one** storage mode:\n\n" +
+ "1. Prefer reliability\n2. Prefer speed\n\n" +
+ "Read [storage guidance](https://example.com/storage).",
+ clarificationOptionsKey: []map[string]any{
+ mockOption("`Postgres` [docs](https://example.com/postgres)", "Best for **production** workloads"),
+ mockOption("SQLite", "Best for *local* work"),
+ },
+ },
+ },
+ }
+}
+
// clarificationMultiQuestionArgs returns the MCP arguments for a 3-question
// clarification bundle that exercises the multi-question UI flow.
func clarificationMultiQuestionArgs() map[string]any {
@@ -778,6 +801,22 @@ func scenarioClarification(e *emitter) {
e.text(fmt.Sprintf("You answered: %s", result))
}
+// scenarioClarificationMarkdown exercises the restricted Markdown renderer
+// through the same blocking MCP round trip used by real clarification calls.
+func scenarioClarificationMarkdown(e *emitter) {
+ fixedDelay(100)
+ e.text("Let me ask you a formatted question about project storage.")
+
+ result, err := callMCPTool("kandev", "ask_user_question_kandev", clarificationMarkdownQuestionArgs())
+ if err != nil {
+ e.text(fmt.Sprintf("Question failed: %s", err))
+ return
+ }
+
+ fixedDelay(50)
+ e.text(fmt.Sprintf("You answered: %s", result))
+}
+
// scenarioClarificationMulti: stress the multi-question path — 3 questions in
// one bundle, all required, single MCP call.
func scenarioClarificationMulti(e *emitter) {
diff --git a/apps/web/components/task/chat/clarification-input-overlay.test.tsx b/apps/web/components/task/chat/clarification-input-overlay.test.tsx
index 2feef1146f..c617c47b26 100644
--- a/apps/web/components/task/chat/clarification-input-overlay.test.tsx
+++ b/apps/web/components/task/chat/clarification-input-overlay.test.tsx
@@ -1,7 +1,12 @@
import { createRef } from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, cleanup, fireEvent, screen } from "@testing-library/react";
-import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http";
+import {
+ sessionId as toSessionId,
+ taskId as toTaskId,
+ type ClarificationRequestMetadata,
+ type Message,
+} from "@/lib/types/http";
import {
ClarificationEscapeGuardProvider,
type ClarificationEscapeGuardEntry,
@@ -343,3 +348,52 @@ describe("ClarificationInputOverlay — labelled Skip button", () => {
});
});
});
+
+describe("ClarificationInputOverlay — lightweight Markdown", () => {
+ it("renders question fields without changing the selected option payload", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response("{}", { status: 200, headers: { "Content-Type": "application/json" } }),
+ );
+ const message = clarMessage({ id: "m1", questionId: "q1", index: 0, total: 1 });
+ const metadata = message.metadata as ClarificationRequestMetadata;
+ metadata.context = "Keep `context` literal";
+ metadata.question = {
+ id: "q1",
+ title: "Use `fast` mode",
+ prompt: "Choose **one**:\n\n1. First\n2. Second",
+ options: [
+ {
+ option_id: "fast-mode",
+ label: "Run in `fast` mode",
+ description: "Best for **small** changes",
+ },
+ ],
+ };
+ renderOverlay([message]);
+
+ const card = screen.getByTestId("clarification-question-card");
+ const title = Array.from(card.querySelectorAll("span")).find(
+ (element) => element.textContent === "Use fast mode" && element.querySelector("code"),
+ );
+ expect(title).toBeDefined();
+ expect(card.querySelector("ol")?.textContent).toContain("First");
+
+ const optionLabel = screen.getByTestId("clarification-option-label");
+ const optionDescription = screen.getByTestId("clarification-option-description");
+ expect(optionLabel.querySelector("code")?.textContent).toBe("fast");
+ expect(optionDescription.querySelector("strong")?.textContent).toBe("small");
+
+ const context = screen.getByTestId("clarification-context");
+ expect(context.textContent).toBe("Keep `context` literal");
+ expect(context.querySelector("code")).toBeNull();
+
+ fireEvent.click(optionLabel.querySelector("code")!);
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(String(init.body))).toEqual({
+ answers: [{ question_id: "q1", selected_options: ["fast-mode"] }],
+ rejected: false,
+ });
+ });
+});
diff --git a/apps/web/components/task/chat/clarification-input-overlay.tsx b/apps/web/components/task/chat/clarification-input-overlay.tsx
index 19eb2a9337..009f458df4 100644
--- a/apps/web/components/task/chat/clarification-input-overlay.tsx
+++ b/apps/web/components/task/chat/clarification-input-overlay.tsx
@@ -2,8 +2,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import { IconMessageQuestion, IconInfoCircle } from "@tabler/icons-react";
-import ReactMarkdown from "react-markdown";
-import { markdownComponents, remarkPlugins } from "@/components/shared/markdown-components";
import type {
Message,
ClarificationRequestMetadata,
@@ -21,6 +19,7 @@ import {
countRunes,
} from "./clarification-overlay-parts";
import { ClarificationHeaderActions } from "./clarification-overlay-header";
+import { ClarificationMarkdown } from "./clarification-markdown";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
@@ -154,18 +153,21 @@ function ClarificationCard(props: CardProps) {
)}
{metadata.question.title && (
-
+
{total > 1 ? "· " : ""}
- {metadata.question.title}
+
+ {metadata.question.title}
+
)}
)}
-
-
- {question.prompt}
-
-
+
+ {question.prompt}
+
{
+ it("renders the approved inline marks and prompt lists", () => {
+ const { container } = render(
+
+ {"Use `code`, **bold**, *italic*, and ~~removed~~.\n\n1. First\n2. Second"}
+ ,
+ );
+
+ expect(container.querySelector("code")?.textContent).toBe("code");
+ expect(container.querySelector("strong")?.textContent).toBe("bold");
+ expect(container.querySelector("em")?.textContent).toBe("italic");
+ expect(container.querySelector("del")?.textContent).toBe("removed");
+ expect(container.querySelector("ol")?.textContent).toContain("Second");
+ });
+
+ it("unwraps block syntax in inline mode and makes links passive on request", () => {
+ const { container } = render(
+ ,
+ );
+
+ expect(container.querySelector("h1, p, ul, ol, li, a")).toBeNull();
+ expect(container.textContent).toContain("Choice");
+ expect(container.textContent).toContain("nested item");
+ });
+
+ it("does not mount unsupported rich content, raw HTML, or unsafe links", () => {
+ const { container } = render(
+
+ {
+ '# Heading\n\n> Quote\n\n```ts\nconst value = 1\n```\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n\n\nraw html\n\n[unsafe](javascript:alert(1)) [safe](https://example.com)'
+ }
+ ,
+ );
+
+ expect(container.querySelector("h1, blockquote, pre, table, img, input, mark")).toBeNull();
+ expect(container.querySelector("code")).toBeNull();
+ expect(container.textContent).toContain("const value = 1");
+ expect(container.textContent).toContain("raw html");
+ expect(container.querySelector("[data-danger]")).toBeNull();
+
+ const links = Array.from(container.querySelectorAll("a"));
+ expect(links).toHaveLength(1);
+ expect(links[0]?.textContent).toBe("safe");
+ expect(links[0]?.getAttribute("href")).toBe("https://example.com");
+ expect(links[0]?.getAttribute("target")).toBe("_blank");
+ expect(links[0]?.getAttribute("rel")).toBe("noopener noreferrer");
+ expect(container.textContent).toContain("unsafe");
+ });
+
+ it("keeps repository-relative links passive", () => {
+ const { container } = render(
+
+ {"Read [the guide](README.md)."}
+ ,
+ );
+
+ expect(container.querySelector("a")).toBeNull();
+ expect(container.textContent).toContain("the guide");
+ });
+});
diff --git a/apps/web/components/task/chat/clarification-markdown.tsx b/apps/web/components/task/chat/clarification-markdown.tsx
new file mode 100644
index 0000000000..2325d6e485
--- /dev/null
+++ b/apps/web/components/task/chat/clarification-markdown.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import ReactMarkdown, { defaultUrlTransform, type Components } from "react-markdown";
+import remarkBreaks from "remark-breaks";
+import remarkGfm from "remark-gfm";
+import { cn } from "@/lib/utils";
+
+const INLINE_ELEMENTS = ["strong", "em", "del", "code", "a", "br"];
+const BLOCK_ELEMENTS = ["p", "ul", "ol", "li", ...INLINE_ELEMENTS];
+
+type ClarificationMarkdownProps = {
+ children: string;
+ variant: "block" | "inline";
+ linkBehavior?: "interactive" | "passive";
+ className?: string;
+};
+
+function markdownComponents(linkBehavior: "interactive" | "passive"): Components {
+ return {
+ p: ({ children }) => {children}
,
+ ul: ({ children }) => (
+
+ ),
+ ol: ({ children }) => (
+
+ {children}
+
+ ),
+ li: ({ children }) => {children},
+ code: ({ children, className }) => {
+ const isBlock = className?.startsWith("language-") || String(children).includes("\n");
+ if (isBlock) return {children};
+ return (
+
+ {children}
+
+ );
+ },
+ a: ({ children, href }) => {
+ const isWebLink = href ? /^https?:\/\//i.test(href) : false;
+ if (linkBehavior === "passive" || !isWebLink) {
+ return {children};
+ }
+ return (
+
+ {children}
+
+ );
+ },
+ };
+}
+
+export function ClarificationMarkdown({
+ children,
+ variant,
+ linkBehavior = "interactive",
+ className,
+}: ClarificationMarkdownProps) {
+ const content = (
+
+ {children}
+
+ );
+
+ if (variant === "inline") {
+ return {content};
+ }
+
+ return {content}
;
+}
+
+export type { ClarificationMarkdownProps };
diff --git a/apps/web/components/task/chat/clarification-overlay-parts.tsx b/apps/web/components/task/chat/clarification-overlay-parts.tsx
index a846a371dc..7c4f8553af 100644
--- a/apps/web/components/task/chat/clarification-overlay-parts.tsx
+++ b/apps/web/components/task/chat/clarification-overlay-parts.tsx
@@ -9,6 +9,7 @@ import type { ClarificationOption } from "@/lib/types/http";
import { KeyboardShortcutTooltip } from "@/components/keyboard-shortcut-tooltip";
import { KEYS } from "@/lib/keyboard/constants";
import { useTranslation } from "react-i18next";
+import { ClarificationMarkdown } from "./clarification-markdown";
// Grow the custom-answer box up to ~6 lines, then scroll internally so the
// clarification overlay stays compact.
@@ -150,14 +151,18 @@ export function ClarificationOptions({
data-testid="clarification-option-label"
className="block leading-5 font-medium"
>
- {option.label}
+
+ {option.label}
+
{option.description && (
- {option.description}
+
+ {option.description}
+
)}
diff --git a/apps/web/components/task/chat/messages/clarification-request-message.test.tsx b/apps/web/components/task/chat/messages/clarification-request-message.test.tsx
new file mode 100644
index 0000000000..15be4c054f
--- /dev/null
+++ b/apps/web/components/task/chat/messages/clarification-request-message.test.tsx
@@ -0,0 +1,64 @@
+import { render } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import {
+ sessionId as toSessionId,
+ taskId as toTaskId,
+ type ClarificationRequestMetadata,
+ type Message,
+} from "@/lib/types/http";
+import { ClarificationRequestMessage } from "./clarification-request-message";
+
+function answeredClarification(): Message {
+ const metadata: ClarificationRequestMetadata = {
+ pending_id: "pending-1",
+ session_id: "session-1",
+ status: "answered",
+ question: {
+ id: "question-1",
+ title: "Deploy `now`",
+ prompt: "Pick **one**:\n\n- Fast\n- Careful",
+ options: [
+ {
+ option_id: "fast",
+ label: "`Fast` path",
+ description: "Best for **small** changes",
+ },
+ ],
+ },
+ response: {
+ question_id: "question-1",
+ selected_options: ["fast"],
+ custom_text: "Keep `this` **literal**",
+ },
+ };
+
+ return {
+ id: "message-1",
+ session_id: toSessionId("session-1"),
+ task_id: toTaskId("task-1"),
+ author_type: "agent",
+ content: "Question",
+ type: "clarification_request",
+ created_at: "2026-08-24T00:00:00Z",
+ metadata,
+ };
+}
+
+describe("ClarificationRequestMessage", () => {
+ it("renders agent question Markdown but keeps custom answer text literal", () => {
+ const { container } = render();
+
+ expect(Array.from(container.querySelectorAll("code"), (node) => node.textContent)).toEqual([
+ "now",
+ "Fast",
+ ]);
+ expect(container.querySelector("strong")?.textContent).toBe("one");
+ expect(container.querySelector("ul")?.textContent).toContain("Careful");
+
+ const customText = Array.from(container.querySelectorAll("span")).find(
+ (node) => node.children.length === 0 && node.textContent?.includes("Keep `this` **literal**"),
+ );
+ expect(customText).toBeDefined();
+ expect(customText?.querySelector("code, strong")).toBeNull();
+ });
+});
diff --git a/apps/web/components/task/chat/messages/clarification-request-message.tsx b/apps/web/components/task/chat/messages/clarification-request-message.tsx
index 3fea145682..d7ee23d29a 100644
--- a/apps/web/components/task/chat/messages/clarification-request-message.tsx
+++ b/apps/web/components/task/chat/messages/clarification-request-message.tsx
@@ -1,15 +1,56 @@
"use client";
-import ReactMarkdown from "react-markdown";
import { IconMessageQuestion, IconCheck, IconX } from "@tabler/icons-react";
-import { markdownComponents, remarkPlugins } from "@/components/shared/markdown-components";
-import type { Message, ClarificationRequestMetadata } from "@/lib/types/http";
+import type {
+ ClarificationAnswer,
+ ClarificationQuestion,
+ Message,
+ ClarificationRequestMetadata,
+} from "@/lib/types/http";
import { useTranslation } from "react-i18next";
+import { ClarificationMarkdown } from "../clarification-markdown";
type ClarificationRequestMessageProps = {
comment: Message;
};
+function AnswerSummary({
+ question,
+ response,
+}: {
+ question: ClarificationQuestion;
+ response: ClarificationAnswer | undefined;
+}) {
+ const { t } = useTranslation();
+ if (!response) return {t("task:clarificationNoSelection")};
+
+ const selectedOptions = (response.selected_options ?? [])
+ .map((optionId) => question.options.find((option) => option.option_id === optionId))
+ .filter((option) => option !== undefined);
+ const hasCustomText = Boolean(response.custom_text);
+
+ if (selectedOptions.length === 0 && !hasCustomText) {
+ return {t("task:clarificationNoSelection")};
+ }
+
+ return (
+
+ {selectedOptions.map((option, index) => (
+
+ {index > 0 ? ", " : null}
+ {option.label}
+
+ ))}
+ {response.custom_text && (
+
+ {selectedOptions.length > 0 ? ", " : null}
+ {`"${response.custom_text}"`}
+
+ )}
+
+ );
+}
+
/**
* Displays a resolved or superseded clarification request in the chat history.
* The active pending clarification is shown in the input area instead.
@@ -42,33 +83,8 @@ export function ClarificationRequestMessage({ comment }: ClarificationRequestMes
return null;
};
- // Get the answer summary for display
- const getAnswerSummary = () => {
- const response = metadata.response;
- if (!response) return t("task:clarificationNoSelection");
-
- const parts: string[] = [];
-
- // Get selected option labels
- if (response.selected_options?.length) {
- for (const optionId of response.selected_options) {
- const option = question.options.find((o) => o.option_id === optionId);
- if (option) {
- parts.push(option.label);
- }
- }
- }
-
- // Add custom text
- if (response.custom_text) {
- parts.push(`"${response.custom_text}"`);
- }
-
- return parts.length > 0 ? parts.join(", ") : t("task:clarificationNoSelection");
- };
-
return (
-
+
{/* Icon */}
@@ -78,18 +94,26 @@ export function ClarificationRequestMessage({ comment }: ClarificationRequestMes
{/* Content */}
{/* Question */}
-
-
- {question.prompt}
-
-
+ {question.title && (
+
+ {question.title}
+
+ )}
+
+ {question.prompt}
+
{/* Answer - indented below question */}
{isAnswered && (
{getStatusIndicator()}
- {/* pre-wrap preserves newlines from multiline custom answers. */}
-
{getAnswerSummary()}
+
{metadata.agent_disconnected && (
{t("task:sentAsNewMessage")}
)}
diff --git a/apps/web/components/task/chat/messages/kandev-tool-message.test.tsx b/apps/web/components/task/chat/messages/kandev-tool-message.test.tsx
index fd941a7ef2..eca8f73bed 100644
--- a/apps/web/components/task/chat/messages/kandev-tool-message.test.tsx
+++ b/apps/web/components/task/chat/messages/kandev-tool-message.test.tsx
@@ -373,7 +373,9 @@ describe("KandevToolMessage document & question renderers", () => {
);
expect(html).toContain("Pick one");
// Selected option gets the "default" Badge variant; unselected stays "outline".
- expect(html).toMatch(/data-variant="default"[^>]*>A<\/span>/);
+ const root = document.createElement("div");
+ root.innerHTML = html;
+ expect(root.querySelector('[data-variant="default"]')?.textContent).toBe("A");
});
it("does not render anything when the renderer is missing", () => {
diff --git a/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.test.tsx b/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.test.tsx
new file mode 100644
index 0000000000..9440326071
--- /dev/null
+++ b/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.test.tsx
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+import { AskUserQuestionRenderer } from "./ask-user-question-renderer";
+
+describe("AskUserQuestionRenderer", () => {
+ it("renders lightweight Markdown in every expanded clarification field", () => {
+ const html = renderToStaticMarkup(
+
,
+ );
+
+ expect(html).toContain("
storage");
+ expect(html).toContain("
one");
+ expect(html).toContain("
Postgres");
+ expect(html).toContain("production");
+ expect(html).toContain("local");
+ expect(html).toContain("Keep `context` literal");
+ expect(html).not.toContain(">context");
+ expect(html).not.toContain('title="For **production**"');
+ });
+
+ it("keeps summary links passive while expanded prompt links stay interactive", () => {
+ const html = renderToStaticMarkup(
+ ,
+ );
+ const root = document.createElement("div");
+ root.innerHTML = html;
+ const header = root.querySelector(".cursor-pointer");
+ const expandedBody = root.querySelector(".mt-2.ml-7");
+
+ expect(header?.querySelector('a[href="https://example.com/storage"]')).toBeNull();
+ expect(expandedBody?.querySelectorAll('a[href="https://example.com/storage"]')).toHaveLength(1);
+ });
+});
diff --git a/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.tsx b/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.tsx
index 1c7f6760bf..107b2d8cbd 100644
--- a/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.tsx
+++ b/apps/web/components/task/chat/messages/kandev/ask-user-question-renderer.tsx
@@ -6,10 +6,12 @@ import { EmptyListNote, KandevBody, KandevRow, KeyValueRow, SummaryDot } from ".
import { pickArray, pickString, shortId } from "./parse";
import type { KandevRenderer } from "./types";
import { useTranslation } from "react-i18next";
+import { ClarificationMarkdown } from "../../clarification-markdown";
type QuestionOption = { label?: string; description?: string };
type Question = {
id?: string;
+ title?: string;
prompt?: string;
options?: QuestionOption[];
};
@@ -23,20 +25,42 @@ function QuestionBlock({ q, answer }: { q: Question; answer: AnswerEntry | undef
const { t } = useTranslation();
return (
- {q.prompt &&
{q.prompt}
}
+ {q.title && (
+
+ {q.title}
+
+ )}
+ {q.prompt && (
+
+ {q.prompt}
+
+ )}
{q.options && q.options.length > 0 && (
-
+
{q.options.map((opt, i) => {
const isSelected = answer?.selected === opt.label;
return (
-
- {opt.label ?? t("task:option", { index: i + 1 })}
-
+
+
+
+ {opt.label ?? t("task:option", { index: i + 1 })}
+
+
+ {opt.description && (
+
+ {opt.description}
+
+ )}
+
);
})}
@@ -86,48 +110,56 @@ export const AskUserQuestionRenderer: KandevRenderer = ({ args, result, status }
const promptShort = firstPrompt ? firstPrompt.replace(/\s+/g, " ").trim() : undefined;
return (
-
- {t("task:questionCount", { count: questions.length })}
- {promptShort && (
- <>
-
- “{promptShort}”
- >
+
+
+ {t("task:questionCount", { count: questions.length })}
+ {promptShort && (
+ <>
+
+
+ “
+
+ {promptShort}
+
+ ”
+
+ >
+ )}
+
+ }
+ status={status}
+ hasExpandableContent={questions.length > 0 || !!context}
+ >
+
+ {context && (
+
+ {context}
+
)}
-
- }
- status={status}
- hasExpandableContent={questions.length > 0 || !!context}
- >
-
- {context && (
-
- {context}
-
- )}
- {questions.length === 0 ? (
-
- ) : (
-
- {questions.map((q, i) => (
-
- ))}
-
- )}
- {pendingId && status === "running" && (
-
- {t("task:awaitingUserResponse", { pendingId: shortId(pendingId) })}
-
- )}
-
-
+ {questions.length === 0 ? (
+
+ ) : (
+
+ {questions.map((q, i) => (
+
+ ))}
+
+ )}
+ {pendingId && status === "running" && (
+
+ {t("task:awaitingUserResponse", { pendingId: shortId(pendingId) })}
+
+ )}
+
+
+
);
};
diff --git a/apps/web/e2e/helpers/clarification.ts b/apps/web/e2e/helpers/clarification.ts
index 6e4a8920b6..910f670aff 100644
--- a/apps/web/e2e/helpers/clarification.ts
+++ b/apps/web/e2e/helpers/clarification.ts
@@ -16,10 +16,10 @@ type SeedOptions = {
};
/**
- * Create a task + session running a mock-agent scenario, navigate to it, and
- * return a ready SessionPage. Shared by the clarification specs (overlay,
- * resize, and mobile) so the seed → navigate → waitForLoad flow lives in one
- * place.
+ * Create a task + session running a mock-agent scenario, wait for blocking
+ * scenarios to reach their causal backend state, navigate to it, and return a
+ * ready SessionPage. Shared by the clarification specs (overlay, resize, and
+ * mobile) so the seed → wait → navigate → waitForLoad flow lives in one place.
*/
export async function seedClarificationSession(
testPage: Page,
@@ -47,7 +47,7 @@ export async function seedClarificationSession(
taskId: task.id,
sessionId: task.session_id,
expectedState: "WAITING_FOR_INPUT",
- message: "clarification session should be waiting for input before navigation",
+ message: "clarification session should reach its blocking state before navigation",
timeout: 60_000,
});
}
diff --git a/apps/web/e2e/tests/chat/clarification.spec.ts b/apps/web/e2e/tests/chat/clarification.spec.ts
index 220271d4f2..5ab21013df 100644
--- a/apps/web/e2e/tests/chat/clarification.spec.ts
+++ b/apps/web/e2e/tests/chat/clarification.spec.ts
@@ -24,6 +24,26 @@ function seedClarificationTask(
return seedClarificationSession(testPage, apiClient, seedData, title, { scenario });
}
+async function waitForPendingClarificationMessages(
+ apiClient: ApiClient,
+ sessionId: string,
+ expectedCount: number,
+ message: string,
+): Promise {
+ await expect
+ .poll(
+ async () => {
+ const { messages } = await apiClient.listSessionMessages(sessionId);
+ return messages.filter(
+ (candidate) =>
+ candidate.type === "clarification_request" && candidate.metadata?.status === "pending",
+ ).length;
+ },
+ { message, timeout: 60_000 },
+ )
+ .toBe(expectedCount);
+}
+
const PLAN_WITH_CLARIFICATION_SCRIPT = [
'e2e:mcp:kandev:create_task_plan_kandev({"task_id":"{task_id}","content":"## Plan\\n\\nEdit 1 item","title":"Implementation Plan"})',
"e2e:delay(100)",
@@ -171,6 +191,13 @@ test.describe("Clarification flow", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
+ await waitForPendingClarificationMessages(
+ apiClient,
+ task.session_id,
+ 1,
+ "custom clarification should be durably pending before navigation",
+ );
+
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
@@ -305,6 +332,14 @@ test.describe("Clarification flow", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
+ await waitForSessionState(apiClient, {
+ taskId: task.id,
+ sessionId: task.session_id,
+ expectedState: "WAITING_FOR_INPUT",
+ message: "timed-out clarification should be ready for a deferred answer before navigation",
+ timeout: 60_000,
+ });
+
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
@@ -322,14 +357,6 @@ test.describe("Clarification flow", () => {
})
.toBe(timeoutStep.id);
- await waitForSessionState(apiClient, {
- taskId: task.id,
- sessionId: task.session_id,
- expectedState: "WAITING_FOR_INPUT",
- message: "timed-out clarification session must remain ready for a deferred answer",
- timeout: 30_000,
- });
-
// Agent moved on; a late custom answer remains editable and goes through
// the event fallback as a new prompt.
const input = session.clarificationInput();
@@ -389,6 +416,14 @@ test.describe("Clarification flow", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
+ await waitForSessionState(apiClient, {
+ taskId: task.id,
+ sessionId: task.session_id,
+ expectedState: "WAITING_FOR_INPUT",
+ message: "timed-out clarification should be ready for a deferred answer before navigation",
+ timeout: 60_000,
+ });
+
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
@@ -398,14 +433,6 @@ test.describe("Clarification flow", () => {
await expect(session.chat).toContainText("Question timed out", { timeout: 30_000 });
await expect(session.clarificationDeferredNotice()).toBeVisible({ timeout: 10_000 });
- await waitForSessionState(apiClient, {
- taskId: task.id,
- sessionId: task.session_id,
- expectedState: "WAITING_FOR_INPUT",
- message: "timed-out clarification session must remain ready for a deferred answer",
- timeout: 30_000,
- });
-
let respondCalls = 0;
await testPage.route("**/api/v1/clarification/*/respond", async (route) => {
respondCalls += 1;
@@ -469,6 +496,54 @@ test.describe("Clarification flow", () => {
expect(descriptionBox.y).toBeGreaterThanOrEqual(labelBox.y + labelBox.height - 1);
});
+ test("renders lightweight markdown across active and resolved clarification text", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const session = await seedClarificationTask(
+ testPage,
+ apiClient,
+ seedData,
+ "Clarification Markdown",
+ "clarification-markdown",
+ );
+
+ const overlay = session.clarificationOverlay();
+ await expect(overlay).toBeVisible();
+ const card = session.clarificationQuestionCardById("markdown");
+ const firstOption = session.clarificationOption("Postgres");
+
+ await expect(card.getByTestId("clarification-question-title").locator("code")).toHaveText("DB");
+ await expect(card.locator("strong").filter({ hasText: "one" })).toBeVisible();
+ await expect(card.locator("ol > li")).toHaveCount(2);
+ const guidance = card.getByRole("link", { name: "storage guidance" });
+ await expect(guidance).toHaveAttribute("href", "https://example.com/storage");
+ await expect(guidance).toHaveAttribute("rel", "noopener noreferrer");
+
+ await expect(firstOption.getByTestId("clarification-option-label").locator("code")).toHaveText(
+ "Postgres",
+ );
+ await expect(
+ firstOption.getByTestId("clarification-option-description").locator("strong"),
+ ).toHaveText("production");
+ await expect(firstOption.locator("a")).toHaveCount(0);
+
+ const context = session.clarificationContext();
+ await expect(context).toContainText("Keep `context` literal.");
+ await expect(context.locator("code")).toHaveCount(0);
+
+ await firstOption.locator("code").click();
+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
+
+ const resolved = session.activeChat().getByTestId("clarification-request-message");
+ await expect(resolved).toBeVisible();
+ await expect(resolved.locator("code").filter({ hasText: "DB" })).toBeVisible();
+ await expect(resolved.locator("strong").filter({ hasText: "one" })).toBeVisible();
+ await expect(resolved.locator("ol > li")).toHaveCount(2);
+ await expect(resolved.locator("code").filter({ hasText: "Postgres" })).toBeVisible();
+ });
+
test("plan mode + clarification does not leave pointer-events stuck on body", async ({
testPage,
}) => {
@@ -852,6 +927,13 @@ test.describe("Multi-question clarification carousel", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
+ await waitForPendingClarificationMessages(
+ apiClient,
+ task.session_id,
+ 3,
+ "plan clarification bundle should be durably pending before navigation",
+ );
+
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
@@ -1023,6 +1105,14 @@ test.describe("Multi-question clarification carousel", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
+ await waitForSessionState(apiClient, {
+ taskId: task.id,
+ sessionId: task.session_id,
+ expectedState: "WAITING_FOR_INPUT",
+ message: "multi-question clarification should block the agent before navigation",
+ timeout: 60_000,
+ });
+
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
diff --git a/apps/web/e2e/tests/chat/mobile-clarification.spec.ts b/apps/web/e2e/tests/chat/mobile-clarification.spec.ts
index 986c594464..14d715707a 100644
--- a/apps/web/e2e/tests/chat/mobile-clarification.spec.ts
+++ b/apps/web/e2e/tests/chat/mobile-clarification.spec.ts
@@ -175,6 +175,63 @@ test.describe("Mobile clarification multiline answer", () => {
await expect(context).toHaveCount(1);
});
+ test("renders lightweight markdown without overflow and submits through formatted content", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const session = await seedClarificationSession(
+ testPage,
+ apiClient,
+ seedData,
+ "Mobile Clarification Markdown",
+ { scenario: "clarification-markdown" },
+ );
+
+ const overlay = session.clarificationOverlay();
+ await expect(overlay).toBeVisible();
+ const card = session.clarificationQuestionCardById("markdown");
+ const option = session.clarificationOption("Postgres");
+
+ await expect(card.getByTestId("clarification-question-title").locator("code")).toHaveText("DB");
+ await expect(card.locator("ol > li")).toHaveCount(2);
+ await expect(
+ option.getByTestId("clarification-option-description").locator("strong"),
+ ).toHaveText("production");
+ await expect(option.locator("a")).toHaveCount(0);
+
+ await option.scrollIntoViewIfNeeded();
+ const [optionBox, overlayBox] = await Promise.all([
+ option.boundingBox(),
+ overlay.boundingBox(),
+ ]);
+ if (!optionBox || !overlayBox) {
+ throw new Error("expected formatted mobile option and overlay to have bounding boxes");
+ }
+ expect(optionBox.x).toBeGreaterThanOrEqual(overlayBox.x - 1);
+ expect(optionBox.x + optionBox.width).toBeLessThanOrEqual(overlayBox.x + overlayBox.width + 1);
+ await expect(
+ testPage.evaluate(
+ () => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
+ ),
+ ).resolves.toBe(true);
+
+ await option.locator("code").tap();
+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
+ await expect(
+ session
+ .activeChat()
+ .getByTestId("clarification-request-message")
+ .locator("code")
+ .filter({ hasText: "Postgres" }),
+ ).toBeVisible();
+ await expect(
+ testPage.evaluate(
+ () => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
+ ),
+ ).resolves.toBe(true);
+ });
+
test("separates batch actions from the stepper while showing submission feedback", async ({
testPage,
apiClient,