Files
PaperClipAI/ui/src/components/task-chat/QuestionForm.tsx
T
a3313f6944 fix(ui): complete read recovery and enforce query error rendering (#18822)
## Thinking Path

> - Paperclip lets people manage agent work through the board.
> - The board reads task, agent, settings, plugin, and run data from the
server.
> - A deploy can interrupt those reads after content is already visible.
> - Local error branches can replace that content with an error or show
raw codes.
> - This pull request moves the remaining reads to the shared recovery
behavior.
> - The query-error guard prevents new local error patterns from
returning.

## Linked Issues or Issue Description

**What happened?**
Loaded lists, settings, task panels, and manual reads could clear their
content or show errors during a server restart. Some reads also disabled
the shared retry policy.

**Expected behavior**
Keep loaded content during a temporary failure. Show the shared
connection banner. Retry reads after recovery. Replace content after a
real access denial or missing resource, with readable copy.

**Steps to reproduce**
Open a task, settings page, or run log. Return 503 with
`tenant_app_unavailable` from the API. Restore the API and check that
content refreshes. Repeat with 403 and 404 to check the failure state.

Related merged work: Refs #15754, Refs #15772, Refs #17960. This change
covers remaining reads and enforcement. Browser persistence and the
outage browser suite follow separately.

## What Changed

- Repair an existing PostgreSQL deadline fixture at UTC boundaries. A
daily cap defers a heartbeat until both its original interval and the
next UTC day allow it. Keep the counted run in its seeded day and cover
noon, just before midnight and the first second after midnight with
explicit clocks and real PostgreSQL. Production scheduling is unchanged.

- Integrate the saved list, settings, shell, task, and manual-read
recovery changes against current master. Preserve the current task,
Inbox, and run-log structure.
- Add `useResilientFetch` for component-local reads. Preserve loaded
data, cancel stale requests, and retry through the shared connectivity
policy. Keep browser and pairing capabilities in memory.
- Retain run log chunks across stream changes and catch up after
recovery without duplicate chunks or stalled requests.
- Keep genuine authorization and missing-resource failures visible.
Translate known single-word codes such as `forbidden`. Show known skills
and disconnected-app failures before sibling loading states. Keep Retry
bound to its failed request.
- Make the query-error guard enforce by default and run it in the CI
policy job. Document the narrow exceptions and the read recovery
contract.
- Invalidate pending OAuth discovery when the operator leaves setup or
its context changes. Keep reserved-popup cleanup bound to the current
attempt.

## Verification

- Current read head `09d1db29dea` is merge-ready: all 59 check runs are
completed (54 successful, three skipped, two neutral), the legacy Snyk
status is successful, and both required `ci / verify` and `ci / e2e`
gates pass. Greptile Apex reviewed this exact head at 5/5 with no
unresolved threads; the branch has no merge conflicts. The current CI
run is `41748339602`.
- Current read head `09d1db29dea` includes master `683fa4725e9`. The
latest change touches only the existing server deadline test fixture.
Application source remains the previously verified `86376fa751e`
revision: all 60 affected skills/disconnected-app tests and both
application UI typechecks passed, along with token gates and the
enforcing query-error guard. Those UI suites were not repeated for this
test-only repair.
- The fixture repair passes all seven deadline integration cases and the
complete server typecheck, including the server test layer. The old
assertion deterministically fails at 23:59:06.888 UTC; its
one-second-old run also fails the first-second-of-day probe. The
corrected fixture passes noon and both midnight probes. The permanent
three-case coverage uses seeded 2099 clocks.
- Twelve new regressions fail against the previous implementation. Both
skills variants and disconnected-app pages show either request's 403 or
429 while the sibling pauses or remains fetching. Permission failures
stay visible. Retry stays usable for its failed request and recovers
independently. An initial test-fixture query-key typo was corrected
before the passing run. The finding is replied to and resolved. Greptile
reviewed prior application revision `86376fa751e` at 5/5 with no new
actionable findings or unresolved threads. The current test-only head
has now received its own Apex 5/5 review with no unresolved threads, and
its CI is successful as recorded above.
- The preceding OAuth fix passed all 237 setup tests on both application
branches. Its ten regressions prove that Back, Cancel, unmount, or
context changes retire initial discovery without creating a connection,
caching old identities, navigating an abandoned popup, or closing a
newer attempt.
- Earlier master integration `e992f770339` passed all 309 tests across
eight affected Slack, recovery, retry, submission and task files, plus
UI typecheck, token gates, enforcing query-error scan and seven guard
tests. The integration preserves Slack workspace reconnect and shared
recovery, readable execution errors, source-inspection company scoping,
and current submission behavior. Newly inherited retained-file recovery
controls keep cached data through transient failures and hide it after
definitive denial.
- The preceding cache head `97c0bc3966f` passed 1,038 focused
cache/write/editor/account/task/API tests. All 22 built-UI
outage/write/loading cases passed in 4.7 minutes on exact browser head
`b7deaaee5da`, with strict checking of all three specs. The latest
skills/app rendering fix is covered by its affected component suites;
those broader cases were not repeated for this separate read path.
- Historical broader UI, CLI and build results and unresolved aggregate
server/DB/adapter failures remain in the PR discussion. Interrupted CI
runs were audited and recorded separately; they are not counted as
passes. Controlled local outages do not prove hosted authentication or a
real Cloud restart/deploy. Real hosted acceptance remains required after
merge and deployment.

Commands for the latest fix:

```sh
pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
node scripts/check-query-error-rendering.mjs --enforce --summary
```

## Risks

This migration touches many read surfaces. The main risks are initial
loading, request cancellation, retained authorization state, and run-log
paging. The tests cover those states. There are no server, schema,
dependency, or API contract changes. The follow-up browser suite and
hosted deploy acceptance are required before release acceptance.

Recovered commits retain their original authors. If squash-merging,
preserve `Co-Authored-By: Bender (Fable) <bender@agents.paperclip.ing>`
and the Paperclip trailer.

## Model Used

OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool
use, and code execution. The context window size is not exposed. Saved
source commits keep their original authorship.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] The affected local tests pass; broader limitations are recorded
above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 14:07:18 -08:00

