feat: optional reason when denying an approval (#12213)

* feat: optional reason when denying an approval

* fix: keep the full deny reason in the audit entry

* fix: name the denial reason in the payload guard and document error.reason

* feat: tuck the deny reason behind an add a reason link

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: ask for the deny reason in a popover on deny

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: label the run page cancel action cancel step

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
hugocasa
2026-11-05 23:27:11 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 Ruben Fiszel
parent 3c5a5caf97
commit c057f8995d
15 changed files with 217 additions and 60 deletions
+3 -1
View File
@@ -19630,7 +19630,9 @@ paths:
type: object
properties:
payload:
description: payload to send to the resumed job
description: >
payload to send to the resumed job. On a denial, a string `reason` in it
is shown in the step's error and the audit log.
approval_token:
type: string
description: approval token for unauthenticated access
File diff suppressed because one or more lines are too long
+23 -4
View File
@@ -5104,6 +5104,7 @@ pub async fn resume_suspended_flow_as_owner(
job_id,
true,
&authed.username,
None,
)
.await?;
@@ -5236,6 +5237,7 @@ async fn resume_suspended(
let approver_value = opt_authed.as_ref().map(|a| a.username.clone());
let deny_reason = (!approved).then(|| deny_reason(&value)).flatten();
insert_resume_job(
resume_id,
resume_job_id,
@@ -5280,6 +5282,7 @@ async fn resume_suspended(
resume_job_id,
approved,
&approver,
deny_reason.as_deref(),
)
.await?;
@@ -5781,6 +5784,7 @@ async fn resume_suspended_job_internal(
reject_mismatched_wac_approval(&mut tx, flow_info.id, resume_id).await?;
}
let deny_reason = (!approved).then(|| deny_reason(&value)).flatten();
insert_resume_job(
resume_id,
job_id,
@@ -5834,6 +5838,7 @@ async fn resume_suspended_job_internal(
job_id,
approved,
&approver,
deny_reason.as_deref(),
)
.await?;
tx.commit().await?;
@@ -5851,6 +5856,7 @@ async fn audit_suspend_resume(
step_job_id: Uuid,
approved: bool,
approver: &str,
deny_reason: Option<&str>,
) -> error::Result<()> {
let flow_id_s = flow_id.to_string();
let step_job_id_s = step_job_id.to_string();
@@ -5867,6 +5873,9 @@ async fn audit_suspend_resume(
if step_job_id != flow_id {
params.insert("step_job_id", step_job_id_s.as_str());
}
if let Some(reason) = deny_reason {
params.insert("reason", reason);
}
audit_log(
&mut **tx,
author,
@@ -5938,6 +5947,12 @@ async fn decrement_suspend(flow_id: Uuid, tx: &mut Transaction<'_, Postgres>) ->
Ok(())
}
/// The reason an approver gave for a denial, read from the deny payload's `reason`.
fn deny_reason(value: &serde_json::Value) -> Option<String> {
let reason = value.get("reason")?.as_str()?.trim();
(!reason.is_empty()).then(|| reason.to_string())
}
async fn insert_resume_job<'c>(
resume_id: u32,
job_id: Uuid,
@@ -5950,11 +5965,15 @@ async fn insert_resume_job<'c>(
// The approver, possibly anonymous, writes this payload, and later steps receive it as
// `resume`, interpolated with the flow's own token.
if windmill_common::variables::untrusted_arg_interpolates(&value.to_string()) {
return Err(Error::BadRequest(
"The resume payload cannot hold $var:, $jsonvar:, $res: or $encrypted: references, \
let what = if approved {
"The resume payload"
} else {
"The denial reason"
};
return Err(Error::BadRequest(format!(
"{what} cannot hold $var:, $jsonvar:, $res: or $encrypted: references, \
or a $WM_* variable name"
.to_string(),
));
)));
}
sqlx::query!(
r#"
+58 -19
View File
@@ -3533,6 +3533,29 @@ pub struct ResumeRow {
pub resume_id: i32,
}
impl ResumeRow {
/// The step's error for a denial, carrying the reason the approver put in the deny
/// payload's `reason`, if any.
fn disapproval_error(&self) -> Value {
let approver = self.approver.as_deref().unwrap_or("unknown");
let reason = serde_json::from_str::<Value>(self.value.get())
.ok()
.and_then(|v| Some(v.get("reason")?.as_str()?.trim().to_string()))
.filter(|r| !r.is_empty());
match reason {
Some(reason) => json!({"error": {
"message": format!("Disapproved by {approver}: {reason}"),
"name": "SuspendedDisapproved",
"reason": reason,
}}),
None => json!({"error": {
"message": format!("Disapproved by {approver}"),
"name": "SuspendedDisapproved",
}}),
}
}
}
lazy_static::lazy_static! {
static ref CRASH_FORCEFULLY_AT_STEP: Option<usize> = std::env::var("CRASH_FORCEFULLY_AT_STEP")
.ok()
@@ -4137,7 +4160,7 @@ async fn push_next_flow_job(
if can_be_resumed || disapproved_or_timeout_but_continue {
if disapproved_or_timeout_but_continue {
let js = if let Some(disapproved) = is_disapproved.as_ref() {
json!({"error": {"message": format!("Disapproved by {}", disapproved.approver.clone().unwrap_or_else( || "unknown".to_string())), "name": "SuspendedDisapproved"}})
disapproved.disapproval_error()
} else {
json!({"error": {"message": "Timed out waiting to be resumed", "name": "SuspendedTimedOut"}})
};
@@ -4265,25 +4288,15 @@ async fn push_next_flow_job(
}
tx.commit().warn_after_seconds(3).await?;
let (logs, error_name) = if let Some(disapprover) = is_disapproved {
(
format!(
"Disapproved by {}",
disapprover
.approver
.clone()
.unwrap_or_else(|| "unknown".to_string())
),
"SuspendedDisapproved",
)
let result: Value = if let Some(disapprover) = is_disapproved {
disapprover.disapproval_error()
} else {
(
"Timed out waiting to be resumed".to_string(),
"SuspendedTimedOut",
)
json!({ "error": {"message": "Timed out waiting to be resumed", "name": "SuspendedTimedOut"}})
};
let result: Value = json!({ "error": {"message": logs, "name": error_name}});
let logs = result["error"]["message"]
.as_str()
.unwrap_or_default()
.to_string();
append_logs(
&flow_job.id,
@@ -7089,9 +7102,35 @@ pub async fn get_previous_job_result(
mod tests {
use super::{
effective_flow_step_timeout, extract_chat_message_from_flow_result, is_simple_modules,
FlowEnvSecrets,
FlowEnvSecrets, ResumeRow,
};
#[test]
fn disapproval_error_carries_the_deny_reason() {
let denial = |value: serde_json::Value| ResumeRow {
value: sqlx::types::Json(to_raw_value(&value).unwrap()),
approver: Some("ann".to_string()),
approved: false,
resume_id: 0,
};
assert_eq!(
denial(json!({"reason": " too risky "})).disapproval_error(),
json!({"error": {"name": "SuspendedDisapproved", "message": "Disapproved by ann: too risky", "reason": "too risky"}})
);
// A form payload without a string reason denies as before.
for value in [
json!(null),
json!({"reason": " "}),
json!({"reason": 3}),
json!({"a": 1}),
] {
assert_eq!(
denial(value).disapproval_error(),
json!({"error": {"name": "SuspendedDisapproved", "message": "Disapproved by ann"}})
);
}
}
// An input computed from a secret is stored encrypted, which an agent worker cannot
// decrypt, so a key that merely shares a secret entry's name must not count as reading it.
#[test]
+1 -1
View File
@@ -6143,7 +6143,7 @@ can call one, not an agent used as a tool.
- \`flow_input.iter.value\` - Current iteration value inside a \`forloopflow\`; in a \`whileloopflow\` it is just the iteration index (a plain number, same as \`flow_input.iter.index\`)
- \`flow_input.iter.index\` - Current loop index when inside a loop (\`forloopflow\` or \`whileloopflow\`)
- After a suspend step (approval), the next step's javascript expressions also get:
- \`resume\` - the last resume payload (the resume form values); with \`continue_on_disapprove_timeout\`, a disapproval or timeout yields \`{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }\` instead
- \`resume\` - the last resume payload (the resume form values); with \`continue_on_disapprove_timeout\`, a disapproval or timeout yields \`{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }\` instead, plus \`reason\` on a disapproval whose approver gave one
- \`resumes\` - every resume payload, in arrival order
- \`approvers\` - a plain array of strings, one per resume: for a resume through the \`resume\`/\`cancel\` URL from \`getResumeUrls(approver)\`, the \`approver\` passed there if any; otherwise (including the \`approvalPage\` link) the resuming user's username, else \`"anonymous"\`, e.g. \`approvers[0]\`. It is NOT the \`{ resume_id, approver }\` objects stored in the flow status, so \`approvers[0].approver\` is always undefined
@@ -60,7 +60,7 @@
)
}
async function continu(approve: boolean) {
async function continu(approve: boolean, reason?: string) {
if (!workspaceId) {
throw new Error('Cannot resume: the job has no workspace')
}
@@ -68,7 +68,7 @@
workspace: workspaceId,
jobId: job?.id ?? '',
requestBody: {
payload: approve ? (default_payload as any) : undefined,
payload: approve ? (default_payload as any) : reason ? { reason } : undefined,
approved: approve
}
})
@@ -101,8 +101,9 @@
<ApprovalActions
approveLabel="Resume"
approveTooltip="Resume or approve this suspended step"
rejectTitle="Cancel the step"
rejectTitle="Cancel step"
hideReject={hide_cancel}
askRejectReason
{light}
onAnswer={continu}
>
@@ -5,6 +5,7 @@
import { sendUserToast } from '$lib/toast'
import { Button } from '../common'
import Tooltip from '../Tooltip.svelte'
import DenyReason from './DenyReason.svelte'
interface Props {
approveLabel: string
@@ -15,8 +16,10 @@
light?: boolean
/** Holds the approve button back, e.g. until an answer is typed. */
approveDisabled?: boolean
/** Reject opens a popover asking for an optional reason, passed to `onAnswer`. */
askRejectReason?: boolean
/** Throws to report a failure; the buttons stay usable then. */
onAnswer: (approved: boolean) => Promise<void>
onAnswer: (approved: boolean, reason?: string) => Promise<void>
/** Shown after the buttons, on the same row. */
children?: Snippet
}
@@ -28,6 +31,7 @@
hideReject = false,
light = false,
approveDisabled = false,
askRejectReason = false,
onAnswer,
children
}: Props = $props()
@@ -35,10 +39,10 @@
let loading = $state(false)
let answered = $state(false)
async function answer(approved: boolean) {
async function answer(approved: boolean, reason?: string) {
loading = true
try {
await onAnswer(approved)
await onAnswer(approved, reason)
answered = true
} catch (e: any) {
sendUserToast(e?.body ?? e?.message ?? 'Failed', true)
@@ -49,7 +53,26 @@
</script>
<div class={twMerge('flex gap-2 items-center', light ? 'flex-col' : 'flex-row')}>
{#if !hideReject}
{#if !hideReject && askRejectReason}
<DenyReason
confirmLabel={rejectTitle}
disabled={loading || answered}
onDeny={(reason) => answer(false, reason)}
>
{#snippet button()}
<Button
title={rejectTitle}
iconOnly
startIcon={{ icon: X }}
variant="default"
disabled={loading || answered}
destructive
unifiedSize="md"
nonCaptureEvent
/>
{/snippet}
</DenyReason>
{:else if !hideReject}
<Button
title={rejectTitle}
iconOnly
@@ -0,0 +1,57 @@
<script lang="ts">
import type { Snippet } from 'svelte'
import { Button } from '$lib/components/common'
import Popover from '$lib/components/meltComponents/Popover.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
interface Props {
/** The deny button. Render it with `nonCaptureEvent`: the popover's own button takes the click. */
button: Snippet
confirmLabel: string
onDeny: (reason: string | undefined) => void
disabled?: boolean
}
let { button, confirmLabel, onDeny, disabled = false }: Props = $props()
let reason = $state('')
function deny(close: () => void) {
close()
onDeny(reason.trim() || undefined)
}
</script>
<Popover
{disabled}
placement="bottom-start"
contentClasses="p-3"
openFocus="#deny-reason-input"
triggerAttrs={{ 'aria-label': confirmLabel }}
>
{#snippet trigger()}
{@render button()}
{/snippet}
{#snippet content({ close })}
<div class="flex flex-col gap-2 w-72 max-w-[calc(100vw-3rem)]">
<label class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">
Reason <span class="font-normal text-secondary">(optional)</span>
</span>
<TextInput
bind:value={reason}
inputProps={{
id: 'deny-reason-input',
maxlength: 1000,
onkeydown: (e) => e.key === 'Enter' && deny(close)
}}
/>
</label>
<div class="flex justify-end">
<Button variant="accent" destructive unifiedSize="sm" onClick={() => deny(close)}>
{confirmLabel}
</Button>
</div>
</div>
{/snippet}
</Popover>
@@ -4,6 +4,7 @@
import type { BadgeColor } from '$lib/components/common'
import DisplayResult from '$lib/components/DisplayResult.svelte'
import SchemaForm from '$lib/components/SchemaForm.svelte'
import DenyReason from './DenyReason.svelte'
import Login from '$lib/components/Login.svelte'
import TimeAgo from '$lib/components/TimeAgo.svelte'
import { enterpriseLicense, userStore } from '$lib/stores'
@@ -27,7 +28,7 @@
runDetailsHref: string
rd: string
onApprove: () => void
onReject: () => void
onReject: (reason: string | undefined) => void
}
let {
@@ -129,15 +130,19 @@
{#if approvalInfo.can_approve}
<div class="flex flex-row flex-wrap justify-between gap-4">
{#if approvalInfo.hide_cancel !== true}
<Button
unifiedSize="lg"
variant="default"
destructive
onclick={onReject}
disabled={loading}
>
Reject
</Button>
<DenyReason confirmLabel="Reject" disabled={loading} onDeny={onReject}>
{#snippet button()}
<Button
unifiedSize="lg"
variant="default"
destructive
disabled={loading}
nonCaptureEvent
>
Reject
</Button>
{/snippet}
</DenyReason>
{:else}
<div></div>
{/if}
@@ -14,6 +14,7 @@
import { mergeSchema } from '$lib/common'
import { emptyString } from '$lib/utils'
import { Alert } from '$lib/components/common'
import DenyReason from '$lib/components/approvals/DenyReason.svelte'
import { getUserExt } from '$lib/user'
import { setLicense } from '$lib/enterpriseUtils'
import DisplayResult from '$lib/components/DisplayResult.svelte'
@@ -124,13 +125,14 @@
}
}
async function cancel() {
async function cancel(reason: string | undefined) {
loading = true
try {
await JobService.resumeSuspended({
workspace: page.params.workspace ?? '',
jobId: page.params.job ?? '',
requestBody: {
payload: reason ? { reason } : undefined,
approval_token: token,
approved: false
}
@@ -347,9 +349,13 @@
{#if !completed && !actionTaken && approvalInfo.can_approve}
<div class="w-max-md flex flex-row gap-x-4 gap-y-4 justify-between w-full flex-wrap">
{#if approvalInfo.hide_cancel !== true}
<Button variant="accent" destructive onclick={cancel} size="lg" disabled={loading}>
Deny
</Button>
<DenyReason confirmLabel="Deny" disabled={loading} onDeny={cancel}>
{#snippet button()}
<Button variant="accent" destructive size="lg" disabled={loading} nonCaptureEvent>
Deny
</Button>
{/snippet}
</DenyReason>
{:else}
<div></div>
{/if}
@@ -13,6 +13,7 @@
import { mergeSchema } from '$lib/common'
import { emptyString } from '$lib/utils'
import { Alert } from '$lib/components/common'
import DenyReason from '$lib/components/approvals/DenyReason.svelte'
import { getUserExt } from '$lib/user'
import { setLicense } from '$lib/enterpriseUtils'
import DisplayResult from '$lib/components/DisplayResult.svelte'
@@ -121,14 +122,14 @@
getJob()
}
async function cancel() {
async function cancel(reason: string | undefined) {
await JobService.cancelSuspendedJobPost({
workspace: page.params.workspace ?? '',
id: page.params.job ?? '',
resumeId: new Number(page.params.resume).valueOf(),
signature: page.params.hmac ?? '',
approver,
requestBody: {}
requestBody: reason ? { reason } : {}
})
sendUserToast('Flow denied!')
getJob()
@@ -274,13 +275,17 @@
{#if !completed}
<div class="w-max-md flex flex-row gap-x-4 gap-y-4 justify-between w-full flex-wrap">
{#if !job?.raw_flow?.modules?.[approvalStep]?.suspend?.hide_cancel}
<Button
variant="accent"
destructive
on:click|once={cancel}
size="lg"
disabled={completed || alreadyResumed}>Deny</Button
>
<DenyReason confirmLabel="Deny" disabled={completed || alreadyResumed} onDeny={cancel}>
{#snippet button()}
<Button
variant="accent"
destructive
size="lg"
disabled={completed || alreadyResumed}
nonCaptureEvent>Deny</Button
>
{/snippet}
</DenyReason>
{:else}
<div></div>
{/if}
+1 -1
View File
@@ -298,7 +298,7 @@ can call one, not an agent used as a tool.
- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)
- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)
- After a suspend step (approval), the next step's javascript expressions also get:
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead, plus `reason` on a disapproval whose approver gave one
- `resumes` - every resume payload, in arrival order
- `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `"anonymous"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined
+1 -1
View File
@@ -327,7 +327,7 @@ can call one, not an agent used as a tool.
- \`flow_input.iter.value\` - Current iteration value inside a \`forloopflow\`; in a \`whileloopflow\` it is just the iteration index (a plain number, same as \`flow_input.iter.index\`)
- \`flow_input.iter.index\` - Current loop index when inside a loop (\`forloopflow\` or \`whileloopflow\`)
- After a suspend step (approval), the next step's javascript expressions also get:
- \`resume\` - the last resume payload (the resume form values); with \`continue_on_disapprove_timeout\`, a disapproval or timeout yields \`{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }\` instead
- \`resume\` - the last resume payload (the resume form values); with \`continue_on_disapprove_timeout\`, a disapproval or timeout yields \`{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }\` instead, plus \`reason\` on a disapproval whose approver gave one
- \`resumes\` - every resume payload, in arrival order
- \`approvers\` - a plain array of strings, one per resume: for a resume through the \`resume\`/\`cancel\` URL from \`getResumeUrls(approver)\`, the \`approver\` passed there if any; otherwise (including the \`approvalPage\` link) the resuming user's username, else \`"anonymous"\`, e.g. \`approvers[0]\`. It is NOT the \`{ resume_id, approver }\` objects stored in the flow status, so \`approvers[0].approver\` is always undefined
@@ -385,7 +385,7 @@ can call one, not an agent used as a tool.
- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)
- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)
- After a suspend step (approval), the next step's javascript expressions also get:
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead, plus `reason` on a disapproval whose approver gave one
- `resumes` - every resume payload, in arrival order
- `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `"anonymous"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined
+1 -1
View File
@@ -303,7 +303,7 @@ can call one, not an agent used as a tool.
- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)
- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)
- After a suspend step (approval), the next step's javascript expressions also get:
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead
- `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: "SuspendedDisapproved" | "SuspendedTimedOut", message } }` instead, plus `reason` on a disapproval whose approver gave one
- `resumes` - every resume payload, in arrival order
- `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `"anonymous"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined