Files
PaperClipAI/server/src/services/chat-slack-native-modal.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

689 lines
24 KiB
TypeScript

import { createHmac } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import type { AskUserQuestionsInteraction } from "@paperclipai/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
buildChatQuestionFormModal,
chatQuestionFormActionRecords,
chatQuestionFormDenialResponse,
createChatQuestionFormDraft,
parseChatQuestionFormSubmitTokenPayload,
validateChatQuestionFormSubmission,
} from "./chat-question-forms.js";
import {
createChatSdkEndpointRuntime,
type ChatSdkEndpointRuntime,
type ChatSdkRuntimeCallbacks,
} from "./chat-sdk-runtime.js";
import type {
ChatSdkStatePersistence,
ChatSdkStateRecord,
ChatSdkStateScope,
} from "./chat-sdk-state.js";
const signingSecret = "synthetic-slack-modal-signing-secret";
const channelId = "C-MODAL";
const threadTs = "1788.100";
const messageTs = "1788.200";
const userId = "U-OPERATOR";
const botUserId = "U-PAPERCLIP-BOT";
type SubmitCallback = NonNullable<ChatSdkRuntimeCallbacks["onModalSubmit"]>;
type SubmitEvent = Parameters<SubmitCallback>[0];
function formFixture(configure?: (interaction: AskUserQuestionsInteraction) => void) {
const interaction: AskUserQuestionsInteraction = {
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: new Date().toISOString(),
updatedAt: new Date().toISOString(),
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" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
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" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
required: true,
answerMode: "text",
textValidation: { minLength: 3, maxLength: 500 },
},
],
},
},
};
configure?.(interaction);
const draft = createChatQuestionFormDraft(interaction)!;
const payload = parseChatQuestionFormSubmitTokenPayload(
chatQuestionFormActionRecords(draft, {
companyId: interaction.companyId,
endpointId: "endpoint-slack-modal",
conversationId: "conversation-slack-modal",
publicationId: "publication-slack-modal",
})[1]!.payload,
)!;
const modal = buildChatQuestionFormModal(
interaction,
draft.submitActionId,
payload,
)!;
return { interaction, draft, payload, modal };
}
function memoryPersistence(): ChatSdkStatePersistence {
const rows = new Map<string, ChatSdkStateRecord>();
const keyFor = (scope: ChatSdkStateScope, key: string) =>
JSON.stringify([scope.companyId, scope.endpointId, key]);
return {
async read(scope, key) {
return rows.get(keyFor(scope, key)) ?? null;
},
async compareAndSet(input) {
const key = keyFor(input, input.key);
const previous = rows.get(key);
if ((previous?.version ?? null) !== input.expectedVersion) return false;
rows.set(key, {
value: input.value,
expiresAt: input.expiresAt,
version: (previous?.version ?? 0) + 1,
});
return true;
},
async deleteIfVersion(input) {
const key = keyFor(input, input.key);
if (rows.get(key)?.version !== input.expectedVersion) return false;
return rows.delete(key);
},
};
}
function signedRequest(payload: unknown, secret = signingSecret) {
const body = new URLSearchParams({
payload: JSON.stringify(payload),
}).toString();
const timestamp = String(Math.floor(Date.now() / 1_000));
const signature = `v0=${createHmac("sha256", secret).update(`v0:${timestamp}:${body}`).digest("hex")}`;
return new Request("https://paperclip.test/webhooks/slack", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-slack-request-timestamp": timestamp,
"x-slack-signature": signature,
},
body,
});
}
interface SlackView {
callback_id: string;
private_metadata: string;
blocks: Array<{
type: string;
block_id: string;
element: {
type: string;
action_id: string;
options?: Array<{ text: { text: string }; value: string }>;
};
}>;
}
function submission(view: SlackView) {
const select = view.blocks.find(
(block) => block.element?.type === "static_select",
)!;
const text = view.blocks.find(
(block) => block.element?.type === "plain_text_input",
)!;
const selected = select.element.options!.find(
(option) => option.text.text === "Production",
)!;
return {
type: "view_submission",
team: { id: "T-PAPERCLIP" },
user: { id: userId, username: "operator", name: "Operator Name" },
view: {
id: "V-MODAL",
callback_id: view.callback_id,
private_metadata: view.private_metadata,
state: {
values: {
[select.block_id]: {
[select.element.action_id]: {
type: "static_select",
selected_option: selected,
},
},
[text.block_id]: {
[text.element.action_id]: {
type: "plain_text_input",
value: " Add regional failover ",
},
},
},
},
},
};
}
describe("Slack native multi-question modal adapter-to-runtime boundary", () => {
const runtimes: ChatSdkEndpointRuntime[] = [];
const servers: Server[] = [];
const unexpectedRequests: string[] = [];
afterEach(async () => {
await Promise.all(runtimes.splice(0).map((runtime) => runtime.shutdown()));
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
server.closeAllConnections();
}),
),
);
expect(unexpectedRequests.splice(0)).toEqual([]);
});
async function harness(
options: {
configureForm?: (interaction: AskUserQuestionsInteraction) => void;
onSubmit?: SubmitCallback;
persistence?: ChatSdkStatePersistence;
endpointId?: string;
companyId?: string;
} = {},
) {
const form = formFixture(options.configureForm);
const views: SlackView[] = [];
const openTriggers: Array<string | null> = [];
const apiMethods: string[] = [];
// Only the provider HTTP boundary is substituted. The installed adapter,
// signed-envelope verification, Chat SDK, modal state and runtime stay real.
// Application callbacks observe input/use the real pure form validator;
// they do not stand in for DB authorization or native continuation proof.
const server = createServer(async (request, response) => {
let body = "";
for await (const chunk of request) body += String(chunk);
const method = request.url?.split("/").at(-1) ?? "";
const params = new URLSearchParams(body);
apiMethods.push(method);
let result: unknown;
if (method === "conversations.replies") {
result = {
ok: true,
messages: [
{
type: "message",
ts: messageTs,
thread_ts: threadTs,
channel: channelId,
user: botUserId,
text: "Deployment details",
},
],
};
} else if (method === "users.info") {
result = {
ok: true,
user: {
id: params.get("user"),
name: "paperclip-agent",
real_name: "Paperclip Agent",
is_bot: true,
profile: { display_name: "Paperclip Agent" },
},
};
} else if (method === "views.open") {
views.push(JSON.parse(params.get("view")!) as SlackView);
openTriggers.push(params.get("trigger_id"));
result = { ok: true, view: { id: "V-MODAL" } };
} else {
unexpectedRequests.push(method);
result = { ok: false, error: "unexpected_test_provider_method" };
}
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify(result));
});
servers.push(server);
await new Promise<void>((resolve) =>
server.listen(0, "127.0.0.1", resolve),
);
const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/`;
const validations: ReturnType<typeof validateChatQuestionFormSubmission>[] =
[];
const validate = (event: SubmitEvent) =>
validateChatQuestionFormSubmission({
callbackId: event.event.callbackId,
privateMetadata: event.event.privateMetadata,
values: event.event.values,
interaction: form.interaction,
payload: form.payload,
});
const onSubmit = vi.fn<SubmitCallback>(
options.onSubmit ??
((event) => {
const result = validate(event);
validations.push(result);
return result.ok
? { action: "clear" }
: result.code === "invalid_form"
? { action: "errors", errors: result.fieldErrors }
: chatQuestionFormDenialResponse();
}),
);
const onAction = vi.fn<NonNullable<ChatSdkRuntimeCallbacks["onAction"]>>(
async (event) => {
expect(event.event.actionId).toBe(form.draft.openActionId);
await event.event.openModal(form.modal);
},
);
const runtime = createChatSdkEndpointRuntime({
companyId: options.companyId ?? form.interaction.companyId,
endpointId: options.endpointId ?? "endpoint-slack-modal",
callbacks: { onMessage() {}, onAction, onModalSubmit: onSubmit },
logger: "silent",
persistence: options.persistence ?? memoryPersistence(),
providerConfig: {
provider: "slack",
userName: "paperclip-agent",
credentials: {
apiUrl,
botToken: "xoxb-synthetic",
botUserId,
signingSecret,
},
},
});
runtimes.push(runtime);
await runtime.initialize();
const open = async () => {
const response = await runtime.handleWebhook(
signedRequest({
type: "block_actions",
team: { id: "T-PAPERCLIP" },
user: { id: userId, username: "operator", name: "Operator Name" },
channel: { id: channelId },
container: {
type: "message",
channel_id: channelId,
message_ts: messageTs,
thread_ts: threadTs,
},
message: { ts: messageTs, thread_ts: threadTs },
actions: [
{ action_id: form.draft.openActionId, value: form.interaction.id },
],
trigger_id: "synthetic-trigger",
}),
);
expect(response.status).toBe(200);
expect(views).toHaveLength(1);
return views[0]!;
};
return {
form,
runtime,
onAction,
onSubmit,
validations,
views,
openTriggers,
apiMethods,
open,
validate,
};
}
it("sends the full prompt, context and editable draft through the real Slack adapter", async () => {
const test = await harness({ configureForm(current) {
current.summary = "The migration checks passed; one detail remains.";
current.payload.questionSet!.description = "Tell us which agent failed.";
current.payload.questionSet!.questions[1]!.header = "Reproduction details";
current.payload.questions[0]!.options[0]!.description = "Complete option explanation. ".repeat(8);
current.payload.questionSet!.questions[0]!.options![0]!.recommended = true;
current.payload.questions[1]!.helpText = "Send the agent link and error text, if available. ".repeat(8);
current.payload.questionSet!.questions[1]!.initialText = "Editable starting answer";
} });
const view = await test.open();
const wire = JSON.stringify(view);
expect(wire).toContain(test.form.interaction.summary);
expect(wire).toContain(test.form.interaction.payload.questionSet!.description);
expect(wire).toContain(test.form.interaction.payload.questions[1]!.helpText!.trim());
expect(wire).toContain("Reproduction details");
expect(wire).toContain(test.form.interaction.payload.questions[0]!.options[0]!.description!.trim());
expect(wire).toContain("recommended");
const text = view.blocks.find(block => block.element?.type === "plain_text_input");
expect(text?.element).toMatchObject({ initial_value: "Editable starting answer" });
const response = await test.runtime.handleWebhook(signedRequest(submission(view)));
expect(await response.json()).toEqual({ response_action: "clear" });
expect(test.validations).toEqual([{ ok: true, answers: expect.any(Array) }]);
});
it("round-trips the actual Paperclip modal, opaque metadata and Slack state into canonical answers", async () => {
const test = await harness();
const view = await test.open();
expect(view.callback_id).toBe(test.form.draft.submitActionId);
expect(test.openTriggers).toEqual(["synthetic-trigger"]);
expect(view).toMatchObject({
type: "modal",
title: { type: "plain_text", text: "Deployment details" },
submit: { type: "plain_text", text: "Continue" },
});
const metadata = JSON.parse(view.private_metadata);
expect(metadata).toEqual({
c: expect.any(String),
m: test.form.draft.submitActionId,
});
expect(metadata.c).not.toBe(metadata.m);
expect(view.blocks.map((block) => block.block_id)).toEqual(
test.form.draft.fields.map((field) => field.fieldId),
);
expect(
view.blocks.every((block) => block.block_id === block.element.action_id),
).toBe(true);
const wire = JSON.stringify(view);
for (const canonical of [
test.form.interaction.id,
test.form.interaction.companyId,
'"environment"',
'"reason"',
'"production"',
]) {
expect(wire).not.toContain(canonical);
}
const response = await test.runtime.handleWebhook(
signedRequest(submission(view)),
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ response_action: "clear" });
expect(test.onSubmit).toHaveBeenCalledOnce();
const event = test.onSubmit.mock.calls[0]![0];
expect(event).toMatchObject({
endpointId: "endpoint-slack-modal",
provider: "slack",
event: {
callbackId: test.form.draft.submitActionId,
privateMetadata: test.form.draft.submitActionId,
viewId: "V-MODAL",
user: { userId, userName: "operator", fullName: "Operator Name" },
relatedThread: { id: `slack:${channelId}:${threadTs}` },
relatedMessage: { id: messageTs },
},
});
expect(event).not.toHaveProperty("transport");
expect(test.validations).toEqual([
{
ok: true,
answers: [
{ questionId: "environment", optionIds: ["production"] },
{
questionId: "reason",
optionIds: [],
otherText: "Add regional failover",
},
],
},
]);
expect(test.apiMethods).toEqual([
"conversations.replies",
"users.info",
"views.open",
]);
});
it("maps field errors to actual Slack block IDs and retains the private token after context consumption", async () => {
const test = await harness();
const view = await test.open();
const submitted = submission(view);
const field = view.blocks.find(
(block) => block.element?.type === "plain_text_input",
)!;
submitted.view.state.values[field.block_id]![field.element.action_id] = {
type: "plain_text_input",
value: "x",
};
const invalid = await test.runtime.handleWebhook(signedRequest(submitted));
expect(await invalid.json()).toEqual({
response_action: "errors",
errors: { [field.block_id]: "Enter at least 3 characters" },
});
const corrected = await test.runtime.handleWebhook(
signedRequest(submission(view)),
);
expect(await corrected.json()).toEqual({ response_action: "clear" });
expect(test.onSubmit).toHaveBeenCalledTimes(2);
expect(test.onSubmit.mock.calls[0]![0].event.relatedThread?.id).toBe(
`slack:${channelId}:${threadTs}`,
);
expect(test.onSubmit.mock.calls[1]![0].event.relatedThread).toBeUndefined();
expect(test.onSubmit.mock.calls[1]![0].event.privateMetadata).toBe(
test.form.draft.submitActionId,
);
expect(test.validations[1]?.ok).toBe(true);
expect(test.apiMethods).toEqual([
"conversations.replies",
"users.info",
"views.open",
]);
});
it.each([
"callback",
"private_metadata",
"extra_field",
"canonical_option",
] as const)(
"does not promote a %s substitution into canonical answers",
async (mode) => {
const test = await harness();
const view = await test.open();
const submitted = submission(view);
if (mode === "callback")
submitted.view.callback_id = `pcfs:${"A".repeat(22)}`;
if (mode === "private_metadata")
submitted.view.private_metadata = JSON.stringify({
...JSON.parse(view.private_metadata),
m: `pcfs:${"B".repeat(22)}`,
});
if (mode === "extra_field")
submitted.view.state.values.extra = {
extra: { type: "plain_text_input", value: "injected" },
};
if (mode === "canonical_option") {
const field = view.blocks.find(
(block) => block.element?.type === "static_select",
)!;
submitted.view.state.values[field.block_id]![field.element.action_id] =
{
type: "static_select",
selected_option: {
text: { text: "Production" },
value: "production",
},
};
}
const response = await test.runtime.handleWebhook(
signedRequest(submitted),
);
expect(response.status).toBe(200);
const body = (await response.json()) as { response_action: string };
expect(body.response_action).toBe(
mode === "canonical_option" || mode === "extra_field"
? "errors"
: "clear",
);
expect(test.validations).toHaveLength(1);
expect(test.validations[0]?.ok).toBe(false);
},
);
it("returns 503 after a swallowed callback failure and delivers the exact retry without SDK dedupe", async () => {
const onSubmit = vi
.fn<SubmitCallback>()
.mockRejectedValueOnce(new Error("synthetic durable callback failed"))
.mockResolvedValue({ action: "clear" });
const test = await harness({ onSubmit });
const view = await test.open();
const submitted = submission(view);
const failed = await test.runtime.handleWebhook(signedRequest(submitted));
expect(failed.status).toBe(503);
expect(failed.headers.get("retry-after")).toBe("1");
expect(await failed.text()).not.toContain(
"synthetic durable callback failed",
);
const retry = await test.runtime.handleWebhook(signedRequest(submitted));
expect(retry.status).toBe(200);
expect(await retry.json()).toEqual({ response_action: "clear" });
expect(test.onSubmit).toHaveBeenCalledTimes(2);
const first = test.onSubmit.mock.calls[0]![0].event;
const second = test.onSubmit.mock.calls[1]![0].event;
expect(first.relatedThread).toBeDefined();
expect(second.relatedThread).toBeUndefined();
expect(second.values).toEqual(first.values);
expect(second.privateMetadata).toBe(first.privateMetadata);
expect(second.callbackId).toBe(first.callbackId);
expect(second.user).toEqual(first.user);
expect(test.validate(test.onSubmit.mock.calls[1]![0]).ok).toBe(true);
});
it("does not return a success response before a held modal callback settles", async () => {
let entered!: () => void;
const observed = new Promise<void>((resolve) => {
entered = resolve;
});
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
const test = await harness({
onSubmit: async () => {
entered();
await held;
return { action: "clear" };
},
});
const view = await test.open();
let returned = false;
const pending = test.runtime
.handleWebhook(signedRequest(submission(view)))
.then((response) => {
returned = true;
return response;
});
try {
await observed;
expect(returned).toBe(false);
} finally {
release();
expect((await pending).status).toBe(200);
}
});
it("rejects an invalid signature without consuming context or calling the form handler", async () => {
const test = await harness();
const view = await test.open();
expect(
(
await test.runtime.handleWebhook(
signedRequest(submission(view), "wrong-secret"),
)
).status,
).toBe(401);
expect(test.onSubmit).not.toHaveBeenCalled();
expect(
(await test.runtime.handleWebhook(signedRequest(submission(view))))
.status,
).toBe(200);
expect(test.onSubmit.mock.calls[0]![0].event.relatedThread).toBeDefined();
});
it("does not borrow another endpoint's modal context or replace the signed submitter with the opener", async () => {
const persistence = memoryPersistence();
const first = await harness({ persistence });
const view = await first.open();
const second = await harness({
persistence,
endpointId: "endpoint-other",
companyId: "company-other",
onSubmit: () => chatQuestionFormDenialResponse(),
});
const submitted = submission(view);
submitted.user.id = "U-DIFFERENT-SUBMITTER";
expect(
(await second.runtime.handleWebhook(signedRequest(submitted))).status,
).toBe(200);
expect(first.onSubmit).not.toHaveBeenCalled();
expect(second.onSubmit.mock.calls[0]![0]).toMatchObject({
endpointId: "endpoint-other",
event: { user: { userId: "U-DIFFERENT-SUBMITTER" } },
});
expect(
second.onSubmit.mock.calls[0]![0].event.relatedThread,
).toBeUndefined();
expect(second.apiMethods).toEqual([]);
await first.runtime.handleWebhook(signedRequest(submitted));
expect(first.onSubmit.mock.calls[0]![0].event.relatedThread?.id).toBe(
`slack:${channelId}:${threadTs}`,
);
expect(first.onSubmit.mock.calls[0]![0].event.user.userId).toBe(
"U-DIFFERENT-SUBMITTER",
);
// Actual DB link/token authorization remains the downstream service's
// responsibility; a private token or SDK thread context is not that grant.
});
});