742 lines
25 KiB
TypeScript

import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Check,
ChevronLeft,
ChevronRight,
Loader2,
Search,
} from "lucide-react";
import type {
PaperclipQuestionResponse,
PaperclipQuestionSet,
} from "@paperclipai/adapter-utils";
import type { MentionOption } from "@/components/MarkdownEditor";
import { DecisionCardFooter } from "@/components/DecisionCardFooter";
import { MarkdownBody } from "@/components/MarkdownBody";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
clearDraft,
loadStructuredDraft,
saveStructuredDraft,
} from "@/lib/composer-draft";
import { cn } from "@/lib/utils";
import {
TaskChatComposerTakeoverControls,
useTaskChatComposerTakeoverActions,
} from "./TaskChatComposerTakeoverContext";
import { TaskChatRichInput } from "./TaskChatRichInput";
import { matchSafeQuestionValidationPattern } from "./question-validation-pattern";
type Question = PaperclipQuestionSet["questions"][number];
type Answer = PaperclipQuestionResponse["answers"][string];
/**
* A form-level message, tagged with whether answering a question resolves it.
*
* Only a missing-answer complaint is something a selection can settle. A send
* that failed is not: the answers are still unsent, so the message has to
* outlive the next click rather than disappear the moment the reader touches
* an option.
*/
type FormError = { message: string; fromMissingAnswer?: boolean };
export interface QuestionFormProps {
footerSlot?: ReactNode;
id: string;
presentation?: "default" | "decision";
questionSet: PaperclipQuestionSet;
initialResponse?: PaperclipQuestionResponse | null;
implicitCustomAnswer?: boolean;
draftKey?: string;
disabled?: boolean;
imageUploadHandler?: (file: File) => Promise<string>;
mentions?: MentionOption[];
onSubmit: (response: PaperclipQuestionResponse) => void | Promise<void>;
/**
* Resolves the request itself (a timeline card cancelling the interaction).
* Inside the composer takeover the form falls back to dismissing the
* takeover, which returns the plain composer without touching the request.
*/
onCancel?: () => void | Promise<void>;
}
function answerHasValue(answer: Answer | undefined): boolean {
return Boolean(
answer?.text?.trim() ||
answer?.customText?.trim() ||
answer?.selectedOptionIds?.length,
);
}
function answerError(
question: Question,
answer: Answer | undefined,
): string | null {
if (question.required && !answerHasValue(answer))
return "This question is required.";
if (
question.answerMode !== "text" &&
answer?.customText !== undefined &&
!answer.customText.trim()
) {
return "Enter a custom answer.";
}
const value =
question.answerMode === "text" ? answer?.text : answer?.customText;
if (value == null || value.length === 0) return null;
const validation = question.textValidation;
if (validation?.minLength != null && value.length < validation.minLength)
return `Enter at least ${validation.minLength} characters.`;
if (validation?.maxLength != null && value.length > validation.maxLength)
return `Enter no more than ${validation.maxLength} characters.`;
if (validation?.pattern) {
const result = matchSafeQuestionValidationPattern(validation.pattern, value);
if (result === "unsupported")
return "This question has an unsupported validation pattern.";
if (result === "no_match") return "Use the requested format.";
}
if (
validation?.inputType === "number" ||
validation?.inputType === "integer"
) {
const numeric = Number(value);
if (
!Number.isFinite(numeric) ||
(validation.inputType === "integer" && !Number.isInteger(numeric))
) {
return `Enter a valid ${validation.inputType}.`;
}
if (validation.minimum != null && numeric < validation.minimum)
return `Enter a value of at least ${validation.minimum}.`;
if (validation.maximum != null && numeric > validation.maximum)
return `Enter a value no greater than ${validation.maximum}.`;
}
return null;
}
function SelectOption({
id,
label,
description,
recommended,
selected,
multiple,
disabled,
onClick,
}: {
id: string;
label: string;
description?: string;
recommended?: boolean;
selected: boolean;
multiple: boolean;
disabled: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
id={id}
role={multiple ? "checkbox" : "radio"}
aria-checked={selected}
disabled={disabled}
className={cn(
"tc-question-option flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",
selected
? "bg-foreground/5"
: recommended
? "bg-muted/50"
: "hover:bg-muted/40",
)}
data-selected={selected ? "true" : "false"}
data-recommended={recommended ? "true" : "false"}
onClick={onClick}
>
<span
aria-hidden
className={cn(
"mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border",
multiple ? "rounded-sm" : "rounded-full",
selected
? "border-primary bg-primary text-primary-foreground"
: "border-muted-foreground/50",
)}
>
{selected ? (
multiple ? (
<Check className="h-3 w-3" />
) : (
<span className="h-1.5 w-1.5 rounded-full bg-current" />
)
) : null}
</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-1.5 text-sm font-medium leading-5 text-foreground">
<span>{label}</span>
{recommended ? (
<span className="rounded-sm bg-background/70 px-1.5 py-0.5 text-(length:--text-micro) font-medium text-muted-foreground">
Recommended
</span>
) : null}
</span>
{description ? (
<span className="block text-xs leading-4 text-muted-foreground">
{description}
</span>
) : null}
</span>
</button>
);
}
export function QuestionResponseSummary({
questionSet,
response,
}: {
questionSet: PaperclipQuestionSet;
response: PaperclipQuestionResponse;
}) {
return (
<dl className="grid gap-2 text-sm">
{questionSet.questions.map((question) => {
const answer = response.answers[question.id];
const selectedLabels = (answer?.selectedOptionIds ?? []).map(
(optionId) =>
question.options?.find((option) => option.id === optionId)?.label ??
optionId,
);
const values = [
...selectedLabels,
answer?.text,
answer?.customText,
].filter((value): value is string => Boolean(value));
return (
<div key={question.id}>
<dt>
{question.header ? (
<span className="block text-xs font-medium text-muted-foreground">
{question.header}
</span>
) : null}
<span className="block text-sm text-foreground">
{question.prompt}
</span>
</dt>
<dd className="mt-0.5 text-foreground">
{values.length > 0 ? values.join(", ") : "No answer"}
</dd>
</div>
);
})}
</dl>
);
}
export function QuestionForm(props: QuestionFormProps) {
// Takeovers can reuse this component for another pending request. Remount
// before draft persistence runs so one request cannot overwrite another.
return <QuestionFormForRequest key={JSON.stringify([props.id, props.draftKey])} {...props} />;
}
function QuestionFormForRequest({
footerSlot,
id,
presentation = "default",
questionSet,
initialResponse,
implicitCustomAnswer = false,
draftKey,
disabled = false,
imageUploadHandler,
mentions,
onSubmit,
onCancel,
}: QuestionFormProps) {
const takeoverActions = useTaskChatComposerTakeoverActions();
// A provider default is an editable draft only. An existing response or
// saved draft, including an explicitly cleared value, always wins. State
// initialization runs once so request refreshes cannot replace user edits.
const startingAnswers = initialResponse?.answers ?? Object.fromEntries(
questionSet.questions
.filter((question) => question.answerMode === "text" && question.initialText !== undefined)
.map((question) => [question.id, { text: question.initialText! }]),
);
const initialDraft = draftKey
? loadStructuredDraft<{
page: number;
answers: Record<string, Answer>;
customActive: Record<string, boolean>;
}>(draftKey, {
page: 0,
answers: structuredClone(startingAnswers),
customActive: Object.fromEntries(
Object.entries(initialResponse?.answers ?? {})
.filter(([, answer]) => Boolean(answer.customText))
.map(([questionId]) => [questionId, true]),
),
})
: null;
const [page, setPage] = useState(initialDraft?.page ?? 0);
const [answers, setAnswers] = useState<Record<string, Answer>>(
() =>
initialDraft?.answers ?? structuredClone(startingAnswers),
);
const [customActive, setCustomActive] = useState<Record<string, boolean>>(
() =>
initialDraft?.customActive ??
Object.fromEntries(
Object.entries(initialResponse?.answers ?? {})
.filter(([, answer]) => Boolean(answer.customText))
.map(([questionId]) => [questionId, true]),
),
);
const [working, setWorking] = useState<"submit" | "cancel" | null>(null);
const [inputUploading, setInputUploading] = useState(false);
const [error, setError] = useState<FormError | null>(null);
const [attemptedQuestions, setAttemptedQuestions] = useState<Record<string, boolean>>({});
const promptRef = useRef<HTMLParagraphElement>(null);
const previousPage = useRef(page);
useEffect(() => {
if (previousPage.current !== page) {
promptRef.current?.focus();
previousPage.current = page;
}
}, [page]);
const [filters, setFilters] = useState<Record<string, string>>({});
useEffect(() => {
setPage((current) =>
Math.min(current, Math.max(questionSet.questions.length - 1, 0)),
);
}, [questionSet.questions.length]);
useEffect(() => {
if (draftKey)
saveStructuredDraft(draftKey, { page, answers, customActive });
}, [answers, customActive, draftKey, page]);
const question = questionSet.questions[page];
const validationErrors = useMemo(
() =>
Object.fromEntries(
questionSet.questions.map((candidate) => [
candidate.id,
answerError(candidate, answers[candidate.id]),
]),
),
[answers, questionSet.questions],
);
if (!question)
return (
<p className="text-sm text-muted-foreground">
No answerable questions were provided.
</p>
);
const answer = answers[question.id] ?? {};
const selected = answer.selectedOptionIds ?? [];
const multiple = question.answerMode === "multi_select";
const allowsCustom =
question.answerMode !== "text" &&
(question.customAnswer?.enabled === true || implicitCustomAnswer);
const isCustomActive = customActive[question.id] === true;
const optionFilter = filters[question.id]?.trim().toLowerCase() ?? "";
const visibleOptions = (question.options ?? []).filter(
(option) =>
!optionFilter ||
option.label.toLowerCase().includes(optionFilter) ||
option.description?.toLowerCase().includes(optionFilter),
);
function updateAnswer(next: Answer) {
setAnswers((current) => ({ ...current, [question.id]: next }));
if (answerError(question, next) == null) {
setError((current) => current?.fromMissingAnswer ? null : current);
}
}
function toggleOption(optionId: string) {
if (disabled || working || inputUploading) return;
const optionIds = multiple
? selected.includes(optionId)
? selected.filter((candidate) => candidate !== optionId)
: [...selected, optionId]
: [optionId];
const nextAnswer = {
...answer,
selectedOptionIds: optionIds,
...(!multiple ? { customText: undefined } : {}),
};
setAnswers({ ...answers, [question.id]: nextAnswer });
if (!multiple) {
setCustomActive((current) => ({ ...current, [question.id]: false }));
// Picking an option answers the question; it does not navigate. Moving on
// stays an explicit act — Next, the pagination arrows, or Submit — so a
// misclick never costs the reader the page they were still reading.
//
// Clear only the complaint this selection actually answers. A failed send
// has to survive it, or the last page quietly loses the one sign that the
// answers never left.
setError((current) => (current?.fromMissingAnswer ? null : current));
}
}
function toggleCustom() {
const active = !isCustomActive;
setCustomActive((current) => ({ ...current, [question.id]: active }));
updateAnswer({
...answer,
...(!multiple && active ? { selectedOptionIds: [] } : {}),
...(active
? { customText: answer.customText ?? "" }
: { customText: undefined }),
});
}
async function submit(responseAnswers: Record<string, Answer> = answers) {
if (disabled || working || inputUploading) return;
const invalidIndex = questionSet.questions.findIndex(
(candidate) =>
answerError(candidate, responseAnswers[candidate.id]) != null,
);
if (invalidIndex >= 0) {
setAttemptedQuestions((current) => ({ ...current, [questionSet.questions[invalidIndex]!.id]: true }));
// A required answer is missing: the pagination arrows browse without
// validating, and a restored draft can land past it. Go back to that
// question and say so rather than dropping the send.
setPage(invalidIndex);
setError({
message: `Question ${invalidIndex + 1} needs an answer before you can send.`,
fromMissingAnswer: true,
});
return;
}
setWorking("submit");
setError(null);
try {
await onSubmit({
schema: "paperclip.question_response.v1",
answers: structuredClone(responseAnswers),
});
if (draftKey) clearDraft(draftKey);
} catch (cause) {
setError({
message:
cause instanceof Error
? cause.message
: "The answers could not be submitted.",
});
} finally {
setWorking(null);
}
}
async function cancel() {
if (!onCancel || disabled || working || inputUploading) return;
setWorking("cancel");
setError(null);
try {
await onCancel();
if (draftKey) clearDraft(draftKey);
} catch (cause) {
setError({
message:
cause instanceof Error
? cause.message
: "The questions could not be cancelled.",
});
} finally {
setWorking(null);
}
}
const currentError = validationErrors[question.id];
const errorMessage = error?.message ?? null;
const isLastPage = page === questionSet.questions.length - 1;
const busy = disabled || working != null || inputUploading;
// Cancel resolves the request when the host owns that; otherwise it just
// closes the composer takeover so the user can type freely.
const cancelAction = onCancel
? () => void cancel()
: takeoverActions?.dismiss;
/** Leaves the current question unanswered and moves on (or sends). */
function skipQuestion() {
if (busy) return;
const { [question.id]: _skipped, ...rest } = answers;
setAnswers(rest);
setCustomActive((current) => ({ ...current, [question.id]: false }));
if (isLastPage) void submit(rest);
else setPage(page + 1);
}
const pagination =
questionSet.questions.length > 1 ? (
<nav
className="flex shrink-0 items-center gap-1"
aria-label="Question pagination"
>
<Button
type="button"
size="icon-xs"
variant="ghost"
aria-label="Previous question"
disabled={disabled || working != null || page === 0}
onClick={() => setPage((current) => current - 1)}
>
<ChevronLeft aria-hidden />
</Button>
<span className="min-w-10 text-center tabular-nums">
{page + 1} of {questionSet.questions.length}
</span>
<Button
type="button"
size="icon-xs"
variant="ghost"
aria-label="Next question"
// The arrows browse; they do not validate. A send that finds an
// earlier answer missing returns to that question (see submit).
disabled={disabled || working != null || isLastPage}
onClick={() => setPage((current) => current + 1)}
>
<ChevronRight aria-hidden />
</Button>
</nav>
) : null;
function progressOrSubmit() {
if (busy) return;
if (currentError) {
setAttemptedQuestions((current) => ({ ...current, [question.id]: true }));
return;
}
if (!isLastPage) {
setPage((current) =>
Math.min(current + 1, questionSet.questions.length - 1),
);
return;
}
void submit();
}
return (
<div
key={question.id}
className="tc-question-page"
onKeyDown={(event) => {
if (
disabled ||
working ||
event.repeat ||
question.answerMode === "text" ||
event.metaKey ||
event.ctrlKey ||
event.altKey
)
return;
const target = event.target as HTMLElement;
if (target.matches("input, textarea, [contenteditable='true']")) return;
const optionIndex = Number.parseInt(event.key, 10) - 1;
const option = visibleOptions[optionIndex];
if (!option || optionIndex < 0 || optionIndex > 8) return;
event.preventDefault();
toggleOption(option.id);
}}
>
{questionSet.description ? (
<div
role="region"
aria-label="Question context"
tabIndex={0}
className="mb-3 max-h-96 overflow-auto text-sm text-muted-foreground"
>
<MarkdownBody mediaMode="reference" linkIssueReferences={false}>{questionSet.description}</MarkdownBody>
</div>
) : null}
{question.answerMode === "text" && presentation !== "decision" ? (
<div className="mb-2 flex items-center gap-3 text-xs text-muted-foreground">
{question.answerMode === "text" ? <span>Write an answer</span> : null}
</div>
) : null}
{pagination ? (
takeoverActions ? (
<TaskChatComposerTakeoverControls>
{pagination}
</TaskChatComposerTakeoverControls>
) : (
<div className="mb-2 flex justify-end text-xs text-muted-foreground">
{pagination}
</div>
)
) : null}
<div>
{question.header && presentation !== "decision" ? (
<p className="mb-1 text-xs font-medium text-muted-foreground">
{question.header}
</p>
) : null}
<p
ref={promptRef}
tabIndex={-1}
id={`${id}-${question.id}-prompt`}
data-decision-prompt={presentation === "decision" ? true : undefined}
className={presentation === "decision" ? "text-lg font-medium leading-relaxed text-foreground" : "text-sm font-medium leading-5 text-foreground"}
>
{question.prompt}
</p>
{question.helpText ? (
<p className="mt-1 text-xs leading-4 text-muted-foreground">
{question.helpText}
</p>
) : null}
</div>
{question.answerMode === "text" ? (
<div className="mt-3">
<TaskChatRichInput
questionAnswer
ariaLabelledBy={`${id}-${question.id}-prompt`}
testId="question-text-answer-composer"
value={answer.text ?? ""}
disabled={disabled || working != null}
onChange={(value) => updateAnswer({ text: value })}
placeholder="Write your answer"
imageUploadHandler={imageUploadHandler}
mentions={mentions}
autoFocus
onUploadingChange={setInputUploading}
onSubmit={() => {
progressOrSubmit();
}}
attachAriaLabel={`Attach image to answer for ${question.prompt}`}
/>
</div>
) : (
<div
className="mt-3 grid gap-1.5"
role={multiple ? "group" : "radiogroup"}
aria-labelledby={`${id}-${question.id}-prompt`}
>
{(question.options?.length ?? 0) > 8 ? (
<label className="relative mb-1 block">
<Search
className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"
aria-hidden
/>
<Input
value={filters[question.id] ?? ""}
onChange={(event) =>
setFilters((current) => ({
...current,
[question.id]: event.target.value,
}))
}
placeholder="Filter choices"
aria-label={`Filter choices for ${question.prompt}`}
className="pl-8"
/>
</label>
) : null}
{visibleOptions.map((option) => (
<SelectOption
key={option.id}
id={`${id}-${question.id}-${option.id}`}
label={option.label}
description={option.description}
recommended={option.recommended}
selected={selected.includes(option.id)}
multiple={multiple}
disabled={disabled || working != null}
onClick={() => toggleOption(option.id)}
/>
))}
{allowsCustom ? (
<div className="space-y-1.5">
<SelectOption
id={`${id}-${question.id}-custom`}
label={question.customAnswer?.label ?? "Other"}
selected={isCustomActive}
multiple={multiple}
disabled={disabled || working != null}
onClick={toggleCustom}
/>
{isCustomActive ? (
<TaskChatRichInput
questionAnswer
ariaLabelledBy={`${id}-${question.id}-prompt`}
testId="question-other-answer-composer"
value={answer.customText ?? ""}
placeholder={
question.customAnswer?.placeholder ?? "Type your answer"
}
disabled={disabled || working != null}
onChange={(value) =>
updateAnswer({ ...answer, customText: value })
}
autoFocus
imageUploadHandler={imageUploadHandler}
mentions={mentions}
onUploadingChange={setInputUploading}
onSubmit={() => {
progressOrSubmit();
}}
attachAriaLabel={`Attach image to other answer for ${question.prompt}`}
/>
) : null}
</div>
) : null}
</div>
)}
{currentError && attemptedQuestions[question.id] ? (
<p role="alert" className="mt-2 text-xs text-destructive">{currentError}</p>
) : null}
<div aria-live="assertive">
{errorMessage ? (
<div className="mt-2 rounded-sm border border-destructive/60 bg-destructive/10 px-2.5 py-2 text-sm text-destructive">
{errorMessage}
</div>
) : null}
</div>
<DecisionCardFooter leading={footerSlot} className="mt-3">
<div className={cn(!footerSlot && "mt-3", "flex flex-wrap items-center justify-end gap-2")}>
{cancelAction ? (
<Button
type="button"
size="sm"
variant="ghost"
disabled={busy}
onClick={cancelAction}
>
{working === "cancel" ? (
<Loader2 aria-hidden className="h-4 w-4 animate-spin" />
) : null}{" "}
Cancel
</Button>
) : null}
{!question.required ? (
<Button
type="button"
size="sm"
variant="outline"
disabled={busy}
onClick={skipQuestion}
>
Skip
</Button>
) : null}
<Button
type="button"
size="sm"
disabled={busy}
onClick={progressOrSubmit}
>
{working === "submit" ? (
<Loader2 aria-hidden className="h-4 w-4 animate-spin" />
) : null}
{isLastPage ? (questionSet.submitLabel ?? "Submit answers") : "Next"}
</Button>
</div>
</DecisionCardFooter>
</div>
);
}