mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - The inbox collects decisions, requests, and updates for the people in a company. > - People need a clear personal queue and a consistent way to answer each request. > - Repeated headings, inconsistent card actions, and separate review flows make that work harder. > - This pull request connects the inbox UI to the routing foundation in #20959. > - Compact cards use shared task controls and open supporting work in a side panel. > - People can answer, claim, transfer, archive, and inspect outcomes from one place. ## Linked Issues or Issue Description **What existing behavior does this improve?** The inbox cards, personal views, shared task controls, and decision history. **Subsystem affected** UI. This PR targets master and uses the routing foundation merged in #20959. **Current behavior** The inbox repeats headings and counts. Cards have different layouts and action placement. The requester can repeat the signed-in person's name. Review and question controls differ between the inbox and task thread. **Proposed behavior** Open Assigned to you by default. Show one count line above the cards. Use a compact card layout with consistent actions and supporting details. Show the requester's avatar and name only when they differ from the signed-in person. Share question controls, including a radio option for Other that reveals a text field when selected. **Reason and benefit** People can scan their queue and complete requests without losing the surrounding task or creating separate drafts for the same review. **Breaking changes** The default inbox view becomes personal. The all-assignee and shared views remain available. Card close menus distinguish personal archive and snooze from shared withdrawal. **Additional context** Refs #20959, #19363, and #19520. Refs #20268 for related actionable-request work. This stack adds personal routing and shared controls. ROADMAP.md includes Multiple Human Users and Agent Reviews and Approvals. ## What Changed - Add personal, unassigned, company, all-assignee, and archived inbox views. Add claim, transfer, personal close actions, receipts, and history controls. - Use compact decision cards with a single count line, one-pixel borders, and equal space above, below, and to the right of each primary action. - Open artifacts and synchronized confirmation/approval controls in a shared side panel. Share their revision drafts and action state with the task thread. Other requests keep one editable form on the inbox card while reviewing an artifact. - Make Other match the question options and reveal its field only when selected. Apply this to inbox and task question cards. - Hide self-requester labels, space agent avatars, and use the standard canceled status icon for withdrawn requests. - Use connector logos in connector cards. Keep the connector promotion background and sidebar border continuous. - Add company and project decision-owner controls and document the updated inbox behavior. ## Verification - The complete [GitHub Actions CI matrix](https://github.com/paperclipai/paperclip/actions/runs/43141559641) passes on `8d81a75e49b518fff6b6ff4c23dd67979b0b97ee` (Linux/Node 24: typecheck, build, general and serialized tests, Runner support, browser shards, and aggregate gates). Greptile is 5/5 on that exact head with zero open findings, and the security scan passes. - Local UI typechecking passes. Eight focused suites pass 382 tests: 236 inbox/review/question/connector tests plus all 146 composer tests. Regressions passed red to green for attachment links, prompt rendering, single-form artifact review, connector scope copy, accessible headings, and the composer test harness's missing theme provider. The final commit changes only that test harness; production code is unchanged from `59d015833f`. - Browser acceptance on the production implementation confirms preserved selected answers with one editable question form, accessible Markdown prompts, inert image references, accurate connector scope copy, native PDF downloads, image sidebar previews, and Open file requesting the attachment endpoint while preserving the inbox URL. Request reads and file responses were intercepted; no question answers were written. The preview is healthy on the final head. - Visual and interaction checks cover Other radio behavior in both themes and on mobile, the loaded Google Calendar logo, and 20px above, below, and to the right of the primary action across all 23 visible cards. The affected desktop/mobile navigation and sidebar specs pass locally and in the final CI browser matrix. - Real-editor browser checks confirm Ctrl/Cmd+Enter cannot bypass another person's confirmation. Cancel preserves the draft and unlocks silently; Continue submits once. Approval write failures remain visible. - `pnpm verify` returns exit 2 because DESIGN.md requires broader coverage; the final full CI matrix supplies every requested gate. Maps and Storybook catalog structural checks pass. The routing foundation #20959 merged after passing 249 database tests, server typechecking, full CI, Greptile 5/5, and security scanning. Its backend and SDK registry are preserved. - Demo data is retained for testing; database suites and browser specs use separate disposable databases. ## Risks - The inbox uses the routing contracts merged in #20959. Personal filters and history affect shared task entry points; the affected controls are included in local regression coverage and full CI. - Personal defaults and close-menu wording change inbox behavior. Existing resolver permissions still control shared actions. - Shared revision state and live invalidation affect two surfaces. Focused tests cover draft synchronization, action locks, and incoming updates. - Visual changes use the existing design tokens and component primitives. ## Model Used OpenAI GPT-6 through Codex. Used repository tools, code execution, and browser checks. This session does not expose a more specific runtime model ID or its context-window size. ## 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 relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run focused tests locally and they pass - [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 any 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: Scott Tong <scott@scottsmbpm5max.lan> Co-authored-by: Paperclip <noreply@paperclip.ing>
752 lines
26 KiB
TypeScript
752 lines
26 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 { NeedsYouPanel } from "@/components/coordinator/NeedsYouCardKit";
|
|
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";
|
|
/** A decision card's ask already is this (single) question's prompt. */
|
|
promptStated?: boolean;
|
|
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",
|
|
promptStated = false,
|
|
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<HTMLDivElement>(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() {
|
|
if (disabled || working || inputUploading) return;
|
|
const active = !multiple || !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) {
|
|
if (cause instanceof DOMException && cause.name === "AbortError") return;
|
|
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();
|
|
}
|
|
// A Needs You decision card puts the question in its inset panel under the
|
|
// card's ask, numbered when there are several (PAP-775).
|
|
const decision = presentation === "decision";
|
|
const body = <>
|
|
{questionSet.description ? (
|
|
<div
|
|
role="region"
|
|
aria-label="Question context"
|
|
tabIndex={0}
|
|
className={cn("max-h-96 overflow-auto text-muted-foreground", decision ? "text-xs" : "mb-3 text-sm")}
|
|
>
|
|
<MarkdownBody mediaMode="reference" linkIssueReferences={false}>{questionSet.description}</MarkdownBody>
|
|
</div>
|
|
) : null}
|
|
{question.answerMode === "text" && !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={cn("flex justify-end text-xs text-muted-foreground", !decision && "mb-2")}>
|
|
{pagination}
|
|
</div>
|
|
)
|
|
) : null}
|
|
<div>
|
|
{question.header && !decision ? (
|
|
<p className="mb-1 text-xs font-medium text-muted-foreground">
|
|
{question.header}
|
|
</p>
|
|
) : null}
|
|
<div ref={promptRef} tabIndex={-1} className={cn("leading-5", decision ? "text-(length:--text-compact)" : "text-sm", decision && promptStated && "sr-only")}>
|
|
<div id={`${id}-${question.id}-prompt`} className="flex items-start gap-1 font-medium text-foreground">
|
|
{decision && questionSet.questions.length > 1 ? <span>{page + 1}.</span> : null}
|
|
<MarkdownBody mediaMode="reference" linkIssueReferences={false} className={cn("min-w-0", decision && "text-(length:--text-compact)")}>{question.prompt}</MarkdownBody>
|
|
</div>
|
|
{decision ? <span aria-hidden className="text-muted-foreground"> · {question.required ? "Required" : "Optional"}</span> : null}
|
|
</div>
|
|
{question.helpText ? (
|
|
<p className="mt-1 text-xs leading-4 text-muted-foreground">
|
|
{question.helpText}
|
|
</p>
|
|
) : null}
|
|
</div>
|
|
{question.answerMode === "text" ? (
|
|
<div className={decision ? undefined : "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={decision ? "Add context for the agent…" : "Write your answer"}
|
|
imageUploadHandler={imageUploadHandler}
|
|
mentions={mentions}
|
|
autoFocus={!decision}
|
|
onUploadingChange={setInputUploading}
|
|
onSubmit={() => {
|
|
progressOrSubmit();
|
|
}}
|
|
attachAriaLabel={`Attach image to answer for ${question.prompt}`}
|
|
/>
|
|
</div>
|
|
) : (
|
|
<div
|
|
className={cn("grid gap-1.5", !decision && "mt-3")}
|
|
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}
|
|
</>;
|
|
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);
|
|
}}
|
|
>
|
|
{decision ? <NeedsYouPanel>{body}</NeedsYouPanel> : body}
|
|
<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>
|
|
);
|
|
}
|