mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 09:07:46 +02:00
## Thinking Path > - Paperclip manages AI agents and their work. > - The experimental Runner owns provider processes and durable sessions. > - Pi needs working task execution and human controls. > - The five-PR stack must preserve changes already on master. > - Each layer now carries the complete integrated source for a safe sequential fallback. > - This PR belongs to native GitHub stack #15602, ending at #14956. ## Linked Issues or Issue Description Refs #14436, #14631, #14743 and #14956. Ship Pi 1.0 through the experimental Paperclip Runner. The five PRs are #14921, #14922, #14923, #14924 and #14956. The user authorized the complete merge after checks pass. Existing `pi_local` execution is unchanged. Accounting and wider provider/platform qualification remain deferred. ## What Changed - Recover missing final replies after workspace finalization changes owners, using accepted-turn evidence without rerunning work or granting external-chat publication. - Preserve the admitted Pi instruction root across warm runs, while retaining changed-root rejection. - Give Pi a bounded 15-second default shutdown grace so stop, drain acknowledgement and durable suspension can complete. Explicit deadlines and other providers retain their existing behavior. - Integrate the Pi 1.0 runtime and master contracts. - Use Pi profile 22. Preserve explicit caller-selected models and exact native thinking levels. Keep Pi's wrapper, helper, extension and question/control behavior unchanged from the qualified profile-19 runtime. - Preserve master's Dot lifecycle and consent fields, configured task environment, status guards and current Codex/Claude dependency versions. Cursor stays qualified. Copilot stays pending; profile 17 binds the changed shared protocol validation sources. - Exclude general AWS IAM credentials from Pi static/custom provider bindings and selected task projections; preserve the provider-scoped Bedrock bearer key. Profile 21 is retained as historical provenance. Rust and cloud install probes use the current declaration. - Patch bundled brace-expansion 5.0.9 to the exact official 5.0.12 payload. Pin the patch and complete runtime closures. Include the patch in normal installed setup tooling. Keep the upstream Pi shrinkwrap as provenance and permit only this exact security correction. - Include current attestation files in the Docker build context. Keep the repository lockfile unchanged from master. CI and private image builds resolve manifest changes before their frozen installation. ## Verification - Full local `pnpm -r typecheck` passes, including Runner Rust, server and UI. Focused integration checks pass: 194 Runner admission/environment tests, 63 profile/credential tests with one expected skip, 152 Dot/UI configuration tests, and Pi transcript/notice tests. - Full local `pnpm build` passes on the final source. - Fresh final-source checks pass: all 698 Rust workspace tests (32 binaries), 156 credential/profile/controller tests with one expected skip, Runner TypeScript typecheck, and 20 package/setup/sandbox tests. - The profile-21 Pi materializer passes on the native host with the official pinned Node 24.21.0 and its npm. It verifies all 150 locked packages, the patched dependency and the exact closure. Setup/package bundle tests and UI token gates pass. - The old hashes were reproduced for all three supported targets before calculating the patched graph. New closure hashes are darwin-arm64 `282022db10150c6632b3444df421342e7d534bdf5d5fb1097a2e79d0625a2bcf`, darwin-x64 `64e251e19009f755c0b04f73ce2138246faab71a961b0f13d75ebfcc34bef12e`, and linux-x64 `713b1fdff42fb56a1518bdc084f181d70bee8ebadc3e4b1d76321ed9108c8410`. Independent native platform execution is separate from graph identity reproduction. - Historical cloud qualification remains unchanged: all seven core cases pass on shipping source `10dc43c9ec65d88c2f782d62afb296d09494f215`, harness `1a4408a48cfb5a1f094a311141c257c92cd7a893`, image `sha256:5b3a775b383591bda1b0c1889e509acc70ce7f37c53f09733c81d59037f02280`, and accepted Sonnet 4.6/low fixture. All 215 canonical files and all seven cleanup checks pass independent verification. These are profile-19 results and are not relabeled as fresh profile-22 runs. - Current Pi digest: `sha256:e92078bee3c23bec4100aa589013a44613d054cd686826534025d8019e9f39a9`. [The readiness plan](https://github.com/paperclipai/paperclip/blob/codex/pi-production-readiness/doc/plans/2026-10-02-pi-production-readiness.md) preserves campaign and failed-attempt provenance. - Merge only after every PR's current-head CI and fresh review pass. Linux CI covers the full suites, build and browser tests. The local embedded Postgres API-authority suite cannot start on this macOS/Node 26 host, so Linux CI must confirm that suite. ### Fresh profile-22 core qualification — 2026-10-08 All seven accepted core cases pass canonically on Pi profile 22, with `openrouter/anthropic/claude-sonnet-4.6` and native-confirmed low thinking. This model is a fixture; production accepts the caller's explicit Pi provider/model. Runtime/install source: `3241a992f2a7703e59e97ed0fd3e5d6405de4401`. Frozen accepted harness: `1a4408a48cfb5a1f094a311141c257c92cd7a893`. Immutable cloud image: `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:506f22db7edd78f37c0c40bec1cc084af1850455026dbf467194bfbb8fcef141`. Pi digest: `sha256:e92078bee3c23bec4100aa589013a44613d054cd686826534025d8019e9f39a9`. [Hosted Linux image and clean-install verification](https://github.com/paperclipai/paperclip/actions/runs/37868328023) passes, including all 20 source-bound archives, normal CLI/Pi setup, companion import and the production pack reader. This exact installation source includes the latest master integration and the corrected Pi warm instruction-root fence. Full local typecheck/build and current-head hosted CI verify the final stack. All 13 focused real-root regressions pass. The full local executor suite passed 662 tests; 15 database tests could not start the Mac embedded PostgreSQL service. Hosted Linux CI passes the full required verification and E2E checks. These fresh results keep their own source identity; profile-19 results remain historical. | Core path | Canonical campaign | Retained archive SHA-256 | | --- | --- | --- | | File edit, validation, download and Done | `pi-core22-replyfix-0-1791511228` | 23 files; `a473e8603a3dd4737863291f8d3d1e392391f0b16d433c3e0e0e9d8baf7a97b0` | | Pending question and controller restart | `pi-core22-replyfix-1-1791511376` | 33 files; `6b829c4eb74e1f32a89c692a4ae7130dbfc1c6d3cf13915effe2103d9e242c8e` | | Three-turn session/process/workspace continuity | `pi-core22-replyfix-2-1791511587` | 23 files; `7a87021f8f9a3fdd3c58bb4467f8d82c635e3ea4795d6e75f144d9aa14818df8` | | Four typed questions and browser reconnects | `pi-core22-replyfix-3-1791511881` | 42 files; `9e31755252be1f4f9cb0626c984c142d4d1ae5f5bee3a7af08444db8d12c280a` | | Plan approval and completion | `pi-core22-replyfix-4-1791512031` | 22 files; `a0383ce1aab38e7b5a25ce0e9dd3bebea5c037ebd96ae6b29dae19015da2ae2c` | | Same-turn steering and permission denial | `pi-core22-replyfix-5-1791512261` | 39 files; `c929b8c7070f0b66aedc17e65ca46e6beab1e363926ac9f7e2a75fb250f05949` | | Stop during pending permission | `pi-core22-replyfix-6-1791512390` | 33 files; `7f0a58ae0f4d5bfc76149435f4e322537089c5bd16e7ffe9b5ad71f10a621a07` | All 215 canonical files (28714587 bytes) are independently hash-verified. All seven cleanup grades pass, with no owned runtime process or temporary root after each case. Automatic retries are zero. The owned cloud host stopped normally after retention. The prior profile-22 warm attempt remains failed and separately retained: archive SHA-256 `1e54eba5ec72b50cee1534b23d1d1d4f21a090006b8a64501ba70db972abfde5`. Its original canonical classification is preserved. Diagnosis reproduced a product bug comparing an agent-files root against an unset checkpoint-only field. The fix stores the admitted physical root separately from the adopted per-run collection capability. The real-root regression fails before the fix and passes afterward, including rejection of a changed physical root. Fixture, grader, model and all seven accepted case IDs are unchanged; this fresh campaign tests final-reply publication after file registration first. The intermediate restart attempt also remains failed and retained: archive SHA-256 `5dcaefdf1d17cf4cd54fd4cf810f45e736667392339b8ce7caf08bb4e225277f`. Its original canonical classification is preserved. Pi resumed, wrote the verified answer and completed its task; exact runner suspension was proven, but idle stop consumed about 5.2s and left under 3s for the drain acknowledgement. The Pi-only default shutdown grace is now 15s, preserving a full 5s drain round trip and a finite suspension reserve. Explicit caller deadlines, other provider defaults, literal drain receipts and exact suspension identity checks remain unchanged. The timing regression fails before this correction and passes afterward; all 18 focused settlement tests and Runner typecheck pass. The final-source file attempt is also preserved as failed (`candidate_failure`), archive SHA-256 `db6767b6773ea618997927ac77bdb005a5ac81492c7b9c0ffbc900449f829bc9`. Native edit, validation, exact downloadable artifact and Done/succeeded all passed, and the exact final reply was durably recorded. A workspace recovery owner completed before the live heartbeat reached presentation, leaving that reply absent from task chat. Recovery now materializes only a completed final reply from the accepted turn of an ordinary internal Done task, preserving issue/run/contract binding, suppression, external-chat authorization and same-run deduplication. The database regression covers the generated file-preparation receipt, suppression, unapproved external continuation and replay. Server typecheck and all 49 response-selection tests pass; hosted Linux verifies the database regression because embedded PostgreSQL cannot start on this Mac. The delayed-final-answer database regression passes on [the final root-source Linux server shard](https://github.com/paperclipai/paperclip/actions/runs/37868262553/job/113628594152), alongside 1,108 passing tests. The first root Runner shard had one unchanged durable-resume test exceed its 5-second timeout; the identical top-source shard and the isolated exact test passed. One rerun of that failed job and its required aggregate passed without source or test changes. The original failed job log and the single-rerun receipt remain retained. ### October 9 merge verification Current merge head: `5a8fe63512a7166aaef5cf50065a25008aa8b44b`. All current-head checks pass, including `ci / verify` and `ci / e2e`; exact-head Greptile review is 5/5 with no unresolved threads. Current master conflicts are resolved. The user authorized the maintainer override of the code-owner review gate after these checks. The seven retained live core cases remain bound to source `3241a992f2a7703e59e97ed0fd3e5d6405de4401` and its recorded cloud image. ## Risks - The security correction changes the dependency closure and profile identity. Old sessions must reopen on the new profile. Exact identities and credential bindings fail closed. - The runner remains experimental and requires explicit selection. Legacy Pi Local is unchanged. Caller model IDs pass through; the E2E model is a fixture. - Accounting and the broad platform/provider matrix remain deferred. This merge does not publish a release or deploy a service. ## Model Used OpenAI GPT-6 through Codex assisted with reasoning, repository inspection, editing and tool use. The exact serving ID and context window are not exposed in this session. Final live qualification uses Pi 1.0.0 with `openrouter/anthropic/claude-sonnet-4.6` and native-confirmed low thinking. ## 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 either (a) linked existing issues with `Fixes: #` / `Closes #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run 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: Paperclip <noreply@paperclip.ing>
724 lines
24 KiB
TypeScript
724 lines
24 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } 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 { 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 {
|
|
id: string;
|
|
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({
|
|
id,
|
|
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 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],
|
|
);
|
|
const allValid = Object.values(validationErrors).every(
|
|
(value) => value == null,
|
|
);
|
|
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 }));
|
|
}
|
|
|
|
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) {
|
|
// 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 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 (!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" ? (
|
|
<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 ? (
|
|
<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`}
|
|
className="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
|
|
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={() => {
|
|
if (!inputUploading && currentError == null) 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
|
|
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={() => {
|
|
if (!inputUploading && currentError == null)
|
|
progressOrSubmit();
|
|
}}
|
|
attachAriaLabel={`Attach image to other answer for ${question.prompt}`}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
)}
|
|
{currentError && answerHasValue(answer) ? (
|
|
<p className="mt-2 text-xs text-destructive">{currentError}</p>
|
|
) : null}
|
|
<div aria-live="assertive">
|
|
{error ? (
|
|
<div className="mt-2 rounded-sm border border-destructive/60 bg-destructive/10 px-2.5 py-2 text-sm text-destructive">
|
|
{error.message}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
<div className="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 || (isLastPage ? !allValid : currentError != null)}
|
|
onClick={progressOrSubmit}
|
|
>
|
|
{working === "submit" ? (
|
|
<Loader2 aria-hidden className="h-4 w-4 animate-spin" />
|
|
) : null}
|
|
{isLastPage ? (questionSet.submitLabel ?? "Submit answers") : "Next"}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|