feat(web): clearer custom-answer state and Cmd+Enter submit on clarifications (#934)
* feat(web): add clearAnswer + submit re-entry guard to useClarificationGroup clearAnswer removes a stored answer so emptying a clarification draft can revert the stepper to "unanswered". A small inflight ref in submitCollected / skipAll prevents duplicate POSTs when multiple submit paths race (e.g. Cmd+Enter inside the custom input commits the draft and also asks the parent to finalize the batch). * feat(web): show selected state and Cmd+Enter submit on clarification custom input The "Or type a custom answer…" input previously had no selected styling and needed an Enter keypress before the carousel stepper marked the question as answered, which made it easy to lose track of which path was the active answer. Now: - Typing into the custom input live-records the draft, so the stepper and group progress update immediately and the input picks up the same blue ring + check icon used by selected options. When custom is active, any previously picked option visually deselects (they are mutually exclusive at commit time). - Picking an option after typing wipes that question's draft so the visible input and committed answer stay in sync. - Cmd/Ctrl+Enter submits the bundle when every question is answered — from inside the custom input (commits the draft then finalises) and from anywhere else in the overlay. Inside the input is handled locally so submitCollected does not fire twice. * test(web): cover live-record + Cmd+Enter clarification UX Adds four cases over the existing clarification-multi mock scenario: typing auto-selects custom and deselects the option, emptying the draft reverts the stepper, Cmd+Enter from the last-step custom input submits the bundle, and Cmd+Enter from outside the input submits when all answered. Adds a session-page locator for the new custom-input container so the data-active attribute can be asserted. * fix(web): address bot review feedback on clarification UX - Cmd/Ctrl+Enter inside the custom-text input no longer calls the per-question commit path. The draft is already live-recorded via onChange, so calling onSubmit here only added a stale advance-to-next step before the bundle was submitted. Now Cmd+Enter just finalises. - handleSubmit depends on group.submitCollected (which the hook memoises) rather than the whole group object, so it no longer re-creates on every keystroke through the live-record path. - Add a unit test that fires submitCollected twice concurrently and asserts the inflight ref keeps the wire count at 1 — direct coverage for the guard introduced in the previous commit instead of relying on the 409 round-trip test.
This commit is contained in:
@@ -59,11 +59,13 @@ type CardProps = {
|
||||
selectedOption: string | null;
|
||||
customCommittedText: string | null;
|
||||
customDraft: string;
|
||||
customActive: boolean;
|
||||
isSubmitting: boolean;
|
||||
showAgentDisconnected: boolean;
|
||||
onSelectOption: (optionId: string) => void;
|
||||
onCustomDraftChange: (text: string) => void;
|
||||
onSubmitCustom: (text: string) => void;
|
||||
onRequestFinalSubmit: () => void;
|
||||
};
|
||||
|
||||
function ClarificationCard(props: CardProps) {
|
||||
@@ -74,11 +76,13 @@ function ClarificationCard(props: CardProps) {
|
||||
selectedOption,
|
||||
customCommittedText,
|
||||
customDraft,
|
||||
customActive,
|
||||
isSubmitting,
|
||||
showAgentDisconnected,
|
||||
onSelectOption,
|
||||
onCustomDraftChange,
|
||||
onSubmitCustom,
|
||||
onRequestFinalSubmit,
|
||||
} = props;
|
||||
const { question, metadata } = meta;
|
||||
return (
|
||||
@@ -111,6 +115,7 @@ function ClarificationCard(props: CardProps) {
|
||||
options={question.options}
|
||||
selectedOption={selectedOption}
|
||||
isSubmitting={isSubmitting}
|
||||
customActive={customActive}
|
||||
onSelectOption={onSelectOption}
|
||||
/>
|
||||
{showAgentDisconnected && (
|
||||
@@ -126,8 +131,10 @@ function ClarificationCard(props: CardProps) {
|
||||
draft={customDraft}
|
||||
isSubmitting={isSubmitting}
|
||||
committedText={customCommittedText}
|
||||
active={customActive}
|
||||
onChange={onCustomDraftChange}
|
||||
onSubmit={onSubmitCustom}
|
||||
onRequestFinalSubmit={onRequestFinalSubmit}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -172,12 +179,29 @@ function shouldIgnoreShortcut(e: KeyboardEvent): boolean {
|
||||
return e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;
|
||||
}
|
||||
|
||||
// tryHandleMetaEnter returns true when the event was Cmd/Ctrl+Enter, so the
|
||||
// caller can short-circuit. When focus is inside the custom-text input it
|
||||
// returns true *without* invoking onSubmit — the input's own keydown handler
|
||||
// owns that path and is responsible for committing the draft + final submit.
|
||||
function tryHandleMetaEnter(e: KeyboardEvent, canSubmit: boolean, onSubmit: () => void): boolean {
|
||||
if (e.key !== "Enter" || e.shiftKey || e.altKey) return false;
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const inEditable =
|
||||
e.target instanceof HTMLElement &&
|
||||
(e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA");
|
||||
if (inEditable) return true;
|
||||
e.preventDefault();
|
||||
if (canSubmit) onSubmit();
|
||||
return true;
|
||||
}
|
||||
|
||||
function CarouselKeyboardShortcuts(args: CarouselShortcutArgs) {
|
||||
const optionsCount = args.meta.question.options.length;
|
||||
const isLast = args.activeIndex === args.total - 1;
|
||||
const { canSubmit, onPick, onPrev, onNext, onSkip, onSubmit } = args;
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (tryHandleMetaEnter(e, canSubmit, onSubmit)) return;
|
||||
if (shouldIgnoreShortcut(e)) return;
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
@@ -216,6 +240,98 @@ type CarouselBodyProps = {
|
||||
setCustomDrafts: React.Dispatch<React.SetStateAction<Record<string, string>>>;
|
||||
};
|
||||
|
||||
type QuestionHandlerCtx = {
|
||||
meta: SingleQuestionMeta;
|
||||
group: ReturnType<typeof useClarificationGroup>;
|
||||
isSingleQuestion: boolean;
|
||||
activeIndex: number;
|
||||
total: number;
|
||||
setActiveIndex: (idx: number) => void;
|
||||
setCustomDrafts: React.Dispatch<React.SetStateAction<Record<string, string>>>;
|
||||
};
|
||||
|
||||
type QuestionHandlers = {
|
||||
onSelectOption: (optionId: string) => void;
|
||||
onCustomDraftChange: (value: string) => void;
|
||||
onSubmitCustom: (text: string) => void;
|
||||
};
|
||||
|
||||
type SelectionState = {
|
||||
selectedOption: string | null;
|
||||
customCommittedText: string | null;
|
||||
draft: string;
|
||||
customActive: boolean;
|
||||
};
|
||||
|
||||
function deriveSelectionState(
|
||||
meta: SingleQuestionMeta,
|
||||
answers: Record<string, ClarificationAnswer>,
|
||||
customDrafts: Record<string, string>,
|
||||
): SelectionState {
|
||||
const stored = answers[meta.questionId];
|
||||
const selected = stored?.selected_options ?? [];
|
||||
const selectedOption = selected.length > 0 ? selected[0] : null;
|
||||
const customCommittedText = stored?.custom_text ?? null;
|
||||
const draft = customDrafts[meta.questionId] ?? "";
|
||||
const hasCustomText = draft.trim().length > 0 || (customCommittedText?.length ?? 0) > 0;
|
||||
const customActive = !selectedOption && hasCustomText;
|
||||
return { selectedOption, customCommittedText, draft, customActive };
|
||||
}
|
||||
|
||||
function buildQuestionHandlers(ctx: QuestionHandlerCtx): QuestionHandlers {
|
||||
const { meta, group, isSingleQuestion, activeIndex, total, setActiveIndex, setCustomDrafts } =
|
||||
ctx;
|
||||
|
||||
// Records the answer, then auto-submits (single-question — uses the override
|
||||
// path because setState is async) or auto-advances to the next step.
|
||||
const commitAnswer = (answer: ClarificationAnswer) => {
|
||||
group.recordAnswer(meta.questionId, answer);
|
||||
if (isSingleQuestion) {
|
||||
void group.submitCollected({ [meta.questionId]: answer });
|
||||
return;
|
||||
}
|
||||
if (activeIndex < total - 1) setActiveIndex(activeIndex + 1);
|
||||
};
|
||||
|
||||
return {
|
||||
onSelectOption(optionId) {
|
||||
// Picking an option wipes any in-flight draft so the answer state and
|
||||
// the visible input agree (custom_text and selected_options are mutually
|
||||
// exclusive at commit time).
|
||||
setCustomDrafts((prev) => {
|
||||
if (!prev[meta.questionId]) return prev;
|
||||
return { ...prev, [meta.questionId]: "" };
|
||||
});
|
||||
commitAnswer({ question_id: meta.questionId, selected_options: [optionId] });
|
||||
},
|
||||
// Live-record the draft so the stepper updates and the custom input lights
|
||||
// up the moment the user types. Emptying the draft clears the answer so
|
||||
// allAnswered reverts to false. Enter/Cmd+Enter still drives advance/submit.
|
||||
onCustomDraftChange(value) {
|
||||
setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }));
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
group.clearAnswer(meta.questionId);
|
||||
return;
|
||||
}
|
||||
group.recordAnswer(meta.questionId, {
|
||||
question_id: meta.questionId,
|
||||
selected_options: [],
|
||||
custom_text: trimmed,
|
||||
});
|
||||
},
|
||||
onSubmitCustom(text) {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return;
|
||||
commitAnswer({
|
||||
question_id: meta.questionId,
|
||||
selected_options: [],
|
||||
custom_text: trimmed,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function ClarificationCarouselBody({
|
||||
sortedMessages,
|
||||
group,
|
||||
@@ -231,7 +347,6 @@ function ClarificationCarouselBody({
|
||||
(m) => (m.metadata as ClarificationRequestMetadata | undefined)?.agent_disconnected === true,
|
||||
);
|
||||
const isSubmitting = group.submitState === "submitting";
|
||||
|
||||
const isSingleQuestion = total === 1;
|
||||
|
||||
const allAnswered = sortedMessages.every((m) => {
|
||||
@@ -239,48 +354,31 @@ function ClarificationCarouselBody({
|
||||
return id ? Boolean(group.answers[id]) : false;
|
||||
});
|
||||
|
||||
// group is a fresh object every render, but its submitCollected callback is
|
||||
// memoised by the hook — depend on the function only so this useCallback
|
||||
// doesn't churn on every keystroke (via the live-record path).
|
||||
const submitCollected = group.submitCollected;
|
||||
const handleSubmit = useCallback(() => {
|
||||
if (allAnswered) void group.submitCollected();
|
||||
}, [allAnswered, group]);
|
||||
if (allAnswered) void submitCollected();
|
||||
}, [allAnswered, submitCollected]);
|
||||
|
||||
if (!meta) return null;
|
||||
|
||||
const stored = group.answers[meta.questionId];
|
||||
const selectedOption =
|
||||
stored?.selected_options && stored.selected_options.length > 0
|
||||
? stored.selected_options[0]
|
||||
: null;
|
||||
const customCommittedText = stored?.custom_text ?? null;
|
||||
const draft = customDrafts[meta.questionId] ?? "";
|
||||
const { selectedOption, customCommittedText, draft, customActive } = deriveSelectionState(
|
||||
meta,
|
||||
group.answers,
|
||||
customDrafts,
|
||||
);
|
||||
|
||||
// Records the new answer, then either auto-submits (single-question case
|
||||
// takes the override path so the freshly recorded answer is included even
|
||||
// though setState is async) or auto-advances to the next step.
|
||||
const commitAnswer = (answer: ClarificationAnswer) => {
|
||||
group.recordAnswer(meta.questionId, answer);
|
||||
if (isSingleQuestion) {
|
||||
void group.submitCollected({ [meta.questionId]: answer });
|
||||
return;
|
||||
}
|
||||
if (activeIndex < total - 1) {
|
||||
setActiveIndex(activeIndex + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const onSelectOption = (optionId: string) => {
|
||||
commitAnswer({
|
||||
question_id: meta.questionId,
|
||||
selected_options: [optionId],
|
||||
});
|
||||
};
|
||||
const onSubmitCustom = (text: string) => {
|
||||
if (!text.trim()) return;
|
||||
commitAnswer({
|
||||
question_id: meta.questionId,
|
||||
selected_options: [],
|
||||
custom_text: text.trim(),
|
||||
});
|
||||
};
|
||||
const { onSelectOption, onCustomDraftChange, onSubmitCustom } = buildQuestionHandlers({
|
||||
meta,
|
||||
group,
|
||||
isSingleQuestion,
|
||||
activeIndex,
|
||||
total,
|
||||
setActiveIndex,
|
||||
setCustomDrafts,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -291,13 +389,13 @@ function ClarificationCarouselBody({
|
||||
selectedOption={selectedOption}
|
||||
customCommittedText={customCommittedText}
|
||||
customDraft={draft}
|
||||
customActive={customActive}
|
||||
isSubmitting={isSubmitting}
|
||||
showAgentDisconnected={activeIndex === 0 && showAgentDisconnectedAtTop}
|
||||
onSelectOption={onSelectOption}
|
||||
onCustomDraftChange={(value) =>
|
||||
setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }))
|
||||
}
|
||||
onCustomDraftChange={onCustomDraftChange}
|
||||
onSubmitCustom={onSubmitCustom}
|
||||
onRequestFinalSubmit={handleSubmit}
|
||||
/>
|
||||
{!isSingleQuestion && (
|
||||
<ClarificationCarouselNav
|
||||
|
||||
@@ -76,24 +76,24 @@ type OptionListProps = {
|
||||
options: ClarificationOption[];
|
||||
selectedOption: string | null;
|
||||
isSubmitting: boolean;
|
||||
// When the custom-text input is the active answer (user is typing or has
|
||||
// committed a draft), options visually deselect — the two are mutually
|
||||
// exclusive at commit time, so the highlight tracks whichever is active.
|
||||
customActive: boolean;
|
||||
onSelectOption: (optionId: string) => void;
|
||||
};
|
||||
|
||||
// The agent receives both the selected option id and the custom text when
|
||||
// both are present, so we never visually grey out one when the other is
|
||||
// active — that previously created an asymmetric dimming bug where typing
|
||||
// a custom answer dimmed the options but selecting an option did not dim
|
||||
// the custom input.
|
||||
export function ClarificationOptions({
|
||||
options,
|
||||
selectedOption,
|
||||
isSubmitting,
|
||||
customActive,
|
||||
onSelectOption,
|
||||
}: OptionListProps) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
{options.map((option, idx) => {
|
||||
const isSelected = selectedOption === option.option_id;
|
||||
const isSelected = !customActive && selectedOption === option.option_id;
|
||||
return (
|
||||
<button
|
||||
key={option.option_id}
|
||||
@@ -144,20 +144,43 @@ type CustomInputProps = {
|
||||
draft: string;
|
||||
isSubmitting: boolean;
|
||||
committedText: string | null;
|
||||
// True when the custom input is the active answer (non-empty draft or a
|
||||
// committed custom_text and no option selected). Drives the blue ring +
|
||||
// check icon so it matches the visual language of a selected option.
|
||||
active: boolean;
|
||||
onChange: (text: string) => void;
|
||||
onSubmit: (text: string) => void;
|
||||
// Called after Cmd/Ctrl+Enter so the parent can attempt a batch submit
|
||||
// (no-op when not all questions are answered yet).
|
||||
onRequestFinalSubmit?: () => void;
|
||||
};
|
||||
|
||||
export function ClarificationCustomInput({
|
||||
draft,
|
||||
isSubmitting,
|
||||
committedText,
|
||||
active,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onRequestFinalSubmit,
|
||||
}: CustomInputProps) {
|
||||
return (
|
||||
<div className="mt-2.5 flex items-center gap-2 px-3 py-2 rounded-lg border border-dashed border-border/70 bg-muted/30">
|
||||
<span className="text-muted-foreground text-xs">↳</span>
|
||||
<div
|
||||
data-testid="clarification-custom-input"
|
||||
data-active={active ? "true" : "false"}
|
||||
className={cn(
|
||||
"mt-2.5 flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors",
|
||||
active
|
||||
? "bg-blue-500/15 border-blue-500/50 text-foreground"
|
||||
: "border-dashed border-border/70 bg-muted/30",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn("text-xs", active ? "text-blue-500" : "text-muted-foreground")}
|
||||
aria-hidden="true"
|
||||
>
|
||||
↳
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={
|
||||
@@ -169,7 +192,17 @@ export function ClarificationCustomInput({
|
||||
data-testid="clarification-input"
|
||||
className="flex-1 text-sm bg-transparent placeholder:text-muted-foreground/60 focus:outline-none"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey && draft.trim()) {
|
||||
if (e.key !== "Enter" || e.shiftKey || e.altKey) return;
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
// Cmd/Ctrl+Enter only asks the parent to finalize. The draft was
|
||||
// already live-recorded via onChange, so we skip the per-question
|
||||
// commit path (which would also advance the carousel one step on
|
||||
// multi-question bundles — wasted state churn before submit).
|
||||
e.preventDefault();
|
||||
onRequestFinalSubmit?.();
|
||||
return;
|
||||
}
|
||||
if (draft.trim()) {
|
||||
e.preventDefault();
|
||||
onSubmit(draft.trim());
|
||||
}
|
||||
@@ -182,6 +215,7 @@ export function ClarificationCustomInput({
|
||||
<IconCornerDownLeft className="h-2.5 w-2.5" />
|
||||
Enter
|
||||
</kbd>
|
||||
{active && <IconCheck className="h-3.5 w-3.5 text-blue-500 flex-shrink-0" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -329,6 +329,11 @@ export class SessionPage {
|
||||
return this.clarificationQuestionCardById(questionId).getByTestId("clarification-input");
|
||||
}
|
||||
|
||||
/** Container around the custom text input — exposes data-active for selection state. */
|
||||
clarificationCustomInputContainerForQuestion(questionId: string): Locator {
|
||||
return this.clarificationQuestionCardById(questionId).getByTestId("clarification-custom-input");
|
||||
}
|
||||
|
||||
/** Option button (by visible label text) inside a specific question card. */
|
||||
clarificationOptionForQuestion(questionId: string, text: string): Locator {
|
||||
return this.clarificationQuestionCardById(questionId)
|
||||
|
||||
@@ -473,4 +473,127 @@ test.describe("Multi-question clarification carousel", () => {
|
||||
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
|
||||
await expect(session.clarificationPrev()).toBeDisabled();
|
||||
});
|
||||
|
||||
test("typing in the custom input auto-selects it and deselects the picked option", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const session = await seedClarificationTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
"Multi-q custom auto-selects",
|
||||
"clarification-multi",
|
||||
);
|
||||
|
||||
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// Pick an option on Q1 (auto-advances to Q2), then jump back to Q1.
|
||||
await session.clarificationOption("PostgreSQL").click();
|
||||
await session.clarificationStep(0).click();
|
||||
const selectedBefore = session
|
||||
.clarificationQuestionCardById("db")
|
||||
.locator('[data-testid="clarification-option"][data-selected="true"]');
|
||||
await expect(selectedBefore).toContainText("PostgreSQL");
|
||||
|
||||
// Type into the custom input — it should light up and the option should
|
||||
// deselect, while the stepper keeps step 0 marked as answered.
|
||||
const input = session.clarificationInputForQuestion("db");
|
||||
await input.click();
|
||||
await input.fill("Bespoke KV store");
|
||||
|
||||
const customContainer = session.clarificationCustomInputContainerForQuestion("db");
|
||||
await expect(customContainer).toHaveAttribute("data-active", "true");
|
||||
await expect(
|
||||
session
|
||||
.clarificationQuestionCardById("db")
|
||||
.locator('[data-testid="clarification-option"][data-selected="true"]'),
|
||||
).toHaveCount(0);
|
||||
await expect(session.clarificationStep(0)).toHaveAttribute("data-answered", "true");
|
||||
await expect(session.clarificationGroupProgress()).toContainText("1 of 3 answered");
|
||||
});
|
||||
|
||||
test("emptying the custom draft clears the answer and reverts the stepper", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const session = await seedClarificationTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
"Multi-q draft clears answer",
|
||||
"clarification-multi",
|
||||
);
|
||||
|
||||
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const input = session.clarificationInputForQuestion("db");
|
||||
await input.click();
|
||||
await input.fill("Bespoke KV store");
|
||||
await expect(session.clarificationStep(0)).toHaveAttribute("data-answered", "true");
|
||||
await expect(session.clarificationGroupProgress()).toContainText("1 of 3 answered");
|
||||
|
||||
await input.fill("");
|
||||
await expect(session.clarificationStep(0)).toHaveAttribute("data-answered", "false");
|
||||
await expect(session.clarificationGroupProgress()).toContainText("0 of 3 answered");
|
||||
await expect(session.clarificationCustomInputContainerForQuestion("db")).toHaveAttribute(
|
||||
"data-active",
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
test("Cmd+Enter from the last step's custom input submits the bundle", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const session = await seedClarificationTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
"Multi-q cmd+enter from input",
|
||||
"clarification-multi",
|
||||
);
|
||||
|
||||
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await session.clarificationOption("PostgreSQL").click();
|
||||
await session.clarificationOption("Go").click();
|
||||
|
||||
const deployInput = session.clarificationInputForQuestion("deploy");
|
||||
await deployInput.click();
|
||||
await deployInput.fill("Nomad cluster");
|
||||
await deployInput.press("ControlOrMeta+Enter");
|
||||
|
||||
await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });
|
||||
await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
|
||||
await expect(session.chat).toContainText("Nomad cluster");
|
||||
});
|
||||
|
||||
test("Cmd+Enter from outside the input submits when all questions are answered", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const session = await seedClarificationTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
"Multi-q cmd+enter global",
|
||||
"clarification-multi",
|
||||
);
|
||||
|
||||
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await session.clarificationOption("PostgreSQL").click();
|
||||
await session.clarificationOption("Go").click();
|
||||
await session.clarificationOption("Docker").click();
|
||||
|
||||
// Focus is on the last option button, not the input.
|
||||
await testPage.keyboard.press("ControlOrMeta+Enter");
|
||||
await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });
|
||||
await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -77,6 +77,31 @@ describe("useClarificationGroup — derived state", () => {
|
||||
expect(result.current.answeredCount).toBe(1);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clearAnswer removes the entry and decrements answeredCount", async () => {
|
||||
const msgs = [
|
||||
clarMessage({ id: "m1", pendingId: "p1", questionId: "q1", index: 0, total: 2 }),
|
||||
clarMessage({ id: "m2", pendingId: "p1", questionId: "q2", index: 1, total: 2 }),
|
||||
];
|
||||
const { result } = renderHook(() => useClarificationGroup(msgs));
|
||||
|
||||
await act(async () => {
|
||||
result.current.recordAnswer("q1", { question_id: "q1", custom_text: "draft" });
|
||||
});
|
||||
expect(result.current.answeredCount).toBe(1);
|
||||
|
||||
await act(async () => {
|
||||
result.current.clearAnswer("q1");
|
||||
});
|
||||
expect(result.current.answers["q1"]).toBeUndefined();
|
||||
expect(result.current.answeredCount).toBe(0);
|
||||
|
||||
// Clearing a question that was never recorded is a no-op.
|
||||
await act(async () => {
|
||||
result.current.clearAnswer("q-missing");
|
||||
});
|
||||
expect(result.current.answeredCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useClarificationGroup — submit + skip", () => {
|
||||
@@ -185,3 +210,37 @@ describe("useClarificationGroup — submit + skip", () => {
|
||||
expect(result.current.submitState).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("useClarificationGroup — inflight guard", () => {
|
||||
beforeEach(setupFetchMock);
|
||||
|
||||
// Cmd+Enter inside the custom-text input historically reached both onSubmit
|
||||
// and onRequestFinalSubmit, which could fire submitCollected twice in the
|
||||
// same tick. The hook's inflight ref must keep the wire count at 1 even if
|
||||
// the UI races; the backend would otherwise see a duplicate POST.
|
||||
it("submitCollected guards against concurrent calls", async () => {
|
||||
let resolveFetch: ((res: Response) => void) | null = null;
|
||||
fetchMock.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
);
|
||||
const msgs = [clarMessage({ id: "m1", pendingId: "p1", questionId: "q1", index: 0, total: 1 })];
|
||||
const { result } = renderHook(() => useClarificationGroup(msgs));
|
||||
|
||||
await act(async () => {
|
||||
result.current.recordAnswer("q1", { question_id: "q1", selected_options: ["o1"] });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
const first = result.current.submitCollected();
|
||||
const second = result.current.submitCollected();
|
||||
resolveFetch?.(new Response(null, { status: 200 }));
|
||||
await Promise.all([first, second]);
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.submitState).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ export type ClarificationGroupApi = {
|
||||
answers: Record<string, ClarificationAnswer>;
|
||||
submitState: SubmitState;
|
||||
recordAnswer: (questionId: string, answer: ClarificationAnswer) => void;
|
||||
clearAnswer: (questionId: string) => void;
|
||||
// Submits every recorded answer in a single batch. An optional `override`
|
||||
// map is merged into the current answers right before the POST so callers
|
||||
// can safely auto-submit immediately after recording an answer (the React
|
||||
@@ -88,6 +89,11 @@ export function useClarificationGroup(
|
||||
answersRef.current = answers;
|
||||
}, [answers]);
|
||||
const [submitState, setSubmitState] = useState<SubmitState>("idle");
|
||||
// Re-entry guard: multiple submit paths can race (Cmd+Enter inside the
|
||||
// custom input fires both the input's onSubmit and onRequestFinalSubmit;
|
||||
// a double-click on the Submit button can also race). The hook owns the
|
||||
// guarantee that only one POST is in flight at a time.
|
||||
const inflightRef = useRef(false);
|
||||
|
||||
const pendingId = useMemo(() => {
|
||||
if (!messages || messages.length === 0) return null;
|
||||
@@ -106,12 +112,23 @@ export function useClarificationGroup(
|
||||
setAnswers((prev) => ({ ...prev, [questionId]: answer }));
|
||||
}, []);
|
||||
|
||||
const clearAnswer = useCallback((questionId: string) => {
|
||||
setAnswers((prev) => {
|
||||
if (!(questionId in prev)) return prev;
|
||||
const next = { ...prev };
|
||||
delete next[questionId];
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const submitCollected = useCallback(
|
||||
async (override?: Record<string, ClarificationAnswer>) => {
|
||||
if (!pendingId) return;
|
||||
if (inflightRef.current) return;
|
||||
const current = { ...answersRef.current, ...(override ?? {}) };
|
||||
const haveAll = questionIds.every((id) => Boolean(current[id]));
|
||||
if (!haveAll) return;
|
||||
inflightRef.current = true;
|
||||
setSubmitState("submitting");
|
||||
const ordered = questionIds
|
||||
.map((id) => current[id])
|
||||
@@ -121,6 +138,8 @@ export function useClarificationGroup(
|
||||
} catch (err) {
|
||||
console.error("Clarification submit threw:", err);
|
||||
setSubmitState("error");
|
||||
} finally {
|
||||
inflightRef.current = false;
|
||||
}
|
||||
},
|
||||
[pendingId, questionIds],
|
||||
@@ -129,12 +148,16 @@ export function useClarificationGroup(
|
||||
const skipAll = useCallback(
|
||||
async (reason?: string) => {
|
||||
if (!pendingId) return;
|
||||
if (inflightRef.current) return;
|
||||
inflightRef.current = true;
|
||||
setSubmitState("submitting");
|
||||
try {
|
||||
setSubmitState(await postClarificationSkip(pendingId, reason ?? "User skipped"));
|
||||
} catch (err) {
|
||||
console.error("Clarification skip threw:", err);
|
||||
setSubmitState("error");
|
||||
} finally {
|
||||
inflightRef.current = false;
|
||||
}
|
||||
},
|
||||
[pendingId],
|
||||
@@ -147,6 +170,7 @@ export function useClarificationGroup(
|
||||
answers,
|
||||
submitState,
|
||||
recordAnswer,
|
||||
clearAnswer,
|
||||
submitCollected,
|
||||
skipAll,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user