feat(web): render lightweight markdown in clarifications (#3033)
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
</span>
|
||||
)}
|
||||
{metadata.question.title && (
|
||||
<span className="text-muted-foreground/70">
|
||||
<span data-testid="clarification-question-title" className="text-muted-foreground/70">
|
||||
{total > 1 ? "· " : ""}
|
||||
{metadata.question.title}
|
||||
<ClarificationMarkdown variant="inline">
|
||||
{metadata.question.title}
|
||||
</ClarificationMarkdown>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="markdown-body max-w-none text-sm font-medium [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 mb-3">
|
||||
<ReactMarkdown remarkPlugins={remarkPlugins} components={markdownComponents}>
|
||||
{question.prompt}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
<ClarificationMarkdown
|
||||
variant="block"
|
||||
className="mb-3 max-w-none text-sm font-medium [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
|
||||
>
|
||||
{question.prompt}
|
||||
</ClarificationMarkdown>
|
||||
<ClarificationOptions
|
||||
options={question.options}
|
||||
selectedOption={selectedOption}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ClarificationMarkdown } from "./clarification-markdown";
|
||||
|
||||
describe("ClarificationMarkdown", () => {
|
||||
it("renders the approved inline marks and prompt lists", () => {
|
||||
const { container } = render(
|
||||
<ClarificationMarkdown variant="block">
|
||||
{"Use `code`, **bold**, *italic*, and ~~removed~~.\n\n1. First\n2. Second"}
|
||||
</ClarificationMarkdown>,
|
||||
);
|
||||
|
||||
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(
|
||||
<button type="button">
|
||||
<ClarificationMarkdown variant="inline" linkBehavior="passive">
|
||||
{"# [Choice](https://example.com)\n\n- nested item"}
|
||||
</ClarificationMarkdown>
|
||||
</button>,
|
||||
);
|
||||
|
||||
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(
|
||||
<ClarificationMarkdown variant="block">
|
||||
{
|
||||
'# Heading\n\n> Quote\n\n```ts\nconst value = 1\n```\n\n| A | B |\n| - | - |\n| 1 | 2 |\n\n\n\n<mark data-danger="true">raw html</mark>\n\n[unsafe](javascript:alert(1)) [safe](https://example.com)'
|
||||
}
|
||||
</ClarificationMarkdown>,
|
||||
);
|
||||
|
||||
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(
|
||||
<ClarificationMarkdown variant="inline">
|
||||
{"Read [the guide](README.md)."}
|
||||
</ClarificationMarkdown>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("a")).toBeNull();
|
||||
expect(container.textContent).toContain("the guide");
|
||||
});
|
||||
});
|
||||
@@ -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 }) => <p className="leading-relaxed [&+p]:mt-2">{children}</p>,
|
||||
ul: ({ children }) => (
|
||||
<ul className="my-2 list-disc space-y-0.5 pl-5 marker:text-muted-foreground">{children}</ul>
|
||||
),
|
||||
ol: ({ children }) => (
|
||||
<ol className="my-2 list-decimal space-y-0.5 pl-5 marker:text-muted-foreground">
|
||||
{children}
|
||||
</ol>
|
||||
),
|
||||
li: ({ children }) => <li className="pl-0.5 leading-relaxed">{children}</li>,
|
||||
code: ({ children, className }) => {
|
||||
const isBlock = className?.startsWith("language-") || String(children).includes("\n");
|
||||
if (isBlock) return <span className="whitespace-pre-wrap">{children}</span>;
|
||||
return (
|
||||
<code className="whitespace-pre-wrap break-words rounded border border-foreground/10 bg-muted px-1 py-0.5 font-mono text-[0.9em] text-foreground">
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
},
|
||||
a: ({ children, href }) => {
|
||||
const isWebLink = href ? /^https?:\/\//i.test(href) : false;
|
||||
if (linkBehavior === "passive" || !isWebLink) {
|
||||
return <span className="text-primary underline underline-offset-2">{children}</span>;
|
||||
}
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="break-words text-primary underline underline-offset-2"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function ClarificationMarkdown({
|
||||
children,
|
||||
variant,
|
||||
linkBehavior = "interactive",
|
||||
className,
|
||||
}: ClarificationMarkdownProps) {
|
||||
const content = (
|
||||
<ReactMarkdown
|
||||
allowedElements={variant === "block" ? BLOCK_ELEMENTS : INLINE_ELEMENTS}
|
||||
components={markdownComponents(linkBehavior)}
|
||||
remarkPlugins={[remarkGfm, remarkBreaks]}
|
||||
skipHtml
|
||||
unwrapDisallowed
|
||||
urlTransform={defaultUrlTransform}
|
||||
>
|
||||
{children}
|
||||
</ReactMarkdown>
|
||||
);
|
||||
|
||||
if (variant === "inline") {
|
||||
return <span className={cn("min-w-0 [overflow-wrap:anywhere]", className)}>{content}</span>;
|
||||
}
|
||||
|
||||
return <div className={cn("min-w-0 [overflow-wrap:anywhere]", className)}>{content}</div>;
|
||||
}
|
||||
|
||||
export type { ClarificationMarkdownProps };
|
||||
@@ -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}
|
||||
<ClarificationMarkdown variant="inline" linkBehavior="passive">
|
||||
{option.label}
|
||||
</ClarificationMarkdown>
|
||||
</span>
|
||||
{option.description && (
|
||||
<span
|
||||
data-testid="clarification-option-description"
|
||||
className="block text-muted-foreground/80 mt-0.5 text-xs leading-snug"
|
||||
>
|
||||
{option.description}
|
||||
<ClarificationMarkdown variant="inline" linkBehavior="passive">
|
||||
{option.description}
|
||||
</ClarificationMarkdown>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -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(<ClarificationRequestMessage comment={answeredClarification()} />);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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 <span>{t("task:clarificationNoSelection")}</span>;
|
||||
|
||||
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 <span>{t("task:clarificationNoSelection")}</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="min-w-0">
|
||||
{selectedOptions.map((option, index) => (
|
||||
<span key={option.option_id}>
|
||||
{index > 0 ? ", " : null}
|
||||
<ClarificationMarkdown variant="inline">{option.label}</ClarificationMarkdown>
|
||||
</span>
|
||||
))}
|
||||
{response.custom_text && (
|
||||
<span className="whitespace-pre-wrap">
|
||||
{selectedOptions.length > 0 ? ", " : null}
|
||||
{`"${response.custom_text}"`}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (
|
||||
<div className="w-full">
|
||||
<div className="w-full" data-testid="clarification-request-message">
|
||||
<div className="flex items-start gap-3 w-full">
|
||||
{/* Icon */}
|
||||
<div className="flex-shrink-0 mt-0.5">
|
||||
@@ -78,18 +94,26 @@ export function ClarificationRequestMessage({ comment }: ClarificationRequestMes
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Question */}
|
||||
<div className="markdown-body max-w-none text-xs text-muted-foreground [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
|
||||
<ReactMarkdown remarkPlugins={remarkPlugins} components={markdownComponents}>
|
||||
{question.prompt}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
{question.title && (
|
||||
<ClarificationMarkdown
|
||||
variant="inline"
|
||||
className="mb-0.5 text-xs font-medium text-foreground/80"
|
||||
>
|
||||
{question.title}
|
||||
</ClarificationMarkdown>
|
||||
)}
|
||||
<ClarificationMarkdown
|
||||
variant="block"
|
||||
className="max-w-none text-xs text-muted-foreground [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
|
||||
>
|
||||
{question.prompt}
|
||||
</ClarificationMarkdown>
|
||||
|
||||
{/* Answer - indented below question */}
|
||||
{isAnswered && (
|
||||
<div className="mt-1 ml-3 flex items-start gap-1.5 text-xs text-foreground/80">
|
||||
{getStatusIndicator()}
|
||||
{/* pre-wrap preserves newlines from multiline custom answers. */}
|
||||
<span className="whitespace-pre-wrap">{getAnswerSummary()}</span>
|
||||
<AnswerSummary question={question} response={metadata.response} />
|
||||
{metadata.agent_disconnected && (
|
||||
<span className="text-muted-foreground">{t("task:sentAsNewMessage")}</span>
|
||||
)}
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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(
|
||||
<AskUserQuestionRenderer
|
||||
status="running"
|
||||
args={{
|
||||
context: "Keep `context` literal",
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
title: "Choose `storage`",
|
||||
prompt: "Pick **one**:\n\n1. Fast\n2. Durable",
|
||||
options: [
|
||||
{ label: "`Postgres`", description: "For **production**" },
|
||||
{ label: "SQLite", description: "For *local* work" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}}
|
||||
result={{ responses: { q1: { question_id: "q1", selected: "`Postgres`" } } }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("<code");
|
||||
expect(html).toContain(">storage</code>");
|
||||
expect(html).toContain("<strong>one</strong>");
|
||||
expect(html).toContain("<ol");
|
||||
expect(html).toContain(">Postgres</code>");
|
||||
expect(html).toContain("<strong>production</strong>");
|
||||
expect(html).toContain("<em>local</em>");
|
||||
expect(html).toContain("Keep `context` literal");
|
||||
expect(html).not.toContain(">context</code>");
|
||||
expect(html).not.toContain('title="For **production**"');
|
||||
});
|
||||
|
||||
it("keeps summary links passive while expanded prompt links stay interactive", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<AskUserQuestionRenderer
|
||||
status="running"
|
||||
args={{
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
prompt: "Read the [storage guide](https://example.com/storage).",
|
||||
options: [],
|
||||
},
|
||||
],
|
||||
}}
|
||||
result={{}}
|
||||
/>,
|
||||
);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<div className="space-y-1.5">
|
||||
{q.prompt && <div className="text-xs text-foreground whitespace-pre-wrap">{q.prompt}</div>}
|
||||
{q.title && (
|
||||
<ClarificationMarkdown
|
||||
variant="inline"
|
||||
className="text-[11px] font-medium text-muted-foreground"
|
||||
>
|
||||
{q.title}
|
||||
</ClarificationMarkdown>
|
||||
)}
|
||||
{q.prompt && (
|
||||
<ClarificationMarkdown variant="block" className="text-xs text-foreground">
|
||||
{q.prompt}
|
||||
</ClarificationMarkdown>
|
||||
)}
|
||||
{q.options && q.options.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<div className="space-y-1">
|
||||
{q.options.map((opt, i) => {
|
||||
const isSelected = answer?.selected === opt.label;
|
||||
return (
|
||||
<Badge
|
||||
key={`${opt.label ?? i}`}
|
||||
variant={isSelected ? "default" : "outline"}
|
||||
className="text-[10px]"
|
||||
title={opt.description}
|
||||
>
|
||||
{opt.label ?? t("task:option", { index: i + 1 })}
|
||||
</Badge>
|
||||
<div key={`${opt.label ?? i}`} className="flex min-w-0 items-start gap-2">
|
||||
<Badge
|
||||
variant={isSelected ? "default" : "outline"}
|
||||
className="h-auto min-h-5 max-w-full shrink whitespace-normal overflow-visible text-left text-[10px] leading-tight"
|
||||
>
|
||||
<ClarificationMarkdown variant="inline">
|
||||
{opt.label ?? t("task:option", { index: i + 1 })}
|
||||
</ClarificationMarkdown>
|
||||
</Badge>
|
||||
{opt.description && (
|
||||
<ClarificationMarkdown
|
||||
variant="inline"
|
||||
className="min-w-0 flex-1 text-[10px] leading-relaxed text-muted-foreground"
|
||||
>
|
||||
{opt.description}
|
||||
</ClarificationMarkdown>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -86,48 +110,56 @@ export const AskUserQuestionRenderer: KandevRenderer = ({ args, result, status }
|
||||
const promptShort = firstPrompt ? firstPrompt.replace(/\s+/g, " ").trim() : undefined;
|
||||
|
||||
return (
|
||||
<KandevRow
|
||||
Icon={IconHelpHexagon}
|
||||
title={t("task:kandevAskUserQuestion")}
|
||||
summary={
|
||||
<span className="inline-flex items-center gap-1.5 min-w-0">
|
||||
<span>{t("task:questionCount", { count: questions.length })}</span>
|
||||
{promptShort && (
|
||||
<>
|
||||
<SummaryDot />
|
||||
<span className="truncate max-w-[50ch]">“{promptShort}”</span>
|
||||
</>
|
||||
<div data-testid="ask-user-question-renderer">
|
||||
<KandevRow
|
||||
Icon={IconHelpHexagon}
|
||||
title={t("task:kandevAskUserQuestion")}
|
||||
summary={
|
||||
<span className="inline-flex items-center gap-1.5 min-w-0">
|
||||
<span>{t("task:questionCount", { count: questions.length })}</span>
|
||||
{promptShort && (
|
||||
<>
|
||||
<SummaryDot />
|
||||
<span className="truncate max-w-[50ch]">
|
||||
“
|
||||
<ClarificationMarkdown variant="inline" linkBehavior="passive" className="inline">
|
||||
{promptShort}
|
||||
</ClarificationMarkdown>
|
||||
”
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
status={status}
|
||||
hasExpandableContent={questions.length > 0 || !!context}
|
||||
>
|
||||
<KandevBody>
|
||||
{context && (
|
||||
<KeyValueRow label={t("task:contextFieldLabel")}>
|
||||
<span className="whitespace-pre-wrap">{context}</span>
|
||||
</KeyValueRow>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
status={status}
|
||||
hasExpandableContent={questions.length > 0 || !!context}
|
||||
>
|
||||
<KandevBody>
|
||||
{context && (
|
||||
<KeyValueRow label={t("task:contextFieldLabel")}>
|
||||
<span className="whitespace-pre-wrap">{context}</span>
|
||||
</KeyValueRow>
|
||||
)}
|
||||
{questions.length === 0 ? (
|
||||
<EmptyListNote messageKey="task:noQuestionsFound" />
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{questions.map((q, i) => (
|
||||
<QuestionBlock
|
||||
key={q.id ?? i}
|
||||
q={q}
|
||||
answer={matchAnswerForQuestion(responses, q, i)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pendingId && status === "running" && (
|
||||
<div className="text-[10px] italic text-muted-foreground/70">
|
||||
{t("task:awaitingUserResponse", { pendingId: shortId(pendingId) })}
|
||||
</div>
|
||||
)}
|
||||
</KandevBody>
|
||||
</KandevRow>
|
||||
{questions.length === 0 ? (
|
||||
<EmptyListNote messageKey="task:noQuestionsFound" />
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{questions.map((q, i) => (
|
||||
<QuestionBlock
|
||||
key={q.id ?? i}
|
||||
q={q}
|
||||
answer={matchAnswerForQuestion(responses, q, i)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pendingId && status === "running" && (
|
||||
<div className="text-[10px] italic text-muted-foreground/70">
|
||||
{t("task:awaitingUserResponse", { pendingId: shortId(pendingId) })}
|
||||
</div>
|
||||
)}
|
||||
</KandevBody>
|
||||
</KandevRow>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user