Skip to content

Commit 65ee4b7

Browse files
fix(plugin-approvals)!: the email action-link reject records the reason the approver types (#36695)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBDabPAKG5NwMj6ZcigV2Bbc)_ Fixes #35722 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — nothing under `skills/**` teaches the approval action link or its confirm page (`git grep -i` for "action link", "approvals/act" and `issueActionTokens` over `skills/` finds nothing) ## 维护者速读 - 审批人从邮件里的"驳回"链接打开确认页时,现在要先填写驳回理由,审批记录里写的是这段理由,不再是固定的"Via action link"。 - 属于"审批收尾"专题:您要求每一次驳回都带理由,邮件链接是最后一个没做到的入口。 - 理由留空提交时,页面原样再问一次并提示必填,链接不会作废,可以填好后再提交;通过链接不受影响,改动可直接撤回。 - 无。 ## What changes `redeemActionToken` (the ADR-0043 action link) decided every reject with the fixed comment "Via action link", while every other reject door (the record-page action, MCP `run_action`, the `/reject` route, the SDK) refuses a reject with no reason. This closes that last door. ADR-0043 names this exact gap under "Non-goals (v1)": "Comment capture on the confirm page (a decision comment field is a fast follow; the page ships decision-only)." This PR is that fast follow; the ADR is not edited. - **Confirm page** (`action-link-pages.ts`). A reject link's page now carries a required textarea named `comment`, labelled "Reason for rejecting · 驳回理由", above the button. The approve page is unchanged. The page copy stays static bilingual (EN · 中文) like every other string on these session-less pages, which by design have no locale negotiation and read no translation bundle. - **Redemption** (`approval-service.ts`). `redeemActionToken(token, { comment })` records the typed reason as the reject's comment. The reason is judged by the one rule `decide()` already applies (`rejectReasonIssues`, extracted from `decide()`: `validateActionParams` over a required `textarea` param, so missing, blank, whitespace-only or non-string is refused). A refused reason answers the new outcome `reason_required` BEFORE the token is consumed: nothing is decided, the link stays live, and the approver can type a reason and send it again. A dead link is still checked first and told as before. An approve reads no field and keeps "Via action link". - **Both doors, one answer** (`actionRedemptionPage`). The plugin's self-hosted mount (`approvals-plugin.ts`) and `handleActionPage` now build the POST answer from one function: decided → result page `200`; dead link → result page `200` (unchanged); reject with no reason → the same confirm page again with the refusal "Enter a reason to reject this request. · 驳回需填写驳回理由。" and `400`. Both read the LAST `comment` field, as they already read the last `token`. **The narrowing.** Two populations, one rule. Over HTTP, a POST to `/api/v1/approvals/act` that redeems a reject token without a reason used to reject the request; it is now refused with `400`. In process, the exported `ApprovalService.redeemActionToken(token)` on a reject token used to decide with "Via action link"; it now takes `input?: { comment?: unknown }` and, with no reason, returns the new `ActionTokenOutcome` arm `{ ok: false, reason: 'reason_required', action: 'reject', request, approverId }` (the type `redeemActionToken` and `peekActionToken` return) without consuming or deciding. The fix for an in-process caller: pass `{ comment }` for a reject token and handle the `reason_required` arm. Declared `Clause-②: no (narrowing)`; the changeset carries the BREAKING note, both FROM / TO pairs, the fix lines and the ADR-0087 disposition (`not-required`, no migration prescription: no stored row, key or authored value moves). ## Tests - `approval-service.test.ts`: a reject records the typed reason (and no "Via action link" row); a reject with no input, `{}`, `''`, whitespace, a number or an array is answered `reason_required` with every token still unconsumed, the request `pending` and no reject row, then the SAME link decides once a reason comes; an approve that is sent a `comment` still records "Via action link". - `action-page-member.integration.test.ts` (real `ObjectKernel`, real plugin, SQL driver, real Hono mount), new top-level `describe`: the reject page has the required field and the approve page none; a reject POST with no `comment`, an empty one and a whitespace one answers `400` with exactly the refusal confirm page, decides nothing, and the same token then decides with the typed reason; parity — both doors answer a blank reason with byte-equal `400` pages (one token asks both doors, which itself proves nothing was consumed), a repeated field reads the last `comment` at both, and both record a typed reason. - Updated, not weakened: three existing cases in that file posted a reject token with only `token`; they now post the reason the page asks for, and the bound-approver case additionally asserts the reject row's comment is the typed reason and the approve row's is "Via action link". <details><summary>Local runs (head 1393d97)</summary> - `pnpm --filter @objectstack/plugin-approvals test` on 1393d97 (clean tree): Test Files 127 passed (127), Tests 1890 passed (1890); lock VERDICT command-exit 0. - `pnpm --filter @objectstack/plugin-approvals typecheck` on 7cbaeef (1393d97 changes only the changeset): VERDICT command-exit 0; `check:test-typecheck` OK — approval-service.test.ts back at the ledger's 182 after the fix round (the first CI round was red at 190: the new pins read an untyped request id). - Full dogfood battery on the final head 1393d97, as CI runs it (`pnpm --filter @objectstack/dogfood test` under the verify lock after the `@objectstack/dogfood^...` closure build): VERDICT command-exit 0 · Test Files 487 passed, 3 skipped (490) · Tests 4121 passed, 68 skipped (4189) · no failures. (An earlier battery on a33c65f read the same counts.) - Changeset gates re-run on 1393d97 after the contract review's S1 edit: `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check:doc-authoring`, `check:nul-bytes`, `check:issue-citations` — all exit 0. - Derived gate families (`node scripts/pm/dispatch-gates.mjs --commands`): 105 derived, 105 run, every one exit 0; `dispatch-gates --ran` reconciliation: "105 derived famil(ies) accounted for — 105 run, 0 NOT-MEASURED". 74 ran on 48e3d70, the 31 the docs commit added ran on a33c65f. Three first answered exit 3 (prerequisite, not a finding) and were re-run green after the prerequisite: `check-plugin-teardown-shape --self-test` (after unshallowing `origin/main`), `check:i18n` and `check:dual-build-cjs-loads` (after a full build). </details> ## Acceptance notes - **Docs.** `content/docs/automation/approvals.mdx` said the email action link "still records the fixed text 'Via action link' instead of the approver's reason". This PR made that false, so the sentence is rewritten here (surface amended by the seat on the claim). - **Translation.** The card asks for the new copy in every locale the package ships. The action-link pages ship no per-locale copy: they are session-less and render static EN · 中文 text (file header of `action-link-pages.ts`), and the new label and refusal follow that design. The record-page reject (`approval_reject`) already reads translated labels through the bundles and is untouched. - **Status choice.** The blank-reason answer is `400`, not `200`: ADR-0043's "told on the page, never as an error status" governs a dead link, and this link is live; what was refused is the input, as on the other reject doors (`400 VALIDATION_ERROR`). A browser still renders the page. - **Approve unchanged.** The card's "approve stays optional" is read as: no reason is required for approve. Adding an optional comment field to the approve page would be a widening of that door and is not done here. ## Verification Read first (by risk): `approval-service.ts` `redeemActionToken` (the reason is judged before the token is consumed), `approval-service.ts` `actionRedemptionPage`, `approvals-plugin.ts` POST handler. Two-minute check: `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/action-page-member.integration.test.ts` — expect every case green, including the three in "the reject link asks for a reason". --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzhBqrB3SGxDwDNYumh)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzhBqrB3SGxDwDNYumh --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4c18c43 commit 65ee4b7

7 files changed

Lines changed: 264 additions & 33 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/plugin-approvals': patch
3+
---
4+
5+
fix(plugin-approvals)!: a reject from the email action link records the reason the approver types on the confirm page, and a reject with no reason is refused on the page
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
Skills-docs: none — nothing under `skills/**` teaches the approval action link or its confirm page (`git grep -i` for "action link", "approvals/act" and `issueActionTokens` over `skills/` finds nothing)
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped. One exported member moves: `ApprovalService.redeemActionToken` takes an optional reason, and its outcome type gains a `reason_required` arm (both stated below). What moves is the answer the ADR-0043 action page, and that member, give a redemption of a reject link with no reason: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** for a caller that POSTs a reject link's token to `/api/v1/approvals/act` (the plugin's self-hosted mount, or the HTTP dispatcher's `/approvals/act` domain through `IApprovalService.handleActionPage`) without a reason, and for code that calls the exported `ApprovalService.redeemActionToken` in process on a reject token without one.
14+
15+
- FROM: the confirm page for a reject link had no reason field. A POST carrying only the `token` field rejected the request and recorded the fixed comment "Via action link", while every other reject door (the record-page action, MCP `run_action`, the `/reject` route, the SDK) refused a reject with no reason.
16+
- TO: the reject confirm page carries a required "Reason for rejecting · 驳回理由" field, posted as `comment`, and the decision records that text as its comment. A POST whose `comment` is missing, blank or not a string (judged by the same rule `ApprovalService.decide()` applies) is answered the same confirm page again with the refusal "Enter a reason to reject this request. · 驳回需填写驳回理由。" and status `400`. Nothing is decided and the token is not consumed, so the approver can type a reason and send the same link again.
17+
18+
- In process, FROM: `redeemActionToken(token)` on a live reject token consumed it, rejected the request with the comment "Via action link" and returned `{ ok: true, action: 'reject', … }`.
19+
- In process, TO: `redeemActionToken(token, input?: { comment?: unknown })`. On a reject token whose `input.comment` is missing, blank or not a string it returns `{ ok: false, reason: 'reason_required', action: 'reject', request, approverId }`, a new arm of the `ActionTokenOutcome` type that `redeemActionToken` and `peekActionToken` return, without consuming the token or deciding. With a reason it decides and records that reason as the comment.
20+
21+
**Not moved.** An approve link: its page has no reason field, a POST reads only `token`, and the decision still records "Via action link". A dead link (unknown, expired, used, already decided, handed to someone else) is still told on the result page with `200`, checked before the reason, and a GET still never decides. Both doors still answer the same status and bytes for the same body.
22+
23+
The fix for a caller: send the reason in the form's `comment` field with the `token` when redeeming a reject link. In process, pass `{ comment }` as the second argument to `redeemActionToken` for a reject token, and handle the `reason_required` arm where you switch on the outcome's `reason`.

‎content/docs/automation/approvals.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,9 +1005,9 @@ declares its `comment` param required, so the action door, MCP `run_action` and
10051005
dialog refuse a reject whose `comment` is missing or blank (`400`, the declared
10061006
param contract's `required` refusal), and `ApprovalService.decide()`, behind the
10071007
`/reject` route and the SDK's `client.approvals.reject`, refuses one the same
1008-
way (`400 VALIDATION_ERROR`); the inbox keeps Reject disabled until a reason is typed. The one
1009-
exception is the email action link, which still records the fixed text "Via
1010-
action link" instead of the approver's reason (tracked in #35722).
1008+
way (`400 VALIDATION_ERROR`); the inbox keeps Reject disabled until a reason is typed. The email
1009+
action link asks too: its reject confirm page has a required reason field, and a reject sent with a
1010+
blank one is answered the page again (`400`) with the link still unused.
10111011

10121012
On the record itself, a record with approval requests grows an **Approvals** tab
10131013
beside Details and Related, with a request-count badge: the current step, decision

‎packages/plugins/plugin-approvals/src/action-link-pages.ts‎

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ function shell(title: string, body: string): string {
4545
.ok{background:#ecfdf5;color:#047857}.warn{background:#fffbeb;color:#b45309}.err{background:#fef2f2;color:#b91c1c}
4646
a{color:#2563eb;text-decoration:none}
4747
.foot{margin-top:18px;font-size:12px;color:#94a3b8}
48+
label{display:block;margin-top:18px;font-size:14px;font-weight:600}
49+
textarea{display:block;box-sizing:border-box;width:100%;min-height:88px;margin-top:6px;padding:8px 10px;
50+
border:1px solid #cbd5e1;border-radius:8px;font:inherit;resize:vertical}
51+
.refusal{margin:14px 0 0;padding:8px 12px;border-radius:8px;background:#fef2f2;color:#b91c1c;font-size:14px}
4852
</style></head><body><div class="card">${body}</div></body></html>`;
4953
}
5054

@@ -76,25 +80,52 @@ function summaryRows(req: ApprovalRequestRow): string {
7680
return rows.map(([k, v]) => `<div class="row"><span class="k">${esc(k)}</span><b>${esc(v)}</b></div>`).join('');
7781
}
7882

79-
/** GET page: summary + a POST form. Rendering only — no mutation. */
83+
/**
84+
* The refusal a reject link's confirm page shows when its form came back with
85+
* no reason. A reject carries its reason on every door (`ApprovalService.decide`);
86+
* this door asks the approver for one on the page instead of recording a fixed
87+
* text, and a blank one leaves the link live so the approver can try again.
88+
*/
89+
export const REJECT_REASON_REQUIRED_COPY = 'Enter a reason to reject this request. · 驳回需填写驳回理由。';
90+
91+
/**
92+
* GET page: summary + a POST form. Rendering only — no mutation.
93+
*
94+
* A reject form carries a required `comment` field, the reason the decision
95+
* records (`redeemActionToken`); an approve form carries none and keeps its
96+
* one button. `refusal: 'reason_required'` is the same page answered again
97+
* after a reject form came back with a blank reason.
98+
*/
8099
export function renderConfirmPage(input: {
81100
request: ApprovalRequestRow;
82101
action: Extract<ApprovalActionKind, 'approve' | 'reject'>;
83102
approverId: string;
84103
token: string;
85104
actPath: string;
105+
refusal?: 'reason_required';
86106
}): string {
87107
const approving = input.action === 'approve';
88108
const verb = approving ? 'Approve · 通过' : 'Reject · 驳回';
109+
const tokenField = `<input type="hidden" name="token" value="${esc(input.token)}">`;
110+
const button = `<button type="submit" class="${approving ? 'approve' : 'reject'}">${verb}</button>`;
111+
const form = approving
112+
? `<form method="post" action="${esc(input.actPath)}" class="actions">
113+
${tokenField}
114+
${button}
115+
</form>`
116+
: `<form method="post" action="${esc(input.actPath)}">
117+
${tokenField}
118+
<label for="comment">Reason for rejecting · 驳回理由</label>
119+
<textarea id="comment" name="comment" required></textarea>
120+
${input.refusal === 'reason_required' ? `<p class="refusal" role="alert">${esc(REJECT_REASON_REQUIRED_COPY)}</p>` : ''}
121+
<div class="actions">${button}</div>
122+
</form>`;
89123
return shell(`${verb} — Approval`, `
90124
<h1>${approving ? '✅ Approve this request?' : '⛔ Reject this request?'}</h1>
91125
<p class="sub">${approving ? '确认通过该审批请求?' : '确认驳回该审批请求?'}
92126
Acting as · 操作身份:<b>${esc(input.approverId)}</b></p>
93127
${summaryRows(input.request)}
94-
<form method="post" action="${esc(input.actPath)}" class="actions">
95-
<input type="hidden" name="token" value="${esc(input.token)}">
96-
<button type="submit" class="${approving ? 'approve' : 'reject'}">${verb}</button>
97-
</form>
128+
${form}
98129
<p class="foot">This link is single-use and expires automatically. · 此链接一次有效,过期自动失效。</p>`);
99130
}
100131

‎packages/plugins/plugin-approvals/src/action-page-member.integration.test.ts‎

Lines changed: 79 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ import type { ObjectQL } from '@objectstack/objectql';
3535
import { SqlDriver } from '@objectstack/driver-sql';
3636
import { ApprovalsServicePlugin } from './approvals-plugin.js';
3737
import type { ApprovalService } from './approval-service.js';
38-
import { renderResultPage } from './action-link-pages.js';
38+
import { REJECT_REASON_REQUIRED_COPY, renderConfirmPage, renderResultPage } from './action-link-pages.js';
3939
import { installDefaultOrganization } from './default-organization.testkit.js';
4040
// Clocked windows measure behaviour, never loading. On an `ObjectKernel` the
4141
// core `i18n` fallback is present, so the plugin's `kernel:ready` hook imports
@@ -171,6 +171,9 @@ const getRequest = (token: string) =>
171171
const postRequest = (body: string, contentType = 'application/x-www-form-urlencoded', headers: Record<string, string> = {}) =>
172172
new Request(`${ORIGIN}${ACT_PATH}`, { method: 'POST', headers: { 'Content-Type': contentType, ...headers }, body });
173173
const tokenForm = (token: string) => new URLSearchParams({ token }).toString();
174+
/** A reject form as the confirm page posts it: the token and the reason typed. */
175+
const rejectForm = (token: string, comment = 'Dates clash with the release.') =>
176+
new URLSearchParams({ token, comment }).toString();
174177

175178
/** Everything a response says, the body as bytes. */
176179
async function snapshot(res: Response) {
@@ -214,7 +217,7 @@ describe('[#22578] handleActionPage — the ADR-0043 action page from a Request'
214217
const rejectTokens = await svc.issueActionTokens(rejected, APPROVER);
215218

216219
const a = await snapshot(await svc.handleActionPage(postRequest(tokenForm(approveTokens.approve))));
217-
const r = await snapshot(await svc.handleActionPage(postRequest(tokenForm(rejectTokens.reject))));
220+
const r = await snapshot(await svc.handleActionPage(postRequest(rejectForm(rejectTokens.reject))));
218221
expect([a.status, r.status]).toEqual([200, 200]);
219222
expect(text(a)).toBe(renderResultPage('approved', (await svc.getRequest(approved, SYSTEM))!));
220223
expect(text(r)).toBe(renderResultPage('rejected', (await svc.getRequest(rejected, SYSTEM))!));
@@ -226,6 +229,9 @@ describe('[#22578] handleActionPage — the ADR-0043 action page from a Request'
226229
expect(decisions).toHaveLength(1);
227230
expect(decisions[0]).toMatchObject({ action, actor_id: APPROVER, acted_as: APPROVER });
228231
}
232+
// The reject records the reason typed on the page; the approve its fixed text.
233+
expect((await decisionsOf(rejected))[0].comment).toBe('Dates clash with the release.');
234+
expect((await decisionsOf(approved))[0].comment).toBe('Via action link');
229235
expect(host.resumed.map((x) => x.branchLabel)).toEqual(['approve', 'reject']);
230236
});
231237

@@ -236,7 +242,7 @@ describe('[#22578] handleActionPage — the ADR-0043 action page from a Request'
236242
await sleep(10);
237243
const consumedOn = await openRequest();
238244
const consumed = await svc.issueActionTokens(consumedOn, APPROVER);
239-
await svc.handleActionPage(postRequest(tokenForm(consumed.reject)));
245+
await svc.handleActionPage(postRequest(rejectForm(consumed.reject)));
240246
const consumedRow = (await svc.getRequest(consumedOn, SYSTEM))!;
241247

242248
const cases: Array<[string, string, string]> = [
@@ -379,7 +385,7 @@ describe('[#22578] parity — the member answers what the self-hosted mount answ
379385
const expired = await svc.issueActionTokens(await openRequest(), APPROVER, { ttlMs: 1 });
380386
await sleep(10);
381387
const consumed = await svc.issueActionTokens(await openRequest(), APPROVER);
382-
await svc.redeemActionToken(consumed.reject);
388+
await svc.redeemActionToken(consumed.reject, { comment: 'Dates clash with the release.' });
383389
const liveOn = await openRequest();
384390
const live = await svc.issueActionTokens(liveOn, APPROVER);
385391

@@ -485,3 +491,72 @@ describe('[#22578] the composition — one mount where a raw app exists, the mem
485491
expect(plugin.infos.filter((line) => line.includes('/approvals/act domain'))).toHaveLength(1);
486492
});
487493
});
494+
495+
describe('the reject link asks for a reason — a blank one is refused on the page, and the link stays live', () => {
496+
it('the reject confirm page carries a required reason field; the approve page does not', async () => {
497+
const { svc, openRequest } = await bootStack({ rawApp: false });
498+
const { approve, reject } = await svc.issueActionTokens(await openRequest(), APPROVER);
499+
const rejectPage = text(await snapshot(await svc.handleActionPage(getRequest(reject))));
500+
const approvePage = text(await snapshot(await svc.handleActionPage(getRequest(approve))));
501+
expect(rejectPage).toContain('<textarea id="comment" name="comment" required>');
502+
expect(approvePage).not.toContain('name="comment"');
503+
// Neither page shows the refusal until a blank reason came back.
504+
expect([rejectPage, approvePage].filter((page) => page.includes(REJECT_REASON_REQUIRED_COPY))).toEqual([]);
505+
});
506+
507+
it('a reject posted with no reason, or a blank one, is answered the confirm page again with 400 — nothing decided, nothing consumed', async () => {
508+
const { svc, openRequest, statusOf, decisionsOf } = await bootStack({ rawApp: false });
509+
const requestId = await openRequest();
510+
const { reject } = await svc.issueActionTokens(requestId, APPROVER);
511+
const row = (await svc.getRequest(requestId, SYSTEM))!;
512+
const refusal = renderConfirmPage({
513+
request: row, action: 'reject', approverId: APPROVER, token: reject, actPath: ACT_PATH, refusal: 'reason_required',
514+
});
515+
expect(refusal).toContain(REJECT_REASON_REQUIRED_COPY);
516+
517+
for (const body of [tokenForm(reject), rejectForm(reject, ''), rejectForm(reject, ' \n ')]) {
518+
const page = await snapshot(await svc.handleActionPage(postRequest(body)));
519+
expect(page.status, body).toBe(400);
520+
expect(page.headers).toEqual([['content-type', 'text/html; charset=utf-8']]);
521+
expect(text(page), body).toBe(refusal);
522+
}
523+
expect(await statusOf(requestId)).toBe('pending');
524+
expect(await decisionsOf(requestId)).toEqual([]);
525+
526+
// The link was never consumed: the same token decides once a reason comes with it.
527+
const decided = await snapshot(await svc.handleActionPage(postRequest(rejectForm(reject, 'Overlaps the audit week.'))));
528+
expect(decided.status).toBe(200);
529+
expect(text(decided)).toBe(renderResultPage('rejected', (await svc.getRequest(requestId, SYSTEM))!));
530+
expect(await decisionsOf(requestId)).toEqual([
531+
expect.objectContaining({ action: 'reject', actor_id: APPROVER, comment: 'Overlaps the audit week.' }),
532+
]);
533+
});
534+
535+
it('parity: both doors answer a blank reason with the same 400 page, and both record a typed one', async () => {
536+
const { app, svc, openRequest, statusOf, decisionsOf } = await bootStack({ rawApp: true });
537+
const viaMember = await openRequest('Twin leave');
538+
const viaMount = await openRequest('Twin leave');
539+
const memberTokens = await svc.issueActionTokens(viaMember, APPROVER);
540+
const mountTokens = await svc.issueActionTokens(viaMount, APPROVER);
541+
542+
// A blank reason consumes nothing, so ONE token asks both doors the same question.
543+
for (const body of [tokenForm(memberTokens.reject), rejectForm(memberTokens.reject, ' ')]) {
544+
const member = await snapshot(await svc.handleActionPage(postRequest(body)));
545+
const mount = await snapshot(await app!.fetch(postRequest(body)));
546+
expect(mount.status).toBe(400);
547+
expect(member, body).toEqual(mount);
548+
}
549+
// A repeated field: the LAST reason is the one both doors read.
550+
const lastBlank = `${rejectForm(memberTokens.reject, 'first')}&comment=`;
551+
const member = await snapshot(await svc.handleActionPage(postRequest(lastBlank)));
552+
expect(member).toEqual(await snapshot(await app!.fetch(postRequest(lastBlank))));
553+
expect(member.status).toBe(400);
554+
expect(await statusOf(viaMember)).toBe('pending');
555+
556+
await svc.handleActionPage(postRequest(rejectForm(memberTokens.reject, 'Member door reason.')));
557+
const viaMountPage = await snapshot(await app!.fetch(postRequest(rejectForm(mountTokens.reject, 'Mount door reason.'))));
558+
expect(viaMountPage.status).toBe(200);
559+
expect(await decisionsOf(viaMember)).toEqual([expect.objectContaining({ action: 'reject', comment: 'Member door reason.' })]);
560+
expect(await decisionsOf(viaMount)).toEqual([expect.objectContaining({ action: 'reject', comment: 'Mount door reason.' })]);
561+
});
562+
});

‎packages/plugins/plugin-approvals/src/approval-service.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2247,6 +2247,42 @@ describe('ApprovalService (node era)', () => {
22472247
expect(await svc.redeemActionToken(approve)).toMatchObject({ ok: false, reason: 'consumed' });
22482248
});
22492249

2250+
it('redeem: a reject records the reason typed on the confirm page as its comment', async () => {
2251+
const resumed: any[] = [];
2252+
svc.attachAutomation({ async resume(runId, signal) { resumed.push({ runId, signal }); } });
2253+
const { id: reqId } = (await svc.openNodeRequest(openInput(['u9']), CTX)) as { id: string };
2254+
const { reject } = await svc.issueActionTokens(reqId, 'u9');
2255+
const out = await svc.redeemActionToken(reject, { comment: 'Over budget for this quarter.' });
2256+
expect(out).toMatchObject({ ok: true, action: 'reject', approverId: 'u9' });
2257+
expect((out as any).request.status).toBe('rejected');
2258+
expect(resumed[0]?.signal?.branchLabel).toBe('reject');
2259+
const acts = await svc.listActions(reqId, SYS);
2260+
expect(acts.at(-1)).toMatchObject({ action: 'reject', actor_id: 'u9', comment: 'Over budget for this quarter.' });
2261+
expect(acts.some(a => a.comment === 'Via action link')).toBe(false);
2262+
});
2263+
2264+
it('redeem: a reject with no reason is refused before the token is consumed — nothing decided, the link stays live', async () => {
2265+
const { id: reqId } = (await svc.openNodeRequest(openInput(['u9']), CTX)) as { id: string };
2266+
const { reject } = await svc.issueActionTokens(reqId, 'u9');
2267+
for (const input of [undefined, {}, { comment: '' }, { comment: ' \n\t ' }, { comment: 42 }, { comment: ['why'] }]) {
2268+
const out = await svc.redeemActionToken(reject, input as any);
2269+
expect(out, JSON.stringify(input)).toMatchObject({ ok: false, reason: 'reason_required', action: 'reject', approverId: 'u9' });
2270+
expect((out as any).request.id).toBe(reqId);
2271+
}
2272+
expect(engine._tables['sys_approval_token'].every(r => r.consumed_at == null)).toBe(true);
2273+
expect((await svc.getRequest(reqId, SYS))?.status).toBe('pending');
2274+
expect((await svc.listActions(reqId, SYS)).filter(a => a.action === 'reject')).toEqual([]);
2275+
// Still live: the same link decides once a reason comes with it.
2276+
expect(await svc.redeemActionToken(reject, { comment: 'Missing receipts.' })).toMatchObject({ ok: true, action: 'reject' });
2277+
});
2278+
2279+
it('redeem: an approve reads no reason and keeps its fixed comment', async () => {
2280+
const { id: reqId } = (await svc.openNodeRequest(openInput(['u9']), CTX)) as { id: string };
2281+
const { approve } = await svc.issueActionTokens(reqId, 'u9');
2282+
expect(await svc.redeemActionToken(approve, { comment: 'typed anyway' })).toMatchObject({ ok: true, action: 'approve' });
2283+
expect((await svc.listActions(reqId, SYS)).at(-1)).toMatchObject({ action: 'approve', comment: 'Via action link' });
2284+
});
2285+
22502286
it('peek: validates without consuming (GET never mutates)', async () => {
22512287
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
22522288
const { reject } = await svc.issueActionTokens(req.id, 'u9');

0 commit comments

Comments
 (0)