Files
PaperClipAI/server/src/services/chat-question-forms.test.ts
T
DottaandPaperclip 7ae81c9fa7 fix(slack): support rich questions and complete review delivery (#17255)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Questions and review decisions must work in the conversation where a
task started.
> - Slack omitted question context and did not publish several review
kinds.
> - Some answers saved in Paperclip also lost their authorized
continuation or their final Slack reply.
> - A settled card and a successful run did not prove that the user
received the result.
> - This pull request preserves complete questions and follows the
existing answer and delivery receipts through continuation.
> - Users can read the request, submit an authorized decision, and
receive the resumed task's result in the same conversation.

## Linked Issues or Issue Description

Refs #17045 and #17218.

**What happened?**

Slack question cards could omit instructions and editable starting text.
Checkbox reviews, item verdicts, task suggestions, and connection
requests had no publication path. Complex question answers submitted in
Paperclip could fail continuation authorization. Several review
continuations completed without delivering their result to Slack.

**Expected behavior**

Show the actual question and context. Use native Slack controls when
they preserve the form contract. Otherwise provide an explicit Paperclip
review link. Persist one authorized response, resume through the
existing delivery path, settle the card, and deliver the useful result
to its originating conversation.

**Steps to reproduce**

1. Start a task in Slack and ask a text or choice question with
instructions and help text.
2. Submit native text and choice responses, then submit a complex form
through Paperclip.
3. Accept a checklist, submit item decisions, select suggested tasks, or
decline a connection request.
4. Inspect the saved answer, continuation run, original Slack card, and
final Slack reply independently.

## What Changed

- Preserve full prompts, context, descriptions, recommendations, help,
and editable starting text. Use direct buttons for short choices, inline
searchable selects for longer lists, and native checkboxes with explicit
submission for multiple choices.
- Add native custom-answer and validated-text modals, ordinary
confirmation buttons, checklist decisions, per-item verdicts with
reasons, suggested-task creation/dismissal, and connection decline. Keep
governed approvals, permission grants, and forms that cannot be
represented faithfully in the full Paperclip review surface.
- Keep Slack-specific canonical-validation feedback in its owning
platform module. Shared callbacks delegate without interpreting provider
presentation.
- Reuse the existing canonical interaction transactions, callback
receipts, publication queue, and continuation delivery. Share ordinary
confirmation handling across Telegram and Slack. Recheck current
authorization and commit response receipts atomically.
- Settle cards with the saved answer and remove stale controls. Ignore
passive Slack link callbacks so opening a task does not display a false
answer error.
- Validate exact multi-select receipt mappings during native
continuation. Recover automation-origin connection replies from their
published prompt after validating the durable connection receipt.
- Keep oversized multi-select handoffs free of unused native tokens, and
retain the complete Paperclip form for 101–128 choices plus Other. Make
the original-conversation audience explicit before submitting a Slack
modal.
- Add rollback, provider serialization, callback, continuation, and
negative authorization regressions. Update the connector playbook and
feature/access maps. No React or application UI changes are included.
- Add a durable Q01–Q11 qualification index and provider coverage
matrix. Require distinct functional, good-experience, and
best-available-control assessments; real unanswered/answering/settled
evidence; saved results, continuation and navigation proof; and retained
failures. Mark other providers unaudited rather than assuming Slack
parity.

## Verification

Candidate: `e0017d446b1016a38d65382366cd1408cce33039`. The
eleven-core-format live Slack gallery is pinned to
`c3d458b2a06b660448940fd8cf33c5906f0058d5`; subsequent boundary fixes
and the sharing notice have automated verification, not new live
screenshots.

- Real Slack UI testing covered all 11 formats: text, closed choice,
long single select, multiple choices, choices with a custom answer,
pattern-validated text, confirmation, checklist, item verdicts,
suggested tasks, and connection requests. Each has
unanswered/answering/answered screenshots as applicable, an inspected
saved result, one continuation, and an individual experience review in
the local HTML gallery.
- The dedicated private QA app/channel used signed callbacks to the
local candidate. A separately approved password-protected, read-only
preview proved connection-review, suggested-task review, and
created-task navigation. Anonymous access, writes, and credential routes
were denied. No OAuth grant was attempted.
- Real testing exposed and repaired a multi-select continuation failure
and a misleading error on link-button clicks. Failed attempts remain in
the evidence. The final navigation replay opened the exact pending
connection request and declined it in Slack without granting access.
Suggested-task creation produced the selected child with the correct
parent and description.
- Final review-fix verification: **32 form tests**, **28
provider/form-rendering tests**, **30 publication tests**, and **171
native continuation/authorization tests** passed. Earlier **3
atomic-resolution rollback**, **9 targeted
callback/publication/Telegram**, and **28 review-continuation** cases
passed. The final Slack/Teams modal subset also passed. The
automation-origin connection cases, 101/128 custom-choice cases, and
oversized multi-select continuation reproduced before their fixes and
passed afterward; failing logs remain retained. These counts describe
relevant runs, not a reliability percentage.
- CI on `b5885b85fd` exposed a test fixture that assumed every Slack
modal block was an input; the new sharing notice correctly renders a
non-input block. The fixture now selects input blocks safely. The exact
signed-modal correction/one-continuation test passed locally, together
with 14 Slack form/modal tests. The failing CI log and its specific
cause remain recorded.
- `pnpm -r typecheck` and `pnpm build` passed. Server typechecking was
repeated after the final source changes. Map and module-boundary checks
and `git diff --check` passed.
- The full `pnpm test:run` was attempted and stopped after repeated
embedded PostgreSQL semaphore exhaustion on this host. Its 1,395-test
chat suite found two stale native-control assertions; both were
corrected and re-tested in a focused run. Focused database suites used
separate disposable databases on existing local PostgreSQL. The full
suite is not claimed green; new-head CI must complete before merge.
- Final-head CI passed on `e0017d446b1016a38d65382366cd1408cce33039`:
all test/build jobs and required `ci / verify` and `ci / e2e` gates are
green
([run](https://github.com/paperclipai/paperclip/actions/runs/40115430194)).
Greptile and Ponytail both reviewed this exact head at 5/5, the security
scan passed, and all review threads are resolved.
- All three QA app callbacks were restored to staging. Both temporary
tunnels and local proxies were closed. The local endpoint was archived
and its local credential copies removed. The candidate app was stopped.

Limits: provider execution used a deterministic Claude protocol fixture,
not an LLM. This is local real-provider UX proof, not deployed staging
or broader Codie/Claude qualification. The public preview intentionally
blocked ancillary artifact routes, so its destination pages could show a
partial-history warning. The complete permission-grant flow and every
oversized/mixed-form branch were not driven manually. Earlier fixture,
test, and provider failures remain recorded.

## Risks

- New reply routes require durable origin proof. Incorrect receipt
matching could lose a reply or route it incorrectly. Tests cover
missing, forged, mismatched, and revoked authority.
- Governed forms keep their Paperclip resolution checks. This change
does not grant new approval authority to Slack.
- Existing completed review results can become deliverable through the
repaired publication path without another provider run.
- No schema, lockfile, workflow, public task-status model, or
runtime-instruction change is included. This branch is not deployed.

## Model Used

OpenAI Codex, GPT-6 family, with code execution and tool use. The exact
backend model ID and context-window size are not exposed in this
session.

## 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 linked existing issues or 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 on the new head
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
on the new head
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-24 10:29:15 -07:00

805 lines
28 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { AskUserQuestionsInteraction } from "@paperclipai/shared";
import { modalToAdaptiveCard } from "@chat-adapter/teams/modals";
import { modalToDiscordPayload } from "@chat-adapter/discord";
import {
buildChatQuestionFormModal,
chatQuestionFormActionRecords,
chatQuestionFormDenialResponse,
chatQuestionFormValidationResponse,
claimChatQuestionFormSubmission,
completeChatQuestionFormSubmission,
createChatQuestionFormDraft,
isChatQuestionFormOpenActionId,
isChatQuestionFormSubmitActionId,
parseChatQuestionFormOpenTokenPayload,
parseChatQuestionFormSubmitTokenPayload,
validateChatQuestionFormSubmission,
} from "./chat-question-forms.js";
function interaction(
overrides: Partial<AskUserQuestionsInteraction["payload"]> = {},
): AskUserQuestionsInteraction {
return {
id: "11111111-1111-4111-8111-111111111111",
companyId: "22222222-2222-4222-8222-222222222222",
issueId: "33333333-3333-4333-8333-333333333333",
kind: "ask_user_questions",
status: "pending",
continuationPolicy: "wake_assignee",
resolverPolicy: "human_only",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
resolverPolicyProvenance: "explicit",
effectiveResolverPolicySource: "requested",
legacyResolverPolicyAliases: { requested: null, effective: null },
createdAt: "2026-09-05T12:00:00.000Z",
updatedAt: "2026-09-05T12:00:00.000Z",
title: "Deployment details",
payload: {
version: 1,
title: "Deployment details",
submitLabel: "Continue",
questions: [
{
id: "environment",
prompt: "Where should I deploy?",
selectionMode: "single",
required: true,
allowOther: false,
options: [
{ id: "staging", label: "Staging", description: "Internal" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
helpText: "Describe the user-facing change",
selectionMode: "single",
required: true,
allowOther: true,
options: [
{
id: "__paperclip_text__",
label: "Type an answer",
freeText: true,
},
],
},
],
questionSet: {
schema: "paperclip.question_set.v1",
title: "Deployment details",
submitLabel: "Continue",
questions: [
{
id: "environment",
prompt: "Where should I deploy?",
required: true,
answerMode: "single_select",
options: [
{ id: "staging", label: "Staging", description: "Internal" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
helpText: "Describe the user-facing change",
required: true,
answerMode: "text",
textValidation: { minLength: 3, maxLength: 500 },
},
],
},
...overrides,
},
};
}
describe("chat question forms", () => {
it("preserves context, complete help and editable starting text in a native form", () => {
const current = interaction();
current.summary = "General checks passed; one detail is needed.";
current.payload.questionSet!.description = "The answer determines the migration test.";
current.payload.questionSet!.questions[1]!.initialText = "Editable draft";
current.payload.questions[1]!.helpText = "Explain the expected behavior. ".repeat(12);
const draft = createChatQuestionFormDraft(current)!;
const payload = parseChatQuestionFormSubmitTokenPayload(chatQuestionFormActionRecords(draft, {
companyId: current.companyId, endpointId: "endpoint", conversationId: "conversation", publicationId: "publication",
})[1]!.payload)!;
const modal = buildChatQuestionFormModal(current, draft.submitActionId, payload)!;
const shown = JSON.stringify(modal);
expect(shown).toContain(current.summary);
expect(shown).toContain(current.payload.questionSet!.description);
expect(shown).toContain(current.payload.questions[1]!.helpText!.trim());
expect(modal.children.find(child => child.type === "text_input")).toMatchObject({ initialValue: "Editable draft" });
});
it.each([13, 100])("opens a native select for all %i choices", count => {
const current = interaction();
current.payload.questions = [{ ...current.payload.questions[0]!, options: Array.from({ length: count }, (_, index) => ({ id: `choice-${index}`, label: `Choice ${index}` })) }];
current.payload.questionSet!.questions = [{ ...current.payload.questionSet!.questions[0]!, options: current.payload.questions[0]!.options.map(({ id, label }) => ({ id, label })) }];
expect(createChatQuestionFormDraft(current)?.fields[0]).toMatchObject({ kind: "single_select", options: expect.any(Array) });
});
it("makes the original conversation audience explicit before a Slack modal answer", () => {
const current = interaction();
const draft = createChatQuestionFormDraft(current, { nativeProvider: "slack" })!;
const payload = parseChatQuestionFormSubmitTokenPayload(chatQuestionFormActionRecords(draft, {
companyId: current.companyId, endpointId: "endpoint", conversationId: "conversation", publicationId: "publication",
})[1]!.payload)!;
const modal = buildChatQuestionFormModal(current, draft.submitActionId, payload)!;
expect(modal.children[0]).toMatchObject({ type: "text", content: "Your answers will be shared in this Slack conversation." });
});
it.each([100, 101, 128])("keeps all %i custom-choice options reachable", count => {
const current = interaction();
const options = Array.from({ length: count }, (_, index) => ({ id: `choice-${index}`, label: `Choice ${index}` }));
current.payload.questions = [{ ...current.payload.questions[0]!, allowOther: true, options: [...options, { id: "other", label: "Other", freeText: true }] }];
current.payload.questionSet!.questions = [{ ...current.payload.questionSet!.questions[0]!, options, customAnswer: { enabled: true } }];
const draft = createChatQuestionFormDraft(current, { nativeProvider: "slack" });
if (count <= 100) expect(draft?.fields[0]).toMatchObject({ kind: "text" });
else expect(draft).toBeNull();
});
it("keeps an oversized editable starting value in the complete Paperclip form", () => {
const current = interaction();
current.payload.questionSet!.questions[1]!.initialText = "a".repeat(3001);
expect(createChatQuestionFormDraft(current)).toBeNull();
});
it("keeps Discord's 4000-character contract explicit without changing legacy provider limits", () => {
const current = interaction();
current.payload.questionSet!.questions[1]!.textValidation = {
minLength: 1,
maxLength: 4000,
};
const legacy = createChatQuestionFormDraft(current)!;
expect(legacy.fields[1]).toMatchObject({ maxLength: 3000 });
const native = createChatQuestionFormDraft(current, {
nativeProvider: "discord",
})!;
expect(native.fields[1]).toMatchObject({ maxLength: 4000 });
const record = chatQuestionFormActionRecords(native, {
companyId: current.companyId,
endpointId: "endpoint",
conversationId: "conversation",
publicationId: "publication",
})[1]!;
const payload = parseChatQuestionFormSubmitTokenPayload(record.payload)!;
expect(payload.nativeProvider).toBe("discord");
expect(
parseChatQuestionFormSubmitTokenPayload({
...record.payload,
nativeProvider: undefined,
}),
).toBeNull();
const modal = buildChatQuestionFormModal(
current,
native.submitActionId,
payload,
)!;
expect(
modalToDiscordPayload(modal, "11111111-1111-4111-8111-111111111111"),
).toMatchObject({
components: [{ type: 18 }, { type: 18, component: { max_length: 4000 } }],
});
});
it.each([25, 26])(
"supports one Discord select with %i options only when it fits natively",
(count) => {
const current = interaction();
current.payload.questions = [current.payload.questions[0]!];
current.payload.questions[0]!.options = Array.from(
{ length: count },
(_, index) => ({ id: `option-${index}`, label: `Option ${index}` }),
);
current.payload.questionSet!.questions = [
{
id: "environment",
prompt: "Where should I deploy?",
required: true,
answerMode: "single_select",
options: current.payload.questions[0]!.options.map(
({ id, label }) => ({ id, label }),
),
},
];
expect(createChatQuestionFormDraft(current)?.fields).toHaveLength(1);
const draft = createChatQuestionFormDraft(current, {
nativeProvider: "discord",
});
if (count === 26) expect(draft).toBeNull();
else expect(draft?.fields).toHaveLength(1);
},
);
it.each([5, 6])(
"preserves all %i questions or selects explicit non-modal fallback",
(count) => {
const current = interaction();
current.payload.questions = Array.from({ length: count }, (_, index) => ({
...current.payload.questions[1]!,
id: `note-${index}`,
}));
current.payload.questionSet!.questions = current.payload.questions.map(
(question) => ({
id: question.id,
prompt: question.prompt,
required: true,
answerMode: "text" as const,
}),
);
const draft = createChatQuestionFormDraft(current, {
nativeProvider: "discord",
});
if (count === 6) expect(draft).toBeNull();
else expect(draft?.fields).toHaveLength(5);
},
);
function invalidFormFixture() {
const current = interaction();
const now = new Date();
const draft = createChatQuestionFormDraft(current, { now })!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: current.companyId,
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]!.payload,
)!;
const select = payload.fields[0]!;
const text = payload.fields[1]!;
if (select.kind !== "single_select" || text.kind !== "text")
throw new Error("Unexpected fixture fields");
return {
select,
text,
args: {
provider: "microsoft-teams" as const,
callbackId: draft.submitActionId,
interaction: current,
payload,
now,
values: {
[select.fieldId]: select.options[0]!.value,
[text.fieldId]: "x",
},
},
};
}
it("rebuilds only the current invalid Teams form with readable errors and retained draft values", () => {
const { args, select, text } = invalidFormFixture();
const before = structuredClone(args);
const result = chatQuestionFormValidationResponse(args);
expect(result.action).toBe("update");
if (result.action !== "update")
throw new Error("Expected editable Teams form");
expect(result.modal).toMatchObject({
callbackId: args.callbackId,
privateMetadata: args.callbackId,
children: expect.arrayContaining([
expect.objectContaining({
type: "select",
id: select.fieldId,
initialOption: select.options[0]!.value,
}),
expect.objectContaining({
type: "text_input",
id: text.fieldId,
initialValue: "x",
}),
expect.objectContaining({
type: "text",
content:
"What should the release note say?: Enter at least 3 characters",
}),
]),
});
expect(args).toEqual(before);
const visibleErrors = result.modal.children.filter(
(child) => child.type === "text",
);
expect(JSON.stringify(visibleErrors)).not.toContain("pcff:");
expect(JSON.stringify(visibleErrors)).not.toContain(args.interaction.id);
});
it("keeps Slack's original inline field error response unchanged", () => {
const { args, text } = invalidFormFixture();
expect(
chatQuestionFormValidationResponse({ ...args, provider: "slack" }),
).toEqual({
action: "errors",
errors: { [text.fieldId]: "Enter at least 3 characters" },
});
});
it.each([
"callback",
"private_metadata",
"expired",
"answered",
"wrong_interaction",
"valid",
] as const)(
"never refreshes an unauthorized, stale or non-invalid form (%s)",
(mode) => {
const { args, text } = invalidFormFixture();
const input = {
...args,
...(mode === "callback"
? { callbackId: `pcfs:${"A".repeat(22)}` }
: {}),
...(mode === "private_metadata" ? { privateMetadata: "forged" } : {}),
...(mode === "expired"
? { now: new Date(Date.parse(args.payload.expiresAt)) }
: {}),
...(mode === "answered"
? {
interaction: { ...args.interaction, status: "answered" as const },
}
: {}),
...(mode === "wrong_interaction"
? { interaction: { ...args.interaction, id: "other-interaction" } }
: {}),
...(mode === "valid"
? { values: { ...args.values, [text.fieldId]: "Corrected answer" } }
: {}),
};
expect(chatQuestionFormValidationResponse(input)).toEqual({
action: "clear",
});
},
);
it("omits unexpected fields and unrecognized options instead of reflecting provider tokens", () => {
const { args, select, text } = invalidFormFixture();
const result = chatQuestionFormValidationResponse({
...args,
values: {
[select.fieldId]: "unrecognized-provider-choice",
[text.fieldId]: "x",
"private-field-name": "private-extra-value",
},
});
expect(result.action).toBe("update");
if (result.action !== "update")
throw new Error("Expected current form rebuild");
expect(JSON.stringify(result)).not.toContain("private-field-name");
expect(JSON.stringify(result)).not.toContain("private-extra-value");
expect(JSON.stringify(result)).not.toContain(
"unrecognized-provider-choice",
);
expect(
result.modal.children.find((child) => child.type === "select"),
).toMatchObject({ initialOption: undefined });
});
it.each([600, 3001])(
"bounds reflected text without silently truncating a %i-character draft",
(length) => {
const { args, text } = invalidFormFixture();
const value = "x".repeat(length);
const result = chatQuestionFormValidationResponse({
...args,
values: { ...args.values, [text.fieldId]: value },
});
if (result.action !== "update")
throw new Error("Expected editable over-limit draft");
expect(
result.modal.children.find((child) => child.type === "text_input"),
).toMatchObject({ initialValue: value.slice(0, 3000) });
expect(JSON.stringify(result).includes("draft was shortened")).toBe(
length > 3000,
);
},
);
it("keeps a credential-bearing starting draft in Paperclip instead of exposing it to a chat modal", () => {
const current = interaction();
current.payload.questionSet!.questions[1]!.initialText = "xoxb-123456789012345678901234567890";
expect(createChatQuestionFormDraft(current)).toBeNull();
});
it("issues opaque open, submit, field, and option tokens as durable action rows", () => {
const now = new Date("2026-09-05T12:00:00.000Z");
const draft = createChatQuestionFormDraft(interaction(), { now });
expect(draft).not.toBeNull();
expect(isChatQuestionFormOpenActionId(draft?.openActionId)).toBe(true);
expect(isChatQuestionFormSubmitActionId(draft?.submitActionId)).toBe(true);
expect(draft?.fields.map((field) => field.fieldId)).toEqual([
expect.stringMatching(/^pcff:[A-Za-z0-9_-]{22}$/),
expect.stringMatching(/^pcff:[A-Za-z0-9_-]{22}$/),
]);
expect(draft?.expiresAt).toBe("2026-09-12T12:00:00.000Z");
expect(draft?.fields[0]).toMatchObject({
kind: "single_select",
options: [
{ optionId: "staging", value: expect.stringMatching(/^pcfo:/) },
{ optionId: "production", value: expect.stringMatching(/^pcfo:/) },
],
});
const rows = chatQuestionFormActionRecords(draft!, {
companyId: "22222222-2222-4222-8222-222222222222",
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
});
expect(rows).toHaveLength(2);
expect(
rows.map((row) => [row.kind, row.providerActionId, row.status]),
).toEqual([
["question_form_open", draft?.openActionId, "issued"],
["question_form_submit", draft?.submitActionId, "issued"],
]);
expect(parseChatQuestionFormOpenTokenPayload(rows[0]?.payload)).toEqual(
rows[0]?.payload,
);
expect(parseChatQuestionFormSubmitTokenPayload(rows[1]?.payload)).toEqual(
rows[1]?.payload,
);
});
it("builds the Chat SDK TextInput and Select modal without provider-visible canonical ids", () => {
const current = interaction();
const draft = createChatQuestionFormDraft(current)!;
const submitPayload = chatQuestionFormActionRecords(draft, {
companyId: current.companyId,
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]?.payload;
const parsed = parseChatQuestionFormSubmitTokenPayload(submitPayload)!;
const modal = buildChatQuestionFormModal(
current,
draft.submitActionId,
parsed,
);
expect(modal).toMatchObject({
type: "modal",
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
title: "Deployment details",
submitLabel: "Continue",
children: [
{
type: "select",
id: draft.fields[0]?.fieldId,
label: "Where should I deploy?",
options: [
{ label: "Staging", value: expect.stringMatching(/^pcfo:/) },
{ label: "Production", value: expect.stringMatching(/^pcfo:/) },
],
},
{ type: "text", content: "Describe the user-facing change" },
{
type: "text_input",
id: draft.fields[1]?.fieldId,
label: "What should the release note say?",
maxLength: 500,
multiline: true,
},
],
});
const wireJson = JSON.stringify(modal);
expect(wireJson).not.toContain('"id":"environment"');
expect(wireJson).not.toContain('"id":"reason"');
expect(wireJson).not.toContain('"value":"production"');
const teamsCard = modalToAdaptiveCard(
modal! as unknown as Parameters<typeof modalToAdaptiveCard>[0],
);
expect(teamsCard).toMatchObject({
actions: [
{
data: { __callbackId: draft.submitActionId },
type: "Action.Submit",
},
],
body: [
{
type: "Input.ChoiceSet",
id: draft.fields[0]?.fieldId,
choices: [
{ title: "Staging", value: expect.stringMatching(/^pcfo:/) },
{ title: "Production", value: expect.stringMatching(/^pcfo:/) },
],
},
{ type: "TextBlock", text: "Describe the user-facing change" },
{
type: "Input.Text",
id: draft.fields[1]?.fieldId,
isMultiline: true,
},
],
});
});
it("maps only opaque submitted values back to canonical answers", () => {
const current = interaction();
const draft = createChatQuestionFormDraft(current)!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: current.companyId,
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]?.payload,
)!;
const select = payload.fields[0];
const text = payload.fields[1];
if (select?.kind !== "single_select" || text?.kind !== "text") {
throw new Error("fixture produced the wrong form fields");
}
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: current,
payload,
values: {
[select.fieldId]: select.options[1]!.value,
[text.fieldId]: " Add regional failover ",
},
}),
).toEqual({
ok: true,
answers: [
{ questionId: "environment", optionIds: ["production"] },
{
questionId: "reason",
optionIds: [],
otherText: "Add regional failover",
},
],
});
const forged = validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: current,
payload,
values: {
[select.fieldId]: "production",
[text.fieldId]: "Good release note",
},
});
expect(forged).toEqual({
ok: false,
code: "invalid_form",
fieldErrors: { [select.fieldId]: "Choose a valid option" },
});
// Chat SDK 4.39 Teams task modules do not preserve privateMetadata; the
// independently opaque callback id is still the durable lookup key.
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
interaction: current,
payload,
values: {
[select.fieldId]: select.options[0]!.value,
[text.fieldId]: "Teams response",
},
}),
).toMatchObject({ ok: true });
});
it("returns provider field errors for missing, malformed, and injected values", () => {
const current = interaction();
const draft = createChatQuestionFormDraft(current)!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: current.companyId,
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]?.payload,
)!;
const [select, text] = payload.fields;
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: current,
payload,
values: {},
}),
).toEqual({
ok: false,
code: "invalid_form",
fieldErrors: {
[select!.fieldId]: "Choose an option",
[text!.fieldId]: "Enter a response",
},
});
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: current,
payload,
values: { canonicalQuestionId: "production" },
}),
).toMatchObject({ ok: false, code: "invalid_form", fieldErrors: {} });
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: "forged",
interaction: current,
payload,
values: {},
}),
).toEqual({
ok: false,
code: "invalid_callback",
fieldErrors: {},
});
});
it("rejects expired, stale, tampered, and non-native form shapes", () => {
const current = interaction();
const draft = createChatQuestionFormDraft(current, {
now: new Date("2026-09-05T12:00:00.000Z"),
})!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: current.companyId,
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]?.payload,
)!;
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: current,
payload,
now: new Date("2026-09-12T12:00:00.001Z"),
values: {},
}),
).toEqual({ ok: false, code: "expired", fieldErrors: {} });
expect(
validateChatQuestionFormSubmission({
callbackId: draft.submitActionId,
privateMetadata: draft.submitActionId,
interaction: { ...current, status: "answered" },
payload,
values: {},
}),
).toEqual({ ok: false, code: "stale_interaction", fieldErrors: {} });
expect(
parseChatQuestionFormSubmitTokenPayload({
...payload,
formActionId: "pcfs:AAAAAAAAAAAAAAAAAAAAAA",
fields: [{ ...payload.fields[0], fieldId: "environment" }],
}),
).toBeNull();
expect(
validateChatQuestionFormSubmission({
callbackId: "pcfs:AAAAAAAAAAAAAAAAAAAAAA",
privateMetadata: "pcfs:AAAAAAAAAAAAAAAAAAAAAA",
interaction: current,
payload,
values: {},
}),
).toEqual({ ok: false, code: "invalid_callback", fieldErrors: {} });
expect(
parseChatQuestionFormSubmitTokenPayload({
...payload,
fields: [{ ...payload.fields[0], fieldId: "environment" }],
}),
).toBeNull();
expect(
createChatQuestionFormDraft(
interaction({
questions: [current.payload.questions[0]!],
questionSet: {
...current.payload.questionSet!,
questions: [current.payload.questionSet!.questions[0]!],
},
}),
),
).toBeNull();
expect(
createChatQuestionFormDraft(
interaction({
questionSet: {
...current.payload.questionSet!,
questions: [
current.payload.questionSet!.questions[0]!,
{
...current.payload.questionSet!.questions[1]!,
textValidation: { pattern: "^(a+)+$" },
},
],
},
}),
),
).toBeNull();
});
it("acknowledges durable denials without reflecting untrusted callback data", () => {
const draft = createChatQuestionFormDraft(interaction())!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: "22222222-2222-4222-8222-222222222222",
endpointId: "44444444-4444-4444-8444-444444444444",
conversationId: "55555555-5555-4555-8555-555555555555",
publicationId: "66666666-6666-4666-8666-666666666666",
})[1]?.payload,
)!;
expect(chatQuestionFormDenialResponse(payload)).toEqual({
action: "errors",
errors: {
[payload.fields[0]!.fieldId]:
"This form is no longer authorized. Close it and open the linked Paperclip task.",
},
});
expect(chatQuestionFormDenialResponse()).toEqual({ action: "clear" });
});
it("claims a submit token atomically and stores no provider answer values", async () => {
const updates: Array<Record<string, unknown>> = [];
const mutationDb = (returning: Array<{ id: string }>) =>
({
update: () => ({
set: (value: Record<string, unknown>) => {
updates.push(value);
return {
where: () => ({
returning: async () => returning,
}),
};
},
}),
}) as unknown as Parameters<typeof claimChatQuestionFormSubmission>[0];
await expect(
claimChatQuestionFormSubmission(mutationDb([{ id: "action-1" }]), {
actionRowId: "action-1",
principalId: "principal-1",
}),
).resolves.toBe(true);
await expect(
claimChatQuestionFormSubmission(mutationDb([]), {
actionRowId: "action-1",
principalId: "principal-2",
}),
).resolves.toBe(false);
await expect(
completeChatQuestionFormSubmission(
mutationDb([{ id: "action-1" }]) as Parameters<
typeof completeChatQuestionFormSubmission
>[0],
{
actionRowId: "action-1",
interactionId: "11111111-1111-4111-8111-111111111111",
},
),
).resolves.toBe(true);
expect(JSON.stringify(updates)).not.toContain("regional failover");
expect(updates[0]).toMatchObject({
principalId: "principal-1",
status: "processing",
});
expect(updates[2]).toMatchObject({
status: "processed",
result: { code: "question_form_answered" },
});
});
});