mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
feat: show who approved a flow run, and list opted-in approvals on home (#12604)
* feat: show who approved a flow run and the runs waiting for your approval Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: skip consumed approvals of a workflow as code and keep agent approval requests on the run page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: confine waiting approvals to a token's tags, track a workflow's pending approval, show continued rejections Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: mark a recent run suspended only while it waits on an approval Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: regenerate the files derived from the OpenFlow schema Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: list a step's approvers without keying on their truncated resume id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop the doubled lines in the run page's approvals card Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show the approvals section on home by default, like recently run Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: list a waiting approval on home only when its step opts in Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show waiting runs in recently run in violet with how long they have waited Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show a waiting run's age in recently run like every other row's Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: open every waiting approval on its approval page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: open approval pages and the recent run link in a new tab Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: word approval rows like the approval page and align them with sibling UI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: list a subflow, branch or loop approval in the run's approvals card Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show nested approvals on the run page, with the steps leading to them Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf: read only the nested runs that can hold an approval, and chain their step ids Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: select a nested approval's own node, refetch only when its waits change Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep nested approvals within the token's tag scope, test which steps are followed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: link each waiting approval row to its approval page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: order finished approvals by decision time, count approvals instead of steps Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show a nested wait in the progress bar, drop the graph's suspended line Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: follow nested loops of deployed flows, show continued timeouts, violet waiting bar Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show the flow progress bar on the public run page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: list approvals that timed out with no response, refresh the count after approving Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: read approvers with a checked query Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: name who approved a waiting step so far Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show each approval's time on hover Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf: list Home approvals from the waiting step's status, not flow definitions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show the Approvals card in the runs page's detail panel Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show approval times in a popover, not a native tooltip Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: put an approval step's resume form above its buttons Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show the approval count and times on the approval page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: leave skipped nested approval steps out of the history Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: count only the current step's approvals on the approval page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
4b715c422a
commit
3efe1e97a7
+97
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n SELECT j.id AS \"id!\",\n COALESCE(j.root_job, j.parent_job, j.id) AS \"root_job_id!\",\n j.runnable_path,\n j.permissioned_as_email AS \"email!\",\n j.created_by AS \"created_by!\",\n j.created_at AS \"created_at!\",\n COALESCE(rj.runnable_path, j.runnable_path) AS flow_path,\n NULLIF(f.summary, '') AS flow_summary,\n s.flow_status->'approval_conditions' AS approval_conditions,\n NULLIF(w.m->'home'->>'step_summary', '') AS step_summary,\n COALESCE((w.m->>'count')::bigint, 1) AS \"required_approvals!\",\n -- Counted as the worker counts them: those sent to the approval step's job,\n -- plus those sent to the flow itself.\n (SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid))\n AS \"approvals!\",\n EXISTS(SELECT 1 FROM resume_job r\n WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2)\n AS \"approved_by_me!\"\n FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n JOIN v2_job_status s ON s.id = q.id\n LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job)\n LEFT JOIN flow f\n ON f.workspace_id = j.workspace_id\n AND f.path = COALESCE(rj.runnable_path, j.runnable_path)\n -- The step waiting on the approval, which the worker marks `home` when the approval\n -- step has `show_on_home`: only those are listed, since many approvals are announced\n -- elsewhere (a resume link sent to a chat) and every admin and owner could give them.\n CROSS JOIN LATERAL (\n SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m\n ) w\n WHERE q.workspace_id = $1\n AND q.suspend > 0\n AND w.m->>'type' = 'WaitingForEvents'\n AND w.m->'home' IS NOT NULL\n AND ($4::text[] IS NULL OR j.tag = ANY($4))\n ORDER BY j.created_at DESC\n LIMIT $3\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id!",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "root_job_id!",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "runnable_path",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "email!",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "created_by!",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"name": "created_at!",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"name": "flow_path",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "flow_summary",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 8,
|
||||
"name": "approval_conditions",
|
||||
"type_info": "Jsonb"
|
||||
},
|
||||
{
|
||||
"ordinal": 9,
|
||||
"name": "step_summary",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 10,
|
||||
"name": "required_approvals!",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"ordinal": 11,
|
||||
"name": "approvals!",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"ordinal": 12,
|
||||
"name": "approved_by_me!",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text",
|
||||
"Int8",
|
||||
"TextArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88"
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT resume_id, approver, created_at, approved FROM resume_job\n WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "resume_id",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "approver",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "approved",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05"
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT j.id, j.tag, j.kind = 'flownode' AS \"is_node!\",\n COALESCE(s.flow_status, c.flow_status) AS flow_status,\n COALESCE(j.raw_flow, fv.value, fn.flow) AS flow\n FROM v2_job j\n LEFT JOIN v2_job_status s ON s.id = j.id\n LEFT JOIN v2_job_completed c ON c.id = j.id\n LEFT JOIN flow_version fv\n ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id\n LEFT JOIN flow_node fn\n ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id\n WHERE j.id = ANY($1) AND j.workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "tag",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "is_node!",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "flow_status",
|
||||
"type_info": "Jsonb"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "flow",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"UuidArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455"
|
||||
}
|
||||
@@ -348,7 +348,7 @@ fn extract_domain_from_route(
|
||||
/// exports) and credential minting (`job_view_token`) are deliberately absent — those are
|
||||
/// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token
|
||||
/// loses the ability to follow its own run through them.
|
||||
const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [
|
||||
const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [
|
||||
"jobs_u/get_flow/",
|
||||
"jobs_u/get_root_job_id/",
|
||||
"jobs_u/get/",
|
||||
@@ -377,6 +377,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [
|
||||
"jobs/job_signature/",
|
||||
"jobs/wac_approval_urls/",
|
||||
"jobs/flow/approval_step_detail/",
|
||||
"jobs/flow/nested_approvals/",
|
||||
"jobs/completed/get/",
|
||||
"jobs/completed/get_result/",
|
||||
"jobs/completed/get_result_maybe/",
|
||||
@@ -575,7 +576,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool {
|
||||
/// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it
|
||||
/// resolves a node up through the enclosing flows, past the job the check admitted.
|
||||
/// A route added here without that check serves a path-scoped token every job.
|
||||
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [
|
||||
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [
|
||||
"jobs_u/get/",
|
||||
"jobs_u/get_logs/",
|
||||
"jobs_u/get_completed_logs_tail/",
|
||||
@@ -595,6 +596,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [
|
||||
"jobs_u/get_flow/",
|
||||
"jobs_u/flow/approval_info/",
|
||||
"jobs/flow/approval_step_detail/",
|
||||
"jobs/flow/nested_approvals/",
|
||||
"jobs/run_progress/",
|
||||
"jobs/flow/user_states/",
|
||||
"jobs/completed/get/",
|
||||
|
||||
@@ -13174,6 +13174,94 @@ paths:
|
||||
application/json:
|
||||
schema: {}
|
||||
|
||||
/w/{workspace}/jobs/flow/nested_approvals/{job_id}:
|
||||
get:
|
||||
summary: list the approvals given in runs nested under a flow run
|
||||
description: >
|
||||
List the approval steps that runs nested under a flow run (subflows, branch and
|
||||
loop runs, at any depth) went past, with who approved or rejected each and when.
|
||||
The flow run's own approval steps are not listed: they are in its flow status.
|
||||
Only the runs started by a step that can hold an approval step are read: a
|
||||
subflow, or a loop or branch whose steps hold one.
|
||||
operationId: listNestedApprovals
|
||||
tags:
|
||||
- job
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: job_id
|
||||
in: path
|
||||
required: true
|
||||
description: id of the flow run
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
responses:
|
||||
"200":
|
||||
description: the nested approval steps, oldest first
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- approvals
|
||||
- more
|
||||
properties:
|
||||
approvals:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- job_id
|
||||
- subflows
|
||||
- step_id
|
||||
- required_events
|
||||
- approvers
|
||||
properties:
|
||||
job_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: the nested run the step belongs to
|
||||
subflows:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: >
|
||||
ids of the subflow steps leading to the nested run, outermost
|
||||
first. Step ids are unique across a flow, loop and branch steps
|
||||
included, so the first one (or the step itself) is a step of
|
||||
the flow run's own graph
|
||||
step_id:
|
||||
type: string
|
||||
step_summary:
|
||||
type: string
|
||||
required_events:
|
||||
type: integer
|
||||
description: >
|
||||
approvals the step required; fewer approvers means it timed out
|
||||
and the flow continued
|
||||
approvers:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- resume_id
|
||||
- approver
|
||||
properties:
|
||||
resume_id:
|
||||
type: integer
|
||||
approver:
|
||||
type: string
|
||||
approved_at:
|
||||
type: string
|
||||
format: date-time
|
||||
approved:
|
||||
type: boolean
|
||||
more:
|
||||
type: boolean
|
||||
description: >
|
||||
more nested runs than are read, typically a loop with an approval in
|
||||
every iteration: their approvals are on those runs' own pages
|
||||
|
||||
/w/{workspace}/jobs/flow/approval_step_detail/{job_id}/{step_id}:
|
||||
get:
|
||||
summary: get the approval detail of one step of a flow run
|
||||
@@ -13284,8 +13372,9 @@ paths:
|
||||
approvals:
|
||||
type: array
|
||||
description: >
|
||||
approvals received. approved, value and created_at are known only
|
||||
while the run is live; a finished run keeps approver names alone.
|
||||
approvals received. approved and value are known only while the run is
|
||||
live; a finished run keeps approver names and, for approvals recorded
|
||||
since it was kept, created_at.
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
@@ -13305,6 +13394,65 @@ paths:
|
||||
error:
|
||||
description: the run's error, when status is not_resumed
|
||||
|
||||
/w/{workspace}/jobs/approvals/waiting:
|
||||
get:
|
||||
summary: list the runs waiting for an approval the caller can give
|
||||
description: >
|
||||
Runs suspended on an approval step the caller can approve, by the same check the
|
||||
approval itself runs, newest first, excluding steps the caller already approved. A
|
||||
step that does not require login is listed only to callers who can read its run.
|
||||
operationId: listWaitingApprovals
|
||||
tags:
|
||||
- job
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
responses:
|
||||
"200":
|
||||
description: runs waiting for the caller's approval
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [approvals, total]
|
||||
properties:
|
||||
approvals:
|
||||
type: array
|
||||
description: the most recent of the listed runs, at most 100
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- job_id
|
||||
- started_by
|
||||
- created_at
|
||||
- approvals
|
||||
- required_approvals
|
||||
properties:
|
||||
job_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >
|
||||
the suspended flow run, the one its approval page takes: the root
|
||||
run, or the branch, loop or subflow run holding the approval step
|
||||
flow_path:
|
||||
type: string
|
||||
flow_summary:
|
||||
type: string
|
||||
step_summary:
|
||||
type: string
|
||||
started_by:
|
||||
type: string
|
||||
created_at:
|
||||
type: string
|
||||
format: date-time
|
||||
approvals:
|
||||
type: integer
|
||||
description: approvals received so far
|
||||
required_approvals:
|
||||
type: integer
|
||||
total:
|
||||
type: integer
|
||||
description: how many runs are listed in all
|
||||
|
||||
/w/{workspace}/jobs/job_view_token/{id}:
|
||||
get:
|
||||
summary: mint a read-only share token for a job
|
||||
@@ -20297,6 +20445,9 @@ paths:
|
||||
flow_summary:
|
||||
type: string
|
||||
description: summary of the flow or workflow the approval belongs to
|
||||
required_events:
|
||||
type: integer
|
||||
description: approvals the step requires; absent for a workflow as code
|
||||
approvers:
|
||||
type: array
|
||||
items:
|
||||
@@ -20309,6 +20460,11 @@ paths:
|
||||
type: integer
|
||||
approver:
|
||||
type: string
|
||||
approved_at:
|
||||
type: string
|
||||
format: date-time
|
||||
approved:
|
||||
type: boolean
|
||||
view_token:
|
||||
type: string
|
||||
description: >-
|
||||
@@ -20563,6 +20719,11 @@ paths:
|
||||
type: integer
|
||||
approver:
|
||||
type: string
|
||||
approved_at:
|
||||
type: string
|
||||
format: date-time
|
||||
approved:
|
||||
type: boolean
|
||||
required:
|
||||
- resume_id
|
||||
- approver
|
||||
@@ -34443,9 +34604,11 @@ components:
|
||||
- has_preprocessor
|
||||
|
||||
RecentRunStatus:
|
||||
description: a failure someone or something marked as handled is `resolved`, not `failure`
|
||||
description: >
|
||||
a failure someone or something marked as handled is `resolved`, not `failure`; a run
|
||||
waiting for an approval is `suspended`, not `running`
|
||||
type: string
|
||||
enum: [success, failure, resolved, canceled, running]
|
||||
enum: [success, failure, resolved, canceled, running, suspended]
|
||||
|
||||
RecentRunHiddenItem:
|
||||
type: object
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -409,6 +409,11 @@ pub fn workspaced_service() -> Router {
|
||||
"/flow/approval_step_detail/{job_id}/{step_id}",
|
||||
get(get_approval_step_detail),
|
||||
)
|
||||
.route(
|
||||
"/flow/nested_approvals/{job_id}",
|
||||
get(list_nested_approvals),
|
||||
)
|
||||
.route("/approvals/waiting", get(list_waiting_approvals))
|
||||
.route(
|
||||
"/job_view_token/{id}",
|
||||
get(get_job_view_token).layer(cors.clone()),
|
||||
@@ -5348,6 +5353,8 @@ struct ApprovalInfo {
|
||||
step_summary: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
flow_summary: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
required_events: Option<u32>,
|
||||
approvers: Vec<Approval>,
|
||||
/// Share-read-link token for the flow, minted only for callers allowed to view this
|
||||
/// approval. Lets an authenticated workspace-member approver open the run details of
|
||||
@@ -5441,6 +5448,10 @@ fn approval_conditions_from_settings(suspend: &Suspend) -> Option<ApprovalCondit
|
||||
struct ApprovalStepView {
|
||||
skin: ApprovalSkin,
|
||||
summary: Option<String>,
|
||||
required_events: Option<u32>,
|
||||
/// The approval step's job: approvals sent to it count for this step, with those sent to
|
||||
/// the flow itself. Rows for the flow's earlier steps stay until the run finishes.
|
||||
job: Option<Uuid>,
|
||||
}
|
||||
|
||||
async fn get_approval_info(
|
||||
@@ -5529,7 +5540,8 @@ async fn get_approval_info(
|
||||
.and_then(|m| m.get("skin"))
|
||||
.and_then(|v| serde_json::from_value::<ApprovalSkin>(v.clone()).ok())
|
||||
.unwrap_or_default();
|
||||
let step = Some(ApprovalStepView { skin, summary: None });
|
||||
let step =
|
||||
Some(ApprovalStepView { skin, summary: None, required_events: None, job: None });
|
||||
(form, description, default_args, enums, run_ac, None, step)
|
||||
} else {
|
||||
let fs = row
|
||||
@@ -5609,6 +5621,10 @@ async fn get_approval_info(
|
||||
.and_then(|module| module.suspend.as_ref())
|
||||
.and_then(approval_conditions_from_settings)
|
||||
});
|
||||
let step_job_id = fs
|
||||
.as_ref()
|
||||
.and_then(|s| approval_step.and_then(|step| s.modules.get(step)))
|
||||
.and_then(|m| m.job());
|
||||
let step = approval_module.map(|module| ApprovalStepView {
|
||||
skin: module
|
||||
.suspend
|
||||
@@ -5616,13 +5632,11 @@ async fn get_approval_info(
|
||||
.and_then(|s| s.skin)
|
||||
.unwrap_or_default(),
|
||||
summary: module.summary.clone().filter(|s| !s.trim().is_empty()),
|
||||
required_events: module.suspend.as_ref().and_then(|s| s.required_events),
|
||||
job: step_job_id,
|
||||
});
|
||||
|
||||
// Fetch description, default_args, and enums from the step's completed job result
|
||||
let step_job_id = fs
|
||||
.as_ref()
|
||||
.and_then(|s| approval_step.and_then(|step| s.modules.get(step)))
|
||||
.and_then(|m| m.job());
|
||||
let (desc, default_args, enums) = if let Some(sjid) = step_job_id {
|
||||
let result: Option<serde_json::Value> = sqlx::query_scalar(
|
||||
"SELECT result FROM v2_job_completed WHERE id = $1 AND workspace_id = $2",
|
||||
@@ -5644,6 +5658,8 @@ async fn get_approval_info(
|
||||
};
|
||||
|
||||
let skin = step.as_ref().map(|s| s.skin).unwrap_or_default();
|
||||
let required_events = step.as_ref().and_then(|s| s.required_events);
|
||||
let step_job = step.as_ref().and_then(|s| s.job);
|
||||
let step_summary = step.and_then(|s| s.summary);
|
||||
|
||||
let user_auth_required = approval_conditions
|
||||
@@ -5678,22 +5694,27 @@ async fn get_approval_info(
|
||||
skin,
|
||||
step_summary: None,
|
||||
flow_summary: None,
|
||||
required_events: None,
|
||||
approvers: vec![],
|
||||
view_token: None,
|
||||
}));
|
||||
}
|
||||
|
||||
// Get existing approvers
|
||||
let approvers: Vec<Approval> = sqlx::query_as::<_, (i32, Option<String>)>(
|
||||
"SELECT resume_id, approver FROM resume_job WHERE flow = $1",
|
||||
let approvers: Vec<Approval> = sqlx::query!(
|
||||
"SELECT resume_id, approver, created_at, approved FROM resume_job
|
||||
WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))",
|
||||
job_id,
|
||||
step_job
|
||||
)
|
||||
.bind(&job_id)
|
||||
.fetch_all(&db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(rid, approver)| Approval {
|
||||
resume_id: rid as u16,
|
||||
approver: approver.unwrap_or_else(|| "anonymous".to_string()),
|
||||
.map(|r| Approval {
|
||||
resume_id: r.resume_id as u16,
|
||||
approver: r.approver.unwrap_or_else(|| "anonymous".to_string()),
|
||||
approved_at: Some(r.created_at),
|
||||
approved: Some(r.approved),
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -5725,6 +5746,7 @@ async fn get_approval_info(
|
||||
skin,
|
||||
step_summary,
|
||||
flow_summary: row.flow_summary,
|
||||
required_events,
|
||||
approvers,
|
||||
view_token,
|
||||
}))
|
||||
@@ -5744,11 +5766,377 @@ enum ApprovalStepStatus {
|
||||
NotResumed,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct WaitingApproval {
|
||||
/// The suspended flow, the one its approval page takes: the root run, or the branch, loop or
|
||||
/// subflow run holding the step.
|
||||
job_id: Uuid,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
flow_path: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
flow_summary: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
step_summary: Option<String>,
|
||||
started_by: String,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
approvals: i64,
|
||||
required_approvals: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct WaitingApprovals {
|
||||
approvals: Vec<WaitingApproval>,
|
||||
/// Every listed run, of which `approvals` holds the most recent.
|
||||
total: usize,
|
||||
}
|
||||
|
||||
// ponytail: scans the most recent suspended runs only; a workspace past this many waiting
|
||||
// approvals needs the approver check in SQL rather than in `can_approve_step`.
|
||||
const WAITING_APPROVALS_SCAN: i64 = 1000;
|
||||
const WAITING_APPROVALS_RETURNED: usize = 100;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct NestedApproval {
|
||||
job_id: Uuid,
|
||||
subflows: Vec<String>,
|
||||
step_id: String,
|
||||
step_summary: Option<String>,
|
||||
/// Fewer approvers than this on a step that went past: it timed out and continued.
|
||||
required_events: u64,
|
||||
approvers: Vec<Approval>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct NestedApprovals {
|
||||
approvals: Vec<NestedApproval>,
|
||||
more: bool,
|
||||
}
|
||||
|
||||
/// Whether a step can start a run holding an approval step: a subflow, whose steps its caller
|
||||
/// does not carry, or a loop or branch whose own steps hold one.
|
||||
fn may_hold_approval(step: &serde_json::Value) -> bool {
|
||||
let holds = |modules: &serde_json::Value| {
|
||||
modules
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|m| m.get("suspend").is_some_and(|s| !s.is_null()) || may_hold_approval(m))
|
||||
};
|
||||
let branches = |v: &serde_json::Value| {
|
||||
v["branches"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|b| holds(&b["modules"]))
|
||||
};
|
||||
let v = &step["value"];
|
||||
match v["type"].as_str() {
|
||||
Some("flow") => true,
|
||||
Some("forloopflow" | "whileloopflow") => holds(&v["modules"]),
|
||||
Some("branchone") => holds(&v["default"]) || branches(v),
|
||||
Some("branchall") => branches(v),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the steps under `modules`, at any depth, that may hold an approval. Read from a
|
||||
/// flow's full definition: a loop or branch run's own (`flow_node`) keeps nested loop and branch
|
||||
/// bodies as `modules_node` references, so its inline steps are not all of them. Step ids are
|
||||
/// unique across a flow, so its loop and branch runs look their steps up here.
|
||||
fn approval_holders(modules: &[serde_json::Value], out: &mut HashSet<String>) {
|
||||
for m in modules {
|
||||
if may_hold_approval(m) {
|
||||
if let Some(id) = m["id"].as_str() {
|
||||
out.insert(id.to_string());
|
||||
}
|
||||
}
|
||||
let v = &m["value"];
|
||||
let nested = std::iter::once(&v["modules"])
|
||||
.chain(std::iter::once(&v["default"]))
|
||||
.chain(v["branches"].as_array().into_iter().flatten().map(|b| &b["modules"]));
|
||||
for body in nested {
|
||||
approval_holders(body.as_array().map(Vec::as_slice).unwrap_or_default(), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ponytail: a loop whose steps hold an approval has one per iteration; past this many nested
|
||||
// runs read, the rest stay on their own runs' pages.
|
||||
const NESTED_RUNS_READ: usize = 200;
|
||||
|
||||
/// The approval steps that runs nested under a flow run (subflows, branch and loop runs, at any
|
||||
/// depth) went past. Who approved them is kept on those runs, not on the flow run. Only the
|
||||
/// runs started by a step that can hold an approval step are read, one level at a time.
|
||||
async fn list_nested_approvals(
|
||||
OptViewToken(view_token): OptViewToken,
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path((w_id, flow_id)): Path<(String, Uuid)>,
|
||||
) -> error::Result<Json<NestedApprovals>> {
|
||||
let created_by = sqlx::query_scalar!(
|
||||
"SELECT created_by FROM v2_job WHERE id = $1 AND workspace_id = $2",
|
||||
flow_id,
|
||||
w_id
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound(format!("Job {flow_id} not found")))?;
|
||||
require_job_read_access(
|
||||
&db,
|
||||
&user_db,
|
||||
&authed,
|
||||
&w_id,
|
||||
&flow_id,
|
||||
&created_by,
|
||||
view_token.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let modules = |v: &Option<serde_json::Value>| -> Vec<serde_json::Value> {
|
||||
v.as_ref()
|
||||
.and_then(|v| v.get("modules"))
|
||||
.and_then(|m| m.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let scope_tags = get_scope_tags(&authed);
|
||||
// Each run to read, with the subflow steps leading to it (none for the flow run itself) and,
|
||||
// for a loop or branch run, the steps of its flow that may hold an approval.
|
||||
type Holders = std::sync::Arc<HashSet<String>>;
|
||||
let mut level: HashMap<Uuid, (Option<Vec<String>>, Option<Holders>)> =
|
||||
HashMap::from([(flow_id, (None, None))]);
|
||||
let mut seen: HashSet<Uuid> = HashSet::from([flow_id]);
|
||||
let mut approvals = vec![];
|
||||
let mut more = false;
|
||||
while !level.is_empty() {
|
||||
let ids: Vec<Uuid> = level.keys().copied().collect();
|
||||
let rows = sqlx::query!(
|
||||
r#"SELECT j.id, j.tag, j.kind = 'flownode' AS "is_node!",
|
||||
COALESCE(s.flow_status, c.flow_status) AS flow_status,
|
||||
COALESCE(j.raw_flow, fv.value, fn.flow) AS flow
|
||||
FROM v2_job j
|
||||
LEFT JOIN v2_job_status s ON s.id = j.id
|
||||
LEFT JOIN v2_job_completed c ON c.id = j.id
|
||||
LEFT JOIN flow_version fv
|
||||
ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id
|
||||
LEFT JOIN flow_node fn
|
||||
ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id
|
||||
WHERE j.id = ANY($1) AND j.workspace_id = $2"#,
|
||||
&ids,
|
||||
w_id
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
let mut next = HashMap::new();
|
||||
for r in rows {
|
||||
let (at, inherited) = level.get(&r.id).cloned().unwrap_or_default();
|
||||
let defs = modules(&r.flow);
|
||||
let holders = match inherited {
|
||||
Some(h) if r.is_node => h,
|
||||
_ => {
|
||||
let mut h = HashSet::new();
|
||||
approval_holders(&defs, &mut h);
|
||||
std::sync::Arc::new(h)
|
||||
}
|
||||
};
|
||||
let statuses = modules(&r.flow_status);
|
||||
// The read check admitted the flow run on its own tag only. A nested run outside
|
||||
// the caller's tag scope is still walked through, so it cannot hide a descendant
|
||||
// the caller could read directly, but its approvals are not returned.
|
||||
let in_scope = scope_tags.as_ref().map_or(true, |t| t.contains(&r.tag.as_str()));
|
||||
if let (Some(subflows), true) = (&at, in_scope) {
|
||||
let flow_step = r.flow_status.as_ref().and_then(|f| f["step"].as_u64());
|
||||
for (i, m) in statuses.iter().enumerate() {
|
||||
// A step `skip_if` skipped never asked for approval.
|
||||
if m["type"] != "Success" || m["skipped"].as_bool() == Some(true) {
|
||||
continue;
|
||||
}
|
||||
let step_id = m["id"].as_str().unwrap_or_default();
|
||||
let def = defs.iter().find(|d| d["id"] == step_id);
|
||||
if !def.is_some_and(|d| !d["suspend"].is_null()) {
|
||||
continue;
|
||||
}
|
||||
let approvers: Vec<Approval> =
|
||||
serde_json::from_value(m["approvers"].clone()).unwrap_or_default();
|
||||
// No response and the flow moved past the step after it: it timed out and
|
||||
// continued. While it waits, `step` is that next step's index.
|
||||
if approvers.is_empty() && !flow_step.is_some_and(|s| s > i as u64 + 1) {
|
||||
continue;
|
||||
}
|
||||
let step_summary = def
|
||||
.and_then(|d| d["summary"].as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string);
|
||||
let required_events = def
|
||||
.and_then(|d| d["suspend"]["required_events"].as_u64())
|
||||
.unwrap_or(1);
|
||||
approvals.push(NestedApproval {
|
||||
job_id: r.id,
|
||||
subflows: subflows.clone(),
|
||||
step_id: step_id.to_string(),
|
||||
step_summary,
|
||||
required_events,
|
||||
approvers,
|
||||
});
|
||||
}
|
||||
}
|
||||
for d in &defs {
|
||||
let Some(step) = d["id"].as_str().filter(|s| holders.contains(*s)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(status) = statuses.iter().find(|s| s["id"] == step) else {
|
||||
continue;
|
||||
};
|
||||
let mut subflows = at.clone().unwrap_or_default();
|
||||
if d["value"]["type"] == "flow" {
|
||||
subflows.push(step.to_string());
|
||||
}
|
||||
// A subflow or branch run is the step's `job`, a loop's or a branch's runs its
|
||||
// `flow_jobs`.
|
||||
let started = std::iter::once(&status["job"])
|
||||
.chain(status["flow_jobs"].as_array().into_iter().flatten())
|
||||
.filter_map(|v| v.as_str()?.parse::<Uuid>().ok());
|
||||
for child in started {
|
||||
if seen.len() > NESTED_RUNS_READ {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
if seen.insert(child) {
|
||||
next.insert(child, (Some(subflows.clone()), Some(holders.clone())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
approvals.sort_by_key(|a| a.approvers.first().and_then(|a| a.approved_at));
|
||||
Ok(Json(NestedApprovals { approvals, more }))
|
||||
}
|
||||
|
||||
/// The runs waiting on an approval step set to show on Home that the caller can approve, by the
|
||||
/// same check the resume boundary runs. A step anyone holding its link can approve is listed
|
||||
/// only to those who can read its run, or every member would learn the names of flows they
|
||||
/// have no access to.
|
||||
async fn list_waiting_approvals(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
) -> error::Result<Json<WaitingApprovals>> {
|
||||
// A token confined to some tags reads no job outside them, here as in every job read.
|
||||
let scope_tags =
|
||||
get_scope_tags(&authed).map(|v| v.into_iter().map(str::to_string).collect::<Vec<_>>());
|
||||
let rows = sqlx::query!(
|
||||
r#"
|
||||
SELECT j.id AS "id!",
|
||||
COALESCE(j.root_job, j.parent_job, j.id) AS "root_job_id!",
|
||||
j.runnable_path,
|
||||
j.permissioned_as_email AS "email!",
|
||||
j.created_by AS "created_by!",
|
||||
j.created_at AS "created_at!",
|
||||
COALESCE(rj.runnable_path, j.runnable_path) AS flow_path,
|
||||
NULLIF(f.summary, '') AS flow_summary,
|
||||
s.flow_status->'approval_conditions' AS approval_conditions,
|
||||
NULLIF(w.m->'home'->>'step_summary', '') AS step_summary,
|
||||
COALESCE((w.m->>'count')::bigint, 1) AS "required_approvals!",
|
||||
-- Counted as the worker counts them: those sent to the approval step's job,
|
||||
-- plus those sent to the flow itself.
|
||||
(SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid))
|
||||
AS "approvals!",
|
||||
EXISTS(SELECT 1 FROM resume_job r
|
||||
WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2)
|
||||
AS "approved_by_me!"
|
||||
FROM v2_job_queue q
|
||||
JOIN v2_job j ON j.id = q.id
|
||||
JOIN v2_job_status s ON s.id = q.id
|
||||
LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job)
|
||||
LEFT JOIN flow f
|
||||
ON f.workspace_id = j.workspace_id
|
||||
AND f.path = COALESCE(rj.runnable_path, j.runnable_path)
|
||||
-- The step waiting on the approval, which the worker marks `home` when the approval
|
||||
-- step has `show_on_home`: only those are listed, since many approvals are announced
|
||||
-- elsewhere (a resume link sent to a chat) and every admin and owner could give them.
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m
|
||||
) w
|
||||
WHERE q.workspace_id = $1
|
||||
AND q.suspend > 0
|
||||
AND w.m->>'type' = 'WaitingForEvents'
|
||||
AND w.m->'home' IS NOT NULL
|
||||
AND ($4::text[] IS NULL OR j.tag = ANY($4))
|
||||
ORDER BY j.created_at DESC
|
||||
LIMIT $3
|
||||
"#,
|
||||
&w_id,
|
||||
&authed.username,
|
||||
WAITING_APPROVALS_SCAN,
|
||||
scope_tags.as_deref(),
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
|
||||
let candidates: Vec<_> = rows
|
||||
.into_iter()
|
||||
.filter(|r| !r.approved_by_me)
|
||||
.filter_map(|r| {
|
||||
let ac = r
|
||||
.approval_conditions
|
||||
.as_ref()
|
||||
.and_then(|v| serde_json::from_value::<ApprovalConditions>(v.clone()).ok());
|
||||
let opt_authed = Some(authed.clone());
|
||||
can_approve_step(&opt_authed, &ac, r.runnable_path.as_deref(), &r.email).then(|| {
|
||||
let auth_required = ac.as_ref().is_some_and(|ac| ac.user_auth_required);
|
||||
(r, auth_required)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let root_ids: Vec<Uuid> = candidates
|
||||
.iter()
|
||||
.filter(|(_, auth_required)| !auth_required)
|
||||
.map(|(r, _)| r.root_job_id)
|
||||
.collect();
|
||||
let readable: std::collections::HashSet<Uuid> = if root_ids.is_empty() {
|
||||
Default::default()
|
||||
} else {
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let ids = sqlx::query_scalar!("SELECT id FROM v2_job WHERE id = ANY($1)", &root_ids)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
ids.into_iter().collect()
|
||||
};
|
||||
|
||||
let listed: Vec<WaitingApproval> = candidates
|
||||
.into_iter()
|
||||
.filter_map(|(r, auth_required)| {
|
||||
(auth_required || readable.contains(&r.root_job_id)).then(|| WaitingApproval {
|
||||
job_id: r.id,
|
||||
flow_path: r.flow_path,
|
||||
flow_summary: r.flow_summary,
|
||||
step_summary: r.step_summary,
|
||||
started_by: r.created_by,
|
||||
created_at: r.created_at,
|
||||
approvals: r.approvals,
|
||||
required_approvals: r.required_approvals,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let total = listed.len();
|
||||
let approvals = listed
|
||||
.into_iter()
|
||||
.take(WAITING_APPROVALS_RETURNED)
|
||||
.collect();
|
||||
Ok(Json(WaitingApprovals { approvals, total }))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StepApproval {
|
||||
resume_id: u16,
|
||||
approver: String,
|
||||
/// Known only while the run is live: a finished run keeps approver names alone.
|
||||
/// Known only while the run is live, as is `value`: a finished run keeps approver names and
|
||||
/// times alone.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
approved: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -5861,7 +6249,6 @@ async fn get_approval_step_detail(
|
||||
module: Option<serde_json::Value>,
|
||||
next_module: Option<serde_json::Value>,
|
||||
module_def: Option<serde_json::Value>,
|
||||
is_last_module: bool,
|
||||
run_approval_conditions: Option<serde_json::Value>,
|
||||
suspend_until: Option<chrono::DateTime<chrono::Utc>>,
|
||||
flow_error: Option<serde_json::Value>,
|
||||
@@ -5880,10 +6267,6 @@ async fn get_approval_step_detail(
|
||||
'$.modules[*] ? (@.id == $id)',
|
||||
jsonb_build_object('id', $3::text)
|
||||
) AS module_def,
|
||||
COALESCE(
|
||||
COALESCE(j.raw_flow, fv.value, fn.flow)->'modules'->-1->>'id' = $3,
|
||||
false
|
||||
) AS is_last_module,
|
||||
s.flow_status->'approval_conditions' AS run_approval_conditions,
|
||||
q.suspend_until,
|
||||
c.result->'error' AS flow_error,
|
||||
@@ -5947,12 +6330,13 @@ async fn get_approval_step_detail(
|
||||
.module_def
|
||||
.and_then(|v| serde_json::from_value(v).ok())
|
||||
.ok_or_else(not_found)?;
|
||||
// The worker holds a run only after a step with a positive `required_events` that has a
|
||||
// step after it (`needs_resume`); the last step's suspend settings never stop the run.
|
||||
// The worker holds a run only after a step with a positive `required_events`. A last step
|
||||
// holds it too: the worker appends a virtual step after it (`add_virtual_items_if_necessary`),
|
||||
// which the stored flow does not carry.
|
||||
let suspend = module_def
|
||||
.suspend
|
||||
.as_ref()
|
||||
.filter(|s| s.required_events.unwrap_or(0) > 0 && !row.is_last_module)
|
||||
.filter(|s| s.required_events.unwrap_or(0) > 0)
|
||||
.ok_or_else(|| {
|
||||
Error::BadRequest(format!("Step {step_id} is not an approval (suspend) step"))
|
||||
})?;
|
||||
@@ -5999,9 +6383,9 @@ async fn get_approval_step_detail(
|
||||
.map(|a| StepApproval {
|
||||
resume_id: a.resume_id,
|
||||
approver: a.approver.clone(),
|
||||
approved: None,
|
||||
approved: a.approved,
|
||||
value: None,
|
||||
created_at: None,
|
||||
created_at: a.approved_at,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
@@ -6594,6 +6978,8 @@ pub async fn get_suspended_job_flow(
|
||||
.map(|x| Approval {
|
||||
resume_id: x.resume_id as u16,
|
||||
approver: x.approver.unwrap_or_else(|| "anonymous".to_string()),
|
||||
approved_at: None,
|
||||
approved: None,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
@@ -13625,3 +14011,84 @@ mod approval_view_gate_tests {
|
||||
assert!(from_settings(serde_json::json!({})).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod nested_approvals_tests {
|
||||
use super::{approval_holders, may_hold_approval};
|
||||
use serde_json::json;
|
||||
|
||||
fn script(id: &str) -> serde_json::Value {
|
||||
json!({"id": id, "value": {"type": "rawscript", "content": "", "language": "bun"}})
|
||||
}
|
||||
|
||||
fn approval(id: &str) -> serde_json::Value {
|
||||
let mut s = script(id);
|
||||
s["suspend"] = json!({"required_events": 1});
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_only_steps_that_can_hold_an_approval() {
|
||||
// A subflow's steps are not in its caller's definition: always followed.
|
||||
assert!(may_hold_approval(
|
||||
&json!({"id": "sub", "value": {"type": "flow", "path": "f/a/b"}})
|
||||
));
|
||||
let lp = |modules| json!({"id": "l", "value": {"type": "forloopflow", "modules": modules}});
|
||||
assert!(!may_hold_approval(&lp(json!([script("a")]))));
|
||||
assert!(may_hold_approval(&lp(json!([script("a"), approval("b")]))));
|
||||
// At any depth of inline loops.
|
||||
assert!(may_hold_approval(&lp(json!([lp(json!([approval("b")]))]))));
|
||||
assert!(may_hold_approval(
|
||||
&json!({"id": "w", "value": {"type": "whileloopflow",
|
||||
"modules": [{"id": "sub", "value": {"type": "flow", "path": "f/a/b"}}]}})
|
||||
));
|
||||
let branches = |kind, default, branch| {
|
||||
json!({"id": "br", "value": {"type": kind, "default": default,
|
||||
"branches": [{"modules": branch}]}})
|
||||
};
|
||||
assert!(!may_hold_approval(&branches(
|
||||
"branchone",
|
||||
json!([script("a")]),
|
||||
json!([script("b")])
|
||||
)));
|
||||
assert!(may_hold_approval(&branches(
|
||||
"branchone",
|
||||
json!([approval("a")]),
|
||||
json!([])
|
||||
)));
|
||||
assert!(may_hold_approval(&branches(
|
||||
"branchone",
|
||||
json!([]),
|
||||
json!([approval("b")])
|
||||
)));
|
||||
assert!(may_hold_approval(&branches(
|
||||
"branchall",
|
||||
json!(null),
|
||||
json!([approval("b")])
|
||||
)));
|
||||
assert!(!may_hold_approval(&branches(
|
||||
"branchall",
|
||||
json!(null),
|
||||
json!([script("b")])
|
||||
)));
|
||||
// A step's own suspend is the caller's own approval, not a nested one.
|
||||
assert!(!may_hold_approval(&approval("a")));
|
||||
// `"suspend": null` is not an approval step.
|
||||
let mut nulled = script("a");
|
||||
nulled["suspend"] = serde_json::Value::Null;
|
||||
assert!(!may_hold_approval(&lp(json!([nulled]))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holders_reach_into_nested_loop_bodies() {
|
||||
// A loop run's own definition keeps the inner loop as a `modules_node` reference, so
|
||||
// the inner loop is found only from the flow's full definition.
|
||||
let inner = json!({"id": "inner", "value": {"type": "forloopflow",
|
||||
"modules": [approval("s")]}});
|
||||
let outer = json!({"id": "outer", "value": {"type": "forloopflow",
|
||||
"modules": [script("a"), inner]}});
|
||||
let mut holders = std::collections::HashSet::new();
|
||||
approval_holders(&[outer, script("z")], &mut holders);
|
||||
assert_eq!(holders, ["outer", "inner"].map(String::from).into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,9 +159,19 @@ pub(crate) async fn list_recent_runs(
|
||||
ORDER BY c.completed_at DESC
|
||||
LIMIT $4)
|
||||
UNION ALL
|
||||
(SELECT q.id, NULL, q.started_at, NULL, NULL
|
||||
(SELECT q.id,
|
||||
-- `suspend` also parks a workflow as code on its children or a sleep: only
|
||||
-- a wait on an approval is one.
|
||||
CASE WHEN q.suspend > 0 AND (
|
||||
s.flow_status->'modules'->((s.flow_status->>'step')::int)->>'type'
|
||||
= 'WaitingForEvents'
|
||||
OR s.workflow_as_code_status->'_checkpoint'->'pending_steps'->>'mode'
|
||||
= 'approval'
|
||||
) THEN 'suspended' END,
|
||||
q.started_at, NULL, NULL
|
||||
FROM v2_job_queue q
|
||||
JOIN v2_job j ON j.id = q.id
|
||||
LEFT JOIN v2_job_status s ON s.id = q.id
|
||||
WHERE q.workspace_id = $1 AND q.running AND {LISTED_ROOT_RUN}
|
||||
AND NOT EXISTS (SELECT 1 FROM v2_job_completed c WHERE c.id = q.id))
|
||||
)
|
||||
@@ -176,6 +186,7 @@ pub(crate) async fn list_recent_runs(
|
||||
'script') = 'flow' THEN 'flow'
|
||||
ELSE 'script' END AS kind,
|
||||
CASE WHEN r.status IS NULL THEN 'running'
|
||||
WHEN r.status = 'suspended' THEN 'suspended'
|
||||
WHEN r.status IN ('success', 'skipped') THEN 'success'
|
||||
WHEN r.status = 'canceled' THEN 'canceled'
|
||||
WHEN EXISTS (SELECT 1 FROM job_resolution jr WHERE jr.job_id = r.id) THEN 'resolved'
|
||||
|
||||
@@ -136,6 +136,13 @@ pub enum BranchChosen {
|
||||
pub struct Approval {
|
||||
pub resume_id: u16,
|
||||
pub approver: String,
|
||||
/// Kept on the step because the resume rows that also record it are deleted with the run.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approved_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
/// False for a rejection the flow continued past (`continue_on_disapprove_timeout`): the
|
||||
/// step succeeds and lists who rejected it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approved: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
@@ -210,6 +217,7 @@ struct UntaggedFlowStatusModule {
|
||||
type_: String,
|
||||
id: Option<String>,
|
||||
count: Option<u16>,
|
||||
home: Option<HomeListing>,
|
||||
progress: Option<u8>,
|
||||
job: Option<Uuid>,
|
||||
iterator: Option<Iterator>,
|
||||
@@ -266,6 +274,12 @@ pub enum AgentAction {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct HomeListing {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub step_summary: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ApprovalCall {
|
||||
pub function_name: String,
|
||||
@@ -282,6 +296,10 @@ pub enum FlowStatusModule {
|
||||
id: String,
|
||||
count: u16,
|
||||
job: Uuid,
|
||||
/// Set while waiting on an approval step with `show_on_home`, so the Home list of
|
||||
/// approvals reads it here rather than in each run's flow definition.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
home: Option<HomeListing>,
|
||||
},
|
||||
WaitingForExecutor {
|
||||
id: String,
|
||||
@@ -385,6 +403,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule {
|
||||
job: untagged
|
||||
.job
|
||||
.ok_or_else(|| serde::de::Error::missing_field("job"))?,
|
||||
home: untagged.home,
|
||||
}),
|
||||
"WaitingForExecutor" => Ok(FlowStatusModule::WaitingForExecutor {
|
||||
id: untagged
|
||||
|
||||
@@ -604,6 +604,10 @@ pub struct Suspend {
|
||||
pub continue_on_disapprove_timeout: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skin: Option<ApprovalSkin>,
|
||||
/// Lists the waiting step on its approvers' Home. Off unless set: an approval announced
|
||||
/// elsewhere (a resume link sent to a chat) would otherwise sit there unanswered.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub show_on_home: Option<bool>,
|
||||
}
|
||||
|
||||
/// How an approval request is presented, on the approval page and in Slack/Teams messages.
|
||||
|
||||
@@ -41,7 +41,8 @@ use windmill_common::db::Authed;
|
||||
use windmill_common::flow_conversations::{add_message_to_conversation_tx, MessageType};
|
||||
use windmill_common::flow_status::{
|
||||
ApprovalConditions, ContinuedOnError, FlowJobDuration, FlowJobsDuration,
|
||||
FlowStatusModuleWParent, Iterator as FlowIterator, JobResult, MAX_CONTINUED_ON_ERROR,
|
||||
FlowStatusModuleWParent, HomeListing, Iterator as FlowIterator, JobResult,
|
||||
MAX_CONTINUED_ON_ERROR,
|
||||
};
|
||||
use windmill_common::flows::{add_virtual_items_if_necessary, Branch, FlowNodeId, StopAfterIf};
|
||||
use windmill_common::jobs::{
|
||||
@@ -3600,6 +3601,7 @@ pub struct ResumeRow {
|
||||
pub approver: Option<String>,
|
||||
pub approved: bool,
|
||||
pub resume_id: i32,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl ResumeRow {
|
||||
@@ -4195,7 +4197,7 @@ async fn push_next_flow_job(
|
||||
// Query for both step-level resumes (job = step_id) and flow-level resumes (job = flow_id)
|
||||
// Flow-level resumes allow pre-approvals that can be consumed by any suspend step
|
||||
let resumes = sqlx::query_as::<_, ResumeRow>(
|
||||
"SELECT value, approver, resume_id, approved FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC",
|
||||
"SELECT value, approver, resume_id, approved, created_at FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(last)
|
||||
.bind(flow_job.id)
|
||||
@@ -4356,7 +4358,9 @@ async fn push_next_flow_job(
|
||||
resume_id: r.resume_id as u16,
|
||||
approver: r
|
||||
.approver.clone()
|
||||
.unwrap_or_else(|| "unknown".to_string())
|
||||
.unwrap_or_else(|| "unknown".to_string()),
|
||||
approved_at: Some(r.created_at),
|
||||
approved: Some(r.approved),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
),
|
||||
@@ -4399,7 +4403,14 @@ async fn push_next_flow_job(
|
||||
json!(FlowStatusModule::WaitingForEvents {
|
||||
id: status_module.id(),
|
||||
count: required_events,
|
||||
job: last
|
||||
job: last,
|
||||
home: (suspend.show_on_home == Some(true)).then(|| HomeListing {
|
||||
step_summary: usize::try_from(status.step - 1)
|
||||
.ok()
|
||||
.and_then(|i| flow.modules.get(i))
|
||||
.and_then(|m| m.summary.clone())
|
||||
.filter(|s| !s.is_empty()),
|
||||
}),
|
||||
}),
|
||||
(required_events.saturating_sub(resume_messages.len() as u16)) as i32,
|
||||
Duration::from_secs(
|
||||
@@ -7574,6 +7585,7 @@ mod tests {
|
||||
approver: Some("ann".to_string()),
|
||||
approved: false,
|
||||
resume_id: 0,
|
||||
created_at: chrono::Utc::now(),
|
||||
};
|
||||
assert_eq!(
|
||||
denial(json!({"reason": " too risky "})).disapproval_error(),
|
||||
|
||||
Generated
+1
-1
File diff suppressed because one or more lines are too long
@@ -632,7 +632,14 @@
|
||||
</div>
|
||||
|
||||
{#if jobId}
|
||||
<FlowProgressBar {job} bind:this={flowProgressBar} slim textPosition="bottom" showStepId />
|
||||
<FlowProgressBar
|
||||
{job}
|
||||
bind:this={flowProgressBar}
|
||||
slim
|
||||
textPosition="bottom"
|
||||
showStepId
|
||||
waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if job}
|
||||
|
||||
@@ -152,10 +152,17 @@
|
||||
|
||||
let storedToolCallJobs: Record<string, Job> = $state({})
|
||||
let toolCallIndicesToLoad: string[] = $state([])
|
||||
|
||||
let inner: FlowStatusViewerInner | undefined = $state(undefined)
|
||||
/** Selects a step in the graph, as a click on its node does. */
|
||||
export function selectStep(id: string) {
|
||||
inner?.selectStep(id)
|
||||
}
|
||||
</script>
|
||||
|
||||
{#key jobId}
|
||||
<FlowStatusViewerInner
|
||||
bind:this={inner}
|
||||
onJobsLoaded={({ job, force }) => {
|
||||
if (job.script_path != lastScriptPath && job.script_path) {
|
||||
lastScriptPath = job.script_path
|
||||
|
||||
@@ -348,6 +348,49 @@
|
||||
|
||||
let selectionManager = new SelectionManager()
|
||||
|
||||
function onGraphSelect(e: string | FlowModule) {
|
||||
subflowPathChain = undefined
|
||||
if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') {
|
||||
rightColumnSelect = 'node_status'
|
||||
}
|
||||
if (typeof e == 'string') {
|
||||
if (e == 'Input') {
|
||||
selectedNode = 'start'
|
||||
stepDetail = undefined
|
||||
} else if (e == 'Result') {
|
||||
selectedNode = 'end'
|
||||
stepDetail = 'end'
|
||||
} else {
|
||||
const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e
|
||||
const resolved = resolveLoadedExpandedSubflowStep(
|
||||
e,
|
||||
job?.raw_flow?.modules ?? [],
|
||||
expandedSubflows ?? {}
|
||||
)
|
||||
stepDetail =
|
||||
resolved?.module ?? dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id)
|
||||
subflowPathChain = resolved?.pathChain
|
||||
selectedNode = e
|
||||
if (e.startsWith(AI_TOOL_CALL_PREFIX)) {
|
||||
const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-')
|
||||
const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId)
|
||||
const jIdx = Number(j)
|
||||
const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx
|
||||
toolCallStore?.addToolCallToLoad(storeKey)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stepDetail = e
|
||||
selectedNode = e.id
|
||||
}
|
||||
}
|
||||
|
||||
/** Selects a step from outside the graph, as a click on its node does. */
|
||||
export function selectStep(id: string) {
|
||||
selectionManager.selectId(id)
|
||||
onGraphSelect(id)
|
||||
}
|
||||
|
||||
function onFlowModuleId() {
|
||||
let modId = flowJobIds?.moduleId
|
||||
if (modId) {
|
||||
@@ -602,7 +645,7 @@
|
||||
let jobStatus = job?.flow_status?.modules?.[job?.flow_status.step]
|
||||
|
||||
if (jobStatus && jobStatus.count != undefined) {
|
||||
suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job! }
|
||||
suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job!, prefix }
|
||||
} else if (suspendStatus.val[jobId ?? ''] != undefined) {
|
||||
delete suspendStatus.val[jobId ?? '']
|
||||
}
|
||||
@@ -1612,10 +1655,6 @@
|
||||
)
|
||||
)
|
||||
|
||||
let totalEventsWaiting = $derived(
|
||||
Object.values(suspendStatus?.val ?? {}).reduce((a, b) => a + (b?.nb ?? 0), 0)
|
||||
)
|
||||
|
||||
let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? [])
|
||||
</script>
|
||||
|
||||
@@ -2175,11 +2214,6 @@
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
{#if totalEventsWaiting}
|
||||
<span class="text-sm">
|
||||
Flow suspended, waiting for {totalEventsWaiting} events
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<FlowGraphV2
|
||||
{selectionManager}
|
||||
@@ -2193,43 +2227,7 @@
|
||||
flowModuleStates={localModuleStates}
|
||||
runDone={job?.type === 'CompletedJob'}
|
||||
bind:expandedSubflows
|
||||
onSelect={(e) => {
|
||||
subflowPathChain = undefined
|
||||
if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') {
|
||||
rightColumnSelect = 'node_status'
|
||||
}
|
||||
if (typeof e == 'string') {
|
||||
if (e == 'Input') {
|
||||
selectedNode = 'start'
|
||||
stepDetail = undefined
|
||||
} else if (e == 'Result') {
|
||||
selectedNode = 'end'
|
||||
stepDetail = 'end'
|
||||
} else {
|
||||
const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e
|
||||
const resolved = resolveLoadedExpandedSubflowStep(
|
||||
e,
|
||||
job?.raw_flow?.modules ?? [],
|
||||
expandedSubflows ?? {}
|
||||
)
|
||||
stepDetail =
|
||||
resolved?.module ??
|
||||
dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id)
|
||||
subflowPathChain = resolved?.pathChain
|
||||
selectedNode = e
|
||||
if (e.startsWith(AI_TOOL_CALL_PREFIX)) {
|
||||
const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-')
|
||||
const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId)
|
||||
const jIdx = Number(j)
|
||||
const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx
|
||||
toolCallStore?.addToolCallToLoad(storeKey)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stepDetail = e
|
||||
selectedNode = e.id
|
||||
}
|
||||
}}
|
||||
onSelect={onGraphSelect}
|
||||
{onSelectedIteration}
|
||||
earlyStop={job.raw_flow?.skip_expr !== undefined}
|
||||
cache={job.raw_flow?.cache_ttl !== undefined}
|
||||
|
||||
@@ -96,6 +96,23 @@
|
||||
<DisplayResult {workspaceId} noControls result={description} language={job?.language} />
|
||||
<div class="mt-2"></div>
|
||||
{/if}
|
||||
<!-- The form first, then its buttons below it, as any form is submitted. -->
|
||||
{#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema}
|
||||
<div class="flex items-start gap-1 mb-2">
|
||||
<div
|
||||
class={twMerge(
|
||||
'w-full border rounded-lg p-2',
|
||||
light ? 'min-w-96 max-h-svh overflow-y-auto' : ''
|
||||
)}
|
||||
>
|
||||
<SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} />
|
||||
</div>
|
||||
<Tooltip>
|
||||
The payload is optional, it is passed to the following step through the `resume`
|
||||
variable
|
||||
</Tooltip>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- A new approval step gets usable buttons again. -->
|
||||
{#key job?.flow_status?.modules?.[approvalStep]?.job}
|
||||
<ApprovalActions
|
||||
@@ -118,20 +135,6 @@
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema}
|
||||
<div
|
||||
class={twMerge(
|
||||
'w-full border rounded-lg p-2',
|
||||
light ? 'min-w-96 max-h-svh overflow-y-auto' : ''
|
||||
)}
|
||||
>
|
||||
<SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} />
|
||||
</div>
|
||||
<Tooltip>
|
||||
The payload is optional, it is passed to the following step through the `resume`
|
||||
variable
|
||||
</Tooltip>
|
||||
{/if}
|
||||
</ApprovalActions>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
@@ -205,7 +205,10 @@
|
||||
>
|
||||
<span class="text-2xs font-normal text-secondary">
|
||||
{#if status === 'pending' && approvalInfo.approvers.length > 0}
|
||||
Already approved by {approvalInfo.approvers.map((a) => a.approver).join(', ')}
|
||||
{approvalInfo.required_events
|
||||
? `${approvalInfo.approvers.length} of ${approvalInfo.required_events} approvals:`
|
||||
: 'Already approved by'}
|
||||
{approvalInfo.approvers.map((a) => a.approver).join(', ')}
|
||||
{/if}
|
||||
</span>
|
||||
{#if isWorkspaceMember}
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -14,6 +14,8 @@
|
||||
// Prefer step ID over step index when both are available
|
||||
showStepId?: boolean
|
||||
errorAction?: Snippet
|
||||
/** A run nested under this one waits on an approval, which its own steps don't show. */
|
||||
waitingNested?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -23,7 +25,8 @@
|
||||
slim = false,
|
||||
textPosition = 'top',
|
||||
showStepId = false,
|
||||
errorAction
|
||||
errorAction,
|
||||
waitingNested = false
|
||||
}: Props = $props()
|
||||
|
||||
let error: number | undefined = $state(undefined)
|
||||
@@ -189,7 +192,7 @@
|
||||
{textPosition}
|
||||
stepId={currentStepId}
|
||||
{showStepId}
|
||||
{isWaitingForEvents}
|
||||
isWaitingForEvents={isWaitingForEvents || waitingNested}
|
||||
{isCanceled}
|
||||
{isScheduled}
|
||||
{isSkipped}
|
||||
|
||||
@@ -178,6 +178,22 @@
|
||||
</span>
|
||||
</Label>
|
||||
|
||||
<Toggle
|
||||
size="xs"
|
||||
textClass="text-xs font-normal text-primary"
|
||||
disabled={!flowModule.suspend}
|
||||
checked={Boolean(flowModule.suspend?.show_on_home)}
|
||||
options={{
|
||||
right: "List on approvers' home",
|
||||
rightTooltip:
|
||||
'A run waiting on this step shows on the home page of everyone who can approve it. Leave off when the request is sent through Slack, Discord or email.'
|
||||
}}
|
||||
on:change={(e) => {
|
||||
if (flowModule.suspend) {
|
||||
flowModule.suspend.show_on_home = e.detail
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Toggle
|
||||
size="xs"
|
||||
textClass="text-xs font-normal text-primary"
|
||||
|
||||
@@ -3,9 +3,13 @@
|
||||
|
||||
interface Props {
|
||||
id: string
|
||||
/** Past this many characters, cut from the start: the end of a chained id is the step. */
|
||||
maxLength?: number
|
||||
}
|
||||
|
||||
let { id }: Props = $props()
|
||||
let { id, maxLength }: Props = $props()
|
||||
|
||||
let shown = $derived(maxLength && id.length > maxLength ? '…' + id.slice(1 - maxLength) : id)
|
||||
</script>
|
||||
|
||||
<!-- Styled like the id badge on a graph node, so a step named in text reads as the same thing. -->
|
||||
@@ -16,5 +20,5 @@
|
||||
baseClass="!px-1"
|
||||
title={id}
|
||||
>
|
||||
<span class="text-2xs font-normal">{id}</span>
|
||||
<span class="text-2xs font-normal">{shown}</span>
|
||||
</Badge>
|
||||
|
||||
@@ -30,7 +30,8 @@ export type DurationStatus = {
|
||||
export type FlowStatusViewerContext = {
|
||||
flowState?: FlowState
|
||||
retryStatus: StateStore<Record<string, number | undefined>>
|
||||
suspendStatus: StateStore<Record<string, { nb: number; job: Job }>>
|
||||
/** `prefix`: the subflow step ids leading to the run, as `buildPrefix` chains them. */
|
||||
suspendStatus: StateStore<Record<string, { nb: number; job: Job; prefix?: string }>>
|
||||
hideDownloadInGraph?: boolean
|
||||
hideTimeline?: boolean
|
||||
hideNodeDefinition?: boolean
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { CircleCheck, CircleSlash, CircleX, EyeOff, Loader2, Wrench } from 'lucide-svelte'
|
||||
import {
|
||||
CircleCheck,
|
||||
CircleSlash,
|
||||
CircleX,
|
||||
EyeOff,
|
||||
Hourglass,
|
||||
Loader2,
|
||||
Wrench
|
||||
} from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import { useRoleCapabilities } from '$lib/operatorWriteRights'
|
||||
@@ -55,14 +63,18 @@
|
||||
failure: 'Failed',
|
||||
resolved: 'Failed, resolved',
|
||||
canceled: 'Canceled',
|
||||
running: 'Running'
|
||||
running: 'Running',
|
||||
suspended: 'Awaiting approval'
|
||||
}
|
||||
// Waiting for a person is neither progress nor trouble: violet, as a suspended job is
|
||||
// everywhere else, not running's yellow.
|
||||
const barClass = {
|
||||
success: 'bg-green-500 dark:bg-green-600',
|
||||
failure: 'bg-red-500 dark:bg-red-600',
|
||||
resolved: 'bg-orange-300 dark:bg-orange-700',
|
||||
canceled: 'bg-gray-400 dark:bg-gray-500',
|
||||
running: 'bg-yellow-500'
|
||||
running: 'bg-yellow-500',
|
||||
suspended: 'bg-violet-400 dark:bg-violet-500'
|
||||
}
|
||||
|
||||
function runTooltip(run: RecentRun) {
|
||||
@@ -103,6 +115,10 @@
|
||||
<span class="flex w-3.5 shrink-0 justify-center">
|
||||
{#if item.status === 'running'}
|
||||
<Loader2 size={14} class="animate-spin text-yellow-500" />
|
||||
{:else if item.status === 'suspended'}
|
||||
<span class="text-violet-500" title="Awaiting approval"
|
||||
><Hourglass size={14} /></span
|
||||
>
|
||||
{:else if failing}
|
||||
<CircleX size={14} class="text-red-500" />
|
||||
{:else if item.status === 'resolved'}
|
||||
@@ -219,6 +235,8 @@
|
||||
{#if latest}
|
||||
<a
|
||||
href={runHref(latest.id, $workspaceStore)}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="absolute inset-0 text-right font-medium text-accent opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 hover:underline"
|
||||
aria-label="Open the latest run of {title}"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<script lang="ts">
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { ChevronDown, Hourglass, PanelRightOpen } from 'lucide-svelte'
|
||||
import WaitingApprovalsList from './WaitingApprovalsList.svelte'
|
||||
import type { WaitingApprovalsState } from './waitingApprovals.svelte'
|
||||
|
||||
interface Props {
|
||||
approvals: WaitingApprovalsState
|
||||
/** Absent below the width the side column needs: there is no section to add. */
|
||||
onShowSection?: () => void
|
||||
/** A narrow bar: the hourglass and the count. */
|
||||
compact?: boolean
|
||||
}
|
||||
|
||||
let { approvals, onShowSection, compact = false }: Props = $props()
|
||||
|
||||
let isOpen = $state(false)
|
||||
let label = $derived(
|
||||
`${approvals.total} run${approvals.total === 1 ? '' : 's'} waiting for your approval`
|
||||
)
|
||||
</script>
|
||||
|
||||
<!-- Shaped like the recent-runs status beside it: both are statuses of the workspace's runs, where
|
||||
the buttons before them are its changes. -->
|
||||
<div class="flex items-center h-[22px] pl-2.5 ml-1.5 border-l border-border-light wm-page-in">
|
||||
<Popover
|
||||
openOnHover
|
||||
debounceDelay={140}
|
||||
placement="bottom-end"
|
||||
bind:isOpen
|
||||
triggerAttrs={{ 'aria-label': label }}
|
||||
class="flex items-center gap-1.5 h-7 pl-2 pr-1.5 -mr-1.5 rounded-md text-xs font-normal text-violet-600 dark:text-violet-400 whitespace-nowrap tabular-nums hover:bg-surface-secondary {isOpen
|
||||
? 'bg-surface-secondary'
|
||||
: ''}"
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Hourglass size={14} />
|
||||
{approvals.total}{compact ? '' : ' to approve'}
|
||||
{#if !compact}
|
||||
<ChevronDown size={12} class="text-hint" />
|
||||
{/if}
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<div class="w-[380px] max-w-[calc(100vw-32px)] p-1.5 text-xs">
|
||||
<div class="px-2.5 pt-2 pb-1.5">
|
||||
<b class="font-semibold text-emphasis text-[12.5px]">Awaiting your approval</b>
|
||||
</div>
|
||||
<WaitingApprovalsList {approvals} class="max-h-[352px]" onOpen={() => (isOpen = false)} />
|
||||
{#if onShowSection}
|
||||
<div class="flex justify-end mt-1.5 pt-2 px-1.5 pb-1 border-t border-border-light">
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: PanelRightOpen }}
|
||||
onclick={() => {
|
||||
isOpen = false
|
||||
onShowSection()
|
||||
}}
|
||||
>
|
||||
Show approvals on home
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
</div>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script lang="ts">
|
||||
import { Hourglass } from 'lucide-svelte'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import {
|
||||
approvalAge,
|
||||
approvalDetail,
|
||||
approvalHref,
|
||||
approvalTitle,
|
||||
type WaitingApprovalsState
|
||||
} from './waitingApprovals.svelte'
|
||||
|
||||
interface Props {
|
||||
approvals: WaitingApprovalsState
|
||||
/** Caps the list's height; it scrolls inside it, so a long queue never pushes past it. */
|
||||
class?: string
|
||||
onOpen?: () => void
|
||||
}
|
||||
|
||||
let { approvals, class: classNames = '', onOpen }: Props = $props()
|
||||
|
||||
let hidden = $derived(approvals.total - approvals.approvals.length)
|
||||
</script>
|
||||
|
||||
<div class="overflow-y-auto overscroll-contain scrollbar-subtle {classNames}">
|
||||
{#each approvals.approvals as a (a.job_id)}
|
||||
<a
|
||||
href={approvalHref(a, $workspaceStore)}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
onclick={onOpen}
|
||||
class="flex items-center gap-2.5 min-h-[42px] px-2.5 py-[5px] rounded-md hover:bg-surface-hover focus-visible:bg-surface-hover outline-none"
|
||||
>
|
||||
<span class="flex w-3.5 shrink-0 justify-center text-violet-500">
|
||||
<Hourglass size={14} />
|
||||
</span>
|
||||
<span class="flex flex-col min-w-0 flex-1">
|
||||
<span class="truncate text-[12.5px] font-medium text-primary">{approvalTitle(a)}</span>
|
||||
<span class="truncate text-[10.5px] text-hint">{approvalDetail(a)}</span>
|
||||
</span>
|
||||
<span class="w-[46px] shrink-0 text-right text-[11px] text-hint">
|
||||
{approvalAge(a, approvals.now)}
|
||||
</span>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{#if hidden > 0}
|
||||
<!-- The server lists the most recent only: say what is left out rather than end as if complete. -->
|
||||
<p class="px-2.5 pt-1 text-[11.5px] text-hint">
|
||||
{hidden} older run{hidden === 1 ? '' : 's'} also waiting
|
||||
</p>
|
||||
{/if}
|
||||
@@ -0,0 +1,32 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import { PanelRightClose } from 'lucide-svelte'
|
||||
import WaitingApprovalsList from './WaitingApprovalsList.svelte'
|
||||
import type { WaitingApprovalsState } from './waitingApprovals.svelte'
|
||||
|
||||
interface Props {
|
||||
approvals: WaitingApprovalsState
|
||||
onCollapse: () => void
|
||||
}
|
||||
|
||||
let { approvals, onCollapse }: Props = $props()
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-0 h-full">
|
||||
<div class="flex items-center gap-2 shrink-0 pb-2">
|
||||
<h2 class="flex items-baseline gap-1.5 min-w-0 flex-1 text-[13px] font-medium text-primary">
|
||||
<span class="whitespace-nowrap">Awaiting your approval</span>
|
||||
<span class="text-xs font-normal text-hint tabular-nums">{approvals.total}</span>
|
||||
</h2>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: PanelRightClose }}
|
||||
onclick={onCollapse}
|
||||
aria-label="Hide approvals"
|
||||
title="Hide approvals"
|
||||
/>
|
||||
</div>
|
||||
<WaitingApprovalsList {approvals} class="flex-1 min-h-0 -mx-2.5" />
|
||||
</div>
|
||||
@@ -128,10 +128,9 @@ export function useRecentRuns(
|
||||
|
||||
export type RecentRunsState = ReturnType<typeof useRecentRuns>
|
||||
|
||||
const PANEL_OPEN_SETTING = 'wm-home-runs-open'
|
||||
|
||||
export function usePanelOpen() {
|
||||
let open = $state(getLocalSetting(PANEL_OPEN_SETTING) !== 'false')
|
||||
/** Whether a Home side-column section is shown; on until the user hides it. */
|
||||
export function usePanelOpen(setting: string = 'wm-home-runs-open') {
|
||||
let open = $state(getLocalSetting(setting) !== 'false')
|
||||
return {
|
||||
get val() {
|
||||
return open
|
||||
@@ -139,7 +138,7 @@ export function usePanelOpen() {
|
||||
set val(v: boolean) {
|
||||
open = v
|
||||
try {
|
||||
storeLocalSetting(PANEL_OPEN_SETTING, v ? undefined : 'false')
|
||||
storeLocalSetting(setting, v ? undefined : 'false')
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
@@ -176,7 +175,7 @@ export function windowLabel(hours: number) {
|
||||
return hours > 24 && hours % 24 === 0 ? `last ${hours / 24}d` : `last ${hours}h`
|
||||
}
|
||||
|
||||
/** `now`, `3m`, `2h`, `4d`; `running` while the newest run has not finished. */
|
||||
/** `now`, `3m`, `2h`, `4d` since the newest run started; `running` while it is running. */
|
||||
export function shortAge(run: RecentRun, now: number) {
|
||||
if (run.status === 'running') return 'running'
|
||||
const s = Math.max(0, (now - new Date(run.ran_at).getTime()) / 1000)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { JobService, type ListWaitingApprovalsResponse } from '$lib/gen'
|
||||
import { IsDocumentVisible, useInterval } from 'runed'
|
||||
import { persistedResource } from '$lib/persistedResource.svelte'
|
||||
|
||||
export type WaitingApproval = ListWaitingApprovalsResponse['approvals'][number]
|
||||
|
||||
/** An approval waits on a person, who acts within minutes, not seconds; Home stays open in many
|
||||
* tabs. */
|
||||
const REFRESH_MS = 60000
|
||||
|
||||
/**
|
||||
* The runs waiting for an approval the user can give, read from `listWaitingApprovals`. The
|
||||
* header status and the side section read the same instance, so their counts agree.
|
||||
*/
|
||||
export function useWaitingApprovals(workspace: () => string | undefined) {
|
||||
const res = persistedResource(
|
||||
() => ({ workspace: workspace() }),
|
||||
async ({ workspace }) =>
|
||||
workspace ? await JobService.listWaitingApprovals({ workspace }) : undefined,
|
||||
{
|
||||
name: 'waiting_approvals',
|
||||
version: 1,
|
||||
scope: ({ workspace }) => (workspace ? { workspace, args: {} } : undefined)
|
||||
}
|
||||
)
|
||||
let now = $state(Date.now())
|
||||
const visible = new IsDocumentVisible()
|
||||
useInterval(REFRESH_MS, {
|
||||
callback: () => {
|
||||
if (!visible.current) return
|
||||
now = Date.now()
|
||||
if (!res.loading) res.refetch()
|
||||
}
|
||||
})
|
||||
return {
|
||||
get approvals(): WaitingApproval[] {
|
||||
return res.current?.approvals ?? []
|
||||
},
|
||||
/** All the runs waiting, of which `approvals` holds the most recent. */
|
||||
get total(): number {
|
||||
return res.current?.total ?? 0
|
||||
},
|
||||
get now() {
|
||||
return now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type WaitingApprovalsState = ReturnType<typeof useWaitingApprovals>
|
||||
|
||||
/** The approval page, which shows an approver that one run even without read access to it. */
|
||||
export function approvalHref(a: WaitingApproval, workspace: string | undefined) {
|
||||
return `/approve/${workspace ?? ''}/${a.job_id}`
|
||||
}
|
||||
|
||||
export function approvalTitle(a: WaitingApproval) {
|
||||
return a.flow_summary || a.flow_path?.split('/').pop() || 'Flow'
|
||||
}
|
||||
|
||||
export function approvalDetail(a: WaitingApproval) {
|
||||
return [
|
||||
a.step_summary,
|
||||
`started by ${a.started_by}`,
|
||||
a.required_approvals > 1 ? `${a.approvals} of ${a.required_approvals} approvals` : undefined
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
export function approvalAge(a: WaitingApproval, now: number) {
|
||||
const s = Math.max(0, (now - new Date(a.created_at).getTime()) / 1000)
|
||||
if (s < 60) return 'now'
|
||||
if (s < 3600) return `${Math.floor(s / 60)}m`
|
||||
if (s < 86400) return `${Math.floor(s / 3600)}h`
|
||||
return `${Math.floor(s / 86400)}d`
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Tween } from 'svelte/motion'
|
||||
import { linear } from 'svelte/easing'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { Loader2 } from 'lucide-svelte'
|
||||
import { Hourglass, Loader2 } from 'lucide-svelte'
|
||||
import { fade } from 'svelte/transition'
|
||||
import type { Snippet } from 'svelte'
|
||||
|
||||
@@ -92,6 +92,9 @@
|
||||
const status: 'error' | 'done' | 'running' = $derived(
|
||||
error != undefined ? 'error' : finished ? 'done' : 'running'
|
||||
)
|
||||
// Violet like a suspended run everywhere else (badges, Recently run).
|
||||
let waiting = $derived(status == 'running' && isWaitingForEvents && !isCanceled)
|
||||
let fill = $derived(waiting ? 'bg-violet-400' : 'bg-blue-400')
|
||||
</script>
|
||||
|
||||
<div class={twMerge('flex flex-col gap-1', className)}>
|
||||
@@ -127,14 +130,14 @@
|
||||
{/if}
|
||||
{#if partIndex < index - 1}
|
||||
<div
|
||||
class="absolute left-0 bottom-0 h-full w-full bg-blue-400 transition-colors duration-300 ease-in-out"
|
||||
class="absolute left-0 bottom-0 h-full w-full {fill} transition-colors duration-300 ease-in-out"
|
||||
></div>
|
||||
{:else if partIndex == index - 1 || (partIndex == index && subIndex !== undefined) || error == partIndex}
|
||||
<div
|
||||
class="absolute left-0 bottom-0 h-full transition-all duration-300 ease-in-out {error ==
|
||||
partIndex
|
||||
? 'bg-red-400'
|
||||
: 'bg-blue-400'}"
|
||||
: fill}"
|
||||
style="width: {getPercent(partIndex, percent.current)}%"
|
||||
></div>
|
||||
{/if}
|
||||
@@ -153,10 +156,14 @@
|
||||
class="flex justify-between items-end font-medium transition-colors duration-300 ease-in-out {error !=
|
||||
undefined || isCanceled
|
||||
? 'text-red-600 dark:text-red-400'
|
||||
: 'text-blue-700 dark:text-blue-200'}"
|
||||
: waiting
|
||||
? 'text-violet-600 dark:text-violet-400'
|
||||
: 'text-blue-700 dark:text-blue-200'}"
|
||||
>
|
||||
<div class={twMerge(slim ? 'text-xs' : 'text-sm', 'flex items-center gap-1')}>
|
||||
{#if status == 'running' && !isCanceled && !isScheduled && !isSkipped}
|
||||
{#if waiting}
|
||||
<Hourglass size={14} />
|
||||
{:else if status == 'running' && !isCanceled && !isScheduled && !isSkipped}
|
||||
<Loader2 class="animate-spin" size={14} />
|
||||
{/if}
|
||||
{#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { ChevronDown, ExternalLink, Hourglass } from 'lucide-svelte'
|
||||
import { Badge, Button } from '$lib/components/common'
|
||||
import { JobService, type FlowModule, type Job } from '$lib/gen'
|
||||
import FlowStatusWaitingForEvents from '../FlowStatusWaitingForEvents.svelte'
|
||||
import StepIdBadge from '../flows/content/StepIdBadge.svelte'
|
||||
import { displayDate } from '$lib/utils'
|
||||
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
|
||||
|
||||
interface Props {
|
||||
/** The run the step belongs to: the page's run, or a subflow, branch or loop run under it. */
|
||||
job: Job
|
||||
module: FlowModule
|
||||
isOwner: boolean
|
||||
/** The step's id, chained after the subflow steps leading to it (`outer:r:s`). */
|
||||
chainedId: string
|
||||
/** The page run's step the graph selects: the step itself, or the one holding its run. */
|
||||
graphStep: string
|
||||
onSelectStep: () => void
|
||||
}
|
||||
|
||||
let { job, module, isOwner, chainedId, graphStep, onSelectStep }: Props = $props()
|
||||
|
||||
// Primitives: each poll brings a new `job` object, which would refetch on every poll.
|
||||
let workspace = $derived(job.workspace_id)
|
||||
let jobId = $derived(job.id)
|
||||
let stepId = $derived(module.id)
|
||||
const detail = resource(
|
||||
() => ({ workspace, jobId, stepId }),
|
||||
async ({ workspace, jobId, stepId }) =>
|
||||
workspace ? JobService.getApprovalStepDetail({ workspace, jobId, stepId }) : undefined
|
||||
)
|
||||
|
||||
// Open for whoever can act on it; a long description or form takes room only for them.
|
||||
let toggled = $state<boolean | undefined>(undefined)
|
||||
let expanded = $derived(toggled ?? detail.current?.can_approve ?? isOwner)
|
||||
|
||||
// Worded as the approval page words it. Admins and flow owners can approve any step, so they
|
||||
// are not listed.
|
||||
function canApproveLabel(): string {
|
||||
const ac = detail.current?.approval_conditions
|
||||
const who = !ac?.user_auth_required
|
||||
? 'anyone with the approval link'
|
||||
: ac.user_groups_required.length > 0
|
||||
? `members of ${ac.user_groups_required.join(', ')}`
|
||||
: 'any signed-in member'
|
||||
return ac?.self_approval_disabled ? `${who} · self-approval disabled` : who
|
||||
}
|
||||
|
||||
const namesLabel = (names: string[]) =>
|
||||
names.slice(0, 2).join(', ') + (names.length > 2 ? ` +${names.length - 2}` : '')
|
||||
|
||||
let toggleLabel = $derived(expanded ? 'Hide the approval form' : 'Show the approval form')
|
||||
</script>
|
||||
|
||||
<div class="flex items-start gap-3 px-4 py-2 border-t text-xs">
|
||||
<Hourglass size={14} class="shrink-0 mt-[3px] text-violet-500" />
|
||||
<div class="flex flex-1 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5">
|
||||
<span class="flex flex-wrap items-center gap-1 min-w-0 w-64 max-w-full -ml-2">
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
btnClasses="justify-start min-w-0 gap-1"
|
||||
title="Show {graphStep} in the graph"
|
||||
onclick={onSelectStep}
|
||||
>
|
||||
<span class="truncate">{module.summary || module.id}</span>
|
||||
{#if module.summary || chainedId !== module.id}
|
||||
<StepIdBadge id={chainedId} maxLength={24} />
|
||||
{/if}
|
||||
</Button>
|
||||
</span>
|
||||
<span
|
||||
class="flex flex-1 basis-48 flex-wrap items-center gap-x-3 gap-y-0.5 min-w-0 text-secondary"
|
||||
>
|
||||
{#if detail.current}
|
||||
<span><span class="text-hint">Can approve:</span> {canApproveLabel()}</span>
|
||||
{@const approvals = detail.current.approvals}
|
||||
{#if approvals.length > 0}
|
||||
<!-- Two names keep the row on one line; all of them, with times, are on hover. -->
|
||||
<Tooltip small>
|
||||
{#snippet text()}
|
||||
{#each approvals as a}
|
||||
<div>
|
||||
{a.approver}{#if a.created_at}<span class="opacity-70"
|
||||
>{` · ${displayDate(a.created_at)}`}</span
|
||||
>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{/snippet}
|
||||
<span>
|
||||
{approvals.length} of {detail.current.required_events} approvals:
|
||||
<span class="text-primary">{namesLabel(approvals.map((a) => a.approver))}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
{/if}
|
||||
{/if}
|
||||
<!-- The page the Home list and links sent through other channels open, for this run. -->
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
href="/approve/{workspace ?? ''}/{jobId}"
|
||||
target="_blank"
|
||||
endIcon={{ icon: ExternalLink }}
|
||||
>
|
||||
Approval page
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
<span class="flex shrink-0 items-center gap-1">
|
||||
<Badge color="violet" small>Waiting</Badge>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: ChevronDown, classes: expanded ? 'rotate-180' : '' }}
|
||||
title={toggleLabel}
|
||||
aria-label={toggleLabel}
|
||||
aria-expanded={expanded}
|
||||
onclick={() => (toggled = !expanded)}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
{#if expanded}
|
||||
<!-- The step's own approval panel, unchanged: its description, form and buttons. -->
|
||||
<div class="px-4 pt-1 pb-3">
|
||||
<!-- A partial approval changes nothing the job's updates carry: refetch the count. -->
|
||||
<FlowStatusWaitingForEvents
|
||||
workspaceId={job.workspace_id}
|
||||
{job}
|
||||
{isOwner}
|
||||
onAction={() => detail.refetch()}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,249 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { CircleCheck, CircleX, TimerOff } from 'lucide-svelte'
|
||||
import { Badge, Button } from '$lib/components/common'
|
||||
import { JobService, type FlowModule, type Job } from '$lib/gen'
|
||||
import { displayDate, type StateStore } from '$lib/utils'
|
||||
import FlowExecutionStatus from './FlowExecutionStatus.svelte'
|
||||
import FlowApprovalWaitingRow from './FlowApprovalWaitingRow.svelte'
|
||||
import { pendingAgentApproval } from '../agentRequest'
|
||||
import StepIdBadge from '../flows/content/StepIdBadge.svelte'
|
||||
|
||||
interface Props {
|
||||
job: Job
|
||||
isOwner: boolean
|
||||
suspendStatus: StateStore<Record<string, { job: Job; nb: number; prefix?: string }>>
|
||||
/** Selects the step in the run's graph. */
|
||||
onSelectStep: (stepId: string) => void
|
||||
}
|
||||
|
||||
let { job, isOwner, suspendStatus, onSelectStep }: Props = $props()
|
||||
|
||||
type Approver = { approver: string; approved_at?: string; approved?: boolean }
|
||||
/** `chainedId`: the step's id after the subflow steps leading to it (`outer:r:s`).
|
||||
* `graphStep`: its first id. Step ids are unique across a flow, loop and branch steps
|
||||
* included, so that one is a node of this run's graph. */
|
||||
type Located = { chainedId: string; graphStep: string }
|
||||
type DoneRow = Located & {
|
||||
key: string
|
||||
stepId: string
|
||||
summary?: string
|
||||
approvers: Approver[]
|
||||
/** `rejected` and `timedOut`: the flow continued past it (`continue_on_disapprove_timeout`). */
|
||||
outcome: Outcome
|
||||
}
|
||||
type Wait = Located & { job: Job; module: FlowModule }
|
||||
|
||||
type Outcome = 'approved' | 'rejected' | 'timedOut'
|
||||
// Entries written before `approved` was recorded are approvals.
|
||||
const outcome = (approvers: Approver[], required: number | undefined): Outcome =>
|
||||
approvers.some((a) => a.approved === false)
|
||||
? 'rejected'
|
||||
: approvers.length < (required ?? 1)
|
||||
? 'timedOut'
|
||||
: 'approved'
|
||||
|
||||
let ownDone = $derived.by((): DoneRow[] => {
|
||||
const statuses = job.flow_status?.modules ?? []
|
||||
const flowStep = job.flow_status?.step ?? 0
|
||||
return (job.raw_flow?.modules ?? []).flatMap((module, i): DoneRow[] => {
|
||||
const status = statuses[i]
|
||||
const approvers = status?.approvers ?? []
|
||||
if (!module.suspend || status?.type !== 'Success' || status.skipped) return []
|
||||
// No response and the flow moved past the step after it: it timed out and continued.
|
||||
// While it waits, `step` is that next step's index.
|
||||
if (approvers.length === 0 && flowStep <= i + 1) return []
|
||||
return [
|
||||
{
|
||||
key: module.id,
|
||||
stepId: module.id,
|
||||
chainedId: module.id,
|
||||
graphStep: module.id,
|
||||
summary: module.summary || undefined,
|
||||
approvers,
|
||||
outcome: outcome(approvers, module.suspend.required_events)
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
// Every approval the run waits on: its own step, or one in a run nested under it (a subflow,
|
||||
// branch or loop run), which the run's graph shows inside the step holding it.
|
||||
let waits = $derived.by((): Wait[] => {
|
||||
const step = job.flow_status?.step ?? 0
|
||||
const own =
|
||||
job.flow_status?.modules?.[step]?.type === 'WaitingForEvents'
|
||||
? job.raw_flow?.modules?.[step - 1]
|
||||
: undefined
|
||||
if (own?.suspend) return [{ job, module: own, chainedId: own.id, graphStep: own.id }]
|
||||
return Object.values(suspendStatus.val ?? {}).flatMap(({ job: waiting, prefix }): Wait[] => {
|
||||
const module = waiting.raw_flow?.modules?.[(waiting.flow_status?.step ?? 0) - 1]
|
||||
if (waiting.id === job.id || !module?.suspend) return []
|
||||
// The prefix chains the subflow steps leading to the run, not loops or branches.
|
||||
const chain = [...(prefix?.split(':').filter(Boolean) ?? []), module.id]
|
||||
return [{ job: waiting, module, chainedId: chain.join(':'), graphStep: chain[0] }]
|
||||
})
|
||||
})
|
||||
|
||||
// Mirrors `may_hold_approval` on the server: a subflow, or a loop or branch holding one.
|
||||
function mayHoldApproval(m: FlowModule): boolean {
|
||||
const holds = (modules: FlowModule[] | undefined) =>
|
||||
(modules ?? []).some((x) => !!x.suspend || mayHoldApproval(x))
|
||||
const v = m.value
|
||||
switch (v.type) {
|
||||
case 'flow':
|
||||
return true
|
||||
case 'forloopflow':
|
||||
case 'whileloopflow':
|
||||
return holds(v.modules)
|
||||
case 'branchone':
|
||||
return holds(v.default) || v.branches.some((b) => holds(b.modules))
|
||||
case 'branchall':
|
||||
return v.branches.some((b) => holds(b.modules))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Who approved a nested run's steps is kept on that run: read when the run has a step that
|
||||
// can hold one, then again only when its waits change or it finishes, not at every step.
|
||||
// Primitives: each poll brings a new `job` object, which would refetch on every poll.
|
||||
let nests = $derived((job.raw_flow?.modules ?? []).some(mayHoldApproval))
|
||||
let workspace = $derived(job.workspace_id)
|
||||
let jobId = $derived(job.id)
|
||||
let moved = $derived(`${job.type}:${waits.map((w) => w.job.id + w.module.id)}`)
|
||||
const nested = resource(
|
||||
() => ({ nests, workspace, jobId, moved }),
|
||||
async ({ nests, workspace, jobId }) =>
|
||||
nests && workspace ? JobService.listNestedApprovals({ workspace, jobId }) : undefined
|
||||
)
|
||||
|
||||
// In the order they were decided: own and nested steps interleave in a flow's run.
|
||||
const decidedAt = (r: DoneRow) =>
|
||||
r.approvers.reduce((t, a) => (a.approved_at && a.approved_at > t ? a.approved_at : t), '')
|
||||
let done = $derived(
|
||||
[
|
||||
...ownDone,
|
||||
...(nested.current?.approvals ?? []).map(
|
||||
(a): DoneRow => ({
|
||||
key: `${a.job_id}:${a.step_id}`,
|
||||
stepId: a.step_id,
|
||||
chainedId: [...a.subflows, a.step_id].join(':'),
|
||||
graphStep: a.subflows[0] ?? a.step_id,
|
||||
summary: a.step_summary,
|
||||
approvers: a.approvers,
|
||||
outcome: outcome(a.approvers, a.required_events)
|
||||
})
|
||||
)
|
||||
].sort((a, b) => decidedAt(a).localeCompare(decidedAt(b)))
|
||||
)
|
||||
|
||||
// Waits the rows don't hold: an agent asking for a tool approval, or a run whose steps are not
|
||||
// loaded.
|
||||
let otherWaiting = $derived(
|
||||
!!pendingAgentApproval(job) ||
|
||||
(waits.length === 0 && Object.keys(suspendStatus.val ?? {}).length > 0)
|
||||
)
|
||||
|
||||
// Counts, not "N of M": a loop's step counts once per iteration, and the total is unknown
|
||||
// until the loop ends.
|
||||
let counts = $derived(
|
||||
[
|
||||
[done.filter((r) => r.outcome == 'approved').length, 'approved'],
|
||||
[done.filter((r) => r.outcome == 'rejected').length, 'rejected'],
|
||||
[done.filter((r) => r.outcome == 'timedOut').length, 'timed out'],
|
||||
[waits.length, 'waiting']
|
||||
]
|
||||
.filter(([n]) => n)
|
||||
.map(([n, label]) => `${n} ${label}`)
|
||||
.join(' · ')
|
||||
)
|
||||
let stepCount = $derived(done.length + waits.length)
|
||||
</script>
|
||||
|
||||
{#if stepCount > 0 || otherWaiting}
|
||||
<div class="rounded-md border bg-surface-tertiary">
|
||||
<div class="flex items-center justify-between px-4 py-2 text-xs font-semibold text-emphasis">
|
||||
<span>Approvals</span>
|
||||
{#if stepCount > 0}
|
||||
<span class="font-normal text-secondary">{counts}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#each done as row (row.key)}
|
||||
<div class="flex items-start gap-3 px-4 py-2 border-t text-xs">
|
||||
{#if row.outcome == 'rejected'}
|
||||
<CircleX size={14} class="shrink-0 mt-[3px] text-red-500" />
|
||||
{:else if row.outcome == 'timedOut'}
|
||||
<TimerOff size={14} class="shrink-0 mt-[3px] text-yellow-500" />
|
||||
{:else}
|
||||
<CircleCheck size={14} class="shrink-0 mt-[3px] text-green-500" />
|
||||
{/if}
|
||||
<div class="flex flex-1 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5">
|
||||
<span class="flex items-center gap-1 min-w-0 w-64 max-w-full -ml-2">
|
||||
<!-- Into the graph below, where the step's own status, logs and result are. -->
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
btnClasses="justify-start min-w-0 gap-1"
|
||||
title="Show {row.graphStep} in the graph"
|
||||
onclick={() => onSelectStep(row.graphStep)}
|
||||
>
|
||||
<span class="truncate">{row.summary || row.stepId}</span>
|
||||
{#if row.summary || row.chainedId !== row.stepId}
|
||||
<StepIdBadge id={row.chainedId} maxLength={24} />
|
||||
{/if}
|
||||
</Button>
|
||||
</span>
|
||||
<span
|
||||
class="flex flex-1 basis-48 flex-wrap items-center gap-x-3 gap-y-0.5 min-w-0 text-secondary"
|
||||
>
|
||||
<!-- Unkeyed: the status stores resume ids truncated to 16 bits, so two can collide. -->
|
||||
{#each row.approvers as approver}
|
||||
<span>
|
||||
<span class="text-primary">{approver.approver}</span>
|
||||
{#if approver.approved_at}
|
||||
<span class="text-hint">· {displayDate(approver.approved_at)}</span>
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
</span>
|
||||
</div>
|
||||
<span class="shrink-0">
|
||||
{#if row.outcome == 'rejected'}
|
||||
<Badge color="red" small>Rejected, continued</Badge>
|
||||
{:else if row.outcome == 'timedOut'}
|
||||
<Badge color="yellow" small>Timed out, continued</Badge>
|
||||
{:else}
|
||||
<Badge color="green" small>Approved</Badge>
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
{#if nested.current?.more}
|
||||
<p class="px-4 py-2 border-t text-xs text-hint">
|
||||
More approvals in nested runs than shown here: they are on those runs' own pages.
|
||||
</p>
|
||||
{/if}
|
||||
{#each waits as wait (`${wait.job.id}:${wait.module.id}`)}
|
||||
<FlowApprovalWaitingRow
|
||||
job={wait.job}
|
||||
module={wait.module}
|
||||
chainedId={wait.chainedId}
|
||||
graphStep={wait.graphStep}
|
||||
{isOwner}
|
||||
onSelectStep={() => onSelectStep(wait.graphStep)}
|
||||
/>
|
||||
{/each}
|
||||
{#if otherWaiting}
|
||||
<div class="px-4 pt-1 pb-3 border-t">
|
||||
<FlowExecutionStatus
|
||||
{job}
|
||||
{isOwner}
|
||||
{suspendStatus}
|
||||
innerModules={job.flow_status?.modules}
|
||||
embedded
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -11,9 +11,11 @@
|
||||
isOwner: boolean
|
||||
innerModules: FlowStatusModule[] | undefined
|
||||
suspendStatus: StateStore<Record<string, { job: Job; nb: number }>>
|
||||
/** Inside a card of its own (the run's approvals): no frame of its own. */
|
||||
embedded?: boolean
|
||||
}
|
||||
|
||||
let { job, isOwner, suspendStatus }: Props = $props()
|
||||
let { job, isOwner, suspendStatus, embedded = false }: Props = $props()
|
||||
|
||||
const isWaitingForEvents = $derived(
|
||||
job?.flow_status?.modules?.[job?.flow_status?.step]?.type === 'WaitingForEvents'
|
||||
@@ -27,7 +29,9 @@
|
||||
|
||||
{#if job && anyStatusActive}
|
||||
<div
|
||||
class="rounded-md border shadow-md p-4 bg-surface-tertiary flex flex-col justify-center"
|
||||
class="{embedded
|
||||
? ''
|
||||
: 'rounded-md border shadow-md p-4 bg-surface-tertiary'} flex flex-col justify-center"
|
||||
transition:slide={{ duration: 150 }}
|
||||
>
|
||||
{#if isWaitingForEvents}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
import FlowAssetsHandler, { initFlowGraphAssetsCtx } from '../flows/FlowAssetsHandler.svelte'
|
||||
import JobAssetsViewer from '../assets/JobAssetsViewer.svelte'
|
||||
import JobDetailHeader from './JobDetailHeader.svelte'
|
||||
import FlowExecutionStatus from './FlowExecutionStatus.svelte'
|
||||
import FlowApprovals from './FlowApprovals.svelte'
|
||||
|
||||
interface Props {
|
||||
id: string
|
||||
@@ -121,6 +121,8 @@
|
||||
// Flow execution status state
|
||||
let suspendStatus: StateStore<Record<string, { job: Job; nb: number }>> = $state({ val: {} })
|
||||
let isOwner: boolean = $state(false)
|
||||
let flowStatusViewer: FlowStatusViewer | undefined = $state(undefined)
|
||||
let flowStatusEl: HTMLElement | undefined = $state(undefined)
|
||||
</script>
|
||||
|
||||
<JobLoader
|
||||
@@ -172,11 +174,14 @@
|
||||
{/if}
|
||||
<div class="w-full mt-2">
|
||||
{#if isFlow}
|
||||
<FlowExecutionStatus
|
||||
<FlowApprovals
|
||||
{job}
|
||||
{isOwner}
|
||||
innerModules={job?.flow_status?.modules}
|
||||
{suspendStatus}
|
||||
onSelectStep={(stepId) => {
|
||||
flowStatusViewer?.selectStep(stepId)
|
||||
flowStatusEl?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -192,9 +197,10 @@
|
||||
</div>
|
||||
|
||||
<!-- Job execution content -->
|
||||
<div class="w-full mt-6">
|
||||
<div class="w-full mt-6" bind:this={flowStatusEl}>
|
||||
{#if isFlow}
|
||||
<FlowStatusViewer
|
||||
bind:this={flowStatusViewer}
|
||||
jobId={job.id}
|
||||
workspaceId={job.workspace_id}
|
||||
initialJob={job}
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
|
||||
import JobDetailHeader from '$lib/components/runs/JobDetailHeader.svelte'
|
||||
import ScriptRetryChain from '$lib/components/runs/ScriptRetryChain.svelte'
|
||||
import FlowExecutionStatus from '$lib/components/runs/FlowExecutionStatus.svelte'
|
||||
import FlowApprovals from '$lib/components/runs/FlowApprovals.svelte'
|
||||
import JobArgs from '$lib/components/JobArgs.svelte'
|
||||
import FlowProgressBar from '$lib/components/flows/FlowProgressBar.svelte'
|
||||
import JobProgressBar from '$lib/components/jobs/JobProgressBar.svelte'
|
||||
@@ -202,6 +202,8 @@
|
||||
|
||||
let viewTab: 'logs' | 'code' | 'stats' | 'assets' | 'traces' = $state('logs')
|
||||
let selectedJobStep: string | undefined = $state(undefined)
|
||||
let graphEl: HTMLElement | undefined = $state(undefined)
|
||||
let flowStatusViewer: FlowStatusViewer | undefined = $state(undefined)
|
||||
|
||||
// Mirror of the graph's per-module display state (selected iteration of each
|
||||
// ForLoop, etc.). Drives both the iteration pre-fill and the iteration-count
|
||||
@@ -1453,6 +1455,7 @@
|
||||
textPosition="bottom"
|
||||
slim
|
||||
showStepId
|
||||
waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0}
|
||||
>
|
||||
{#snippet errorAction()}
|
||||
<!-- A saved agent's run is its one step: naming it adds nothing. -->
|
||||
@@ -1466,12 +1469,15 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
</FlowProgressBar>
|
||||
{#if suspendStatus}
|
||||
<FlowExecutionStatus
|
||||
{#if suspendStatus && job}
|
||||
<FlowApprovals
|
||||
{job}
|
||||
{isOwner}
|
||||
{suspendStatus}
|
||||
innerModules={job?.flow_status?.modules}
|
||||
onSelectStep={(stepId) => {
|
||||
flowStatusViewer?.selectStep(stepId)
|
||||
graphEl?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1650,9 +1656,10 @@
|
||||
{:else if !job?.['deleted']}
|
||||
<div class="mt-10"></div>
|
||||
|
||||
<div class="w-full mt-10">
|
||||
<div class="w-full mt-10" bind:this={graphEl}>
|
||||
{#if job?.id}
|
||||
<FlowStatusViewer
|
||||
bind:this={flowStatusViewer}
|
||||
jobId={job?.id ?? ''}
|
||||
onJobsLoaded={({ job: newJob }) => {
|
||||
job = newJob
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
import ItemsList from '$lib/components/home/ItemsList.svelte'
|
||||
import RecentRunsPanel from '$lib/components/home/RecentRunsPanel.svelte'
|
||||
import RecentRunsHeaderStatus from '$lib/components/home/RecentRunsHeaderStatus.svelte'
|
||||
import WaitingApprovalsHeaderStatus from '$lib/components/home/WaitingApprovalsHeaderStatus.svelte'
|
||||
import WaitingApprovalsPanel from '$lib/components/home/WaitingApprovalsPanel.svelte'
|
||||
import { useWaitingApprovals } from '$lib/components/home/waitingApprovals.svelte'
|
||||
import {
|
||||
allRunsHref,
|
||||
itemHref,
|
||||
@@ -126,6 +129,17 @@
|
||||
// The side panel needs the room of a desktop window; narrower, only the header status shows.
|
||||
const wide = new MediaQuery('min-width: 1024px')
|
||||
let showRunsPanel = $derived(showRuns && wide.current && runsPanelOpen.val)
|
||||
// Read whether or not the workspace shows the user any item: someone who can only approve,
|
||||
// through a group, may see none of its scripts or flows.
|
||||
const waitingApprovals = useWaitingApprovals(() => $workspaceStore ?? undefined)
|
||||
const approvalsSectionOpen = usePanelOpen('wm-home-approvals-open')
|
||||
let showApprovalsPanel = $derived(
|
||||
tab == 'workspace' && wide.current && approvalsSectionOpen.val && waitingApprovals.total > 0
|
||||
)
|
||||
let showApprovalsStatus = $derived(waitingApprovals.total > 0 && !showApprovalsPanel)
|
||||
let showSideColumn = $derived(showRunsPanel || showApprovalsPanel)
|
||||
const SIDE_CARD =
|
||||
'flex flex-col bg-surface-tertiary border border-border-light rounded-lg px-5 pt-2 pb-3 group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:border-transparent'
|
||||
const runsMenuId = homeHeaderMenu.register(200, () => {
|
||||
const data = recentRuns.current
|
||||
if (!showRuns || showRunsPanel || !homeActionsGathered()) return []
|
||||
@@ -348,6 +362,15 @@
|
||||
{/snippet}
|
||||
|
||||
{#snippet runsStatus()}
|
||||
<!-- Stays in the bar when the other actions gather into ⋮, down to the hourglass and the count:
|
||||
it is the one thing in the bar that waits on the user. -->
|
||||
{#if showApprovalsStatus}
|
||||
<WaitingApprovalsHeaderStatus
|
||||
compact={homeActionsCompact()}
|
||||
approvals={waitingApprovals}
|
||||
onShowSection={wide.current ? () => (approvalsSectionOpen.val = true) : undefined}
|
||||
/>
|
||||
{/if}
|
||||
{#if showRuns && !showRunsPanel && !homeActionsGathered()}
|
||||
<RecentRunsHeaderStatus
|
||||
compact={homeActionsCompact()}
|
||||
@@ -373,17 +396,17 @@
|
||||
<!-- Where edits to this workspace are made is a fact about the workspace, so it sits in the
|
||||
header with the workspace's own name rather than above the list. -->
|
||||
<PageHeaderContent actions={editRuleBadge} />
|
||||
<!-- After the home menu (order 100): the run status closes the bar. -->
|
||||
<!-- After the home menu (order 100): the run statuses close the bar. -->
|
||||
<PageHeaderContent
|
||||
actions={runsStatus}
|
||||
actionsOrder={200}
|
||||
actionFolds={HOME_ACTION_FOLDS}
|
||||
actionsVersion={homeActionsVersion()}
|
||||
actionsVersion={`${homeActionsVersion()}:${showApprovalsStatus}`}
|
||||
/>
|
||||
|
||||
<ForkWorkspaceBanner />
|
||||
<WorkspaceDraftsBanner />
|
||||
<div class="flex w-full justify-center {showRunsPanel ? 'max-w-[1520px]' : ''}">
|
||||
<div class="flex w-full justify-center {showSideColumn ? 'max-w-[1520px]' : ''}">
|
||||
<div class="flex flex-col items-center flex-1 min-w-0">
|
||||
<!-- While the composer is open this column stays at the top and the lists scroll under it. Its
|
||||
parent holds the lists too, because a sticky element holds only inside its parent; its
|
||||
@@ -485,23 +508,41 @@
|
||||
<ItemsList bind:this={itemsList} bind:subtab showEditButtons={showCreateButtons} />
|
||||
{/if}
|
||||
</div>
|
||||
{#if showRunsPanel}
|
||||
<!-- Beside the composer and the items card, as one of the page's cards, and like them it
|
||||
loses its frame while the composer is open. The page scrolls, so it holds to the top
|
||||
and its list scrolls inside it. `data-works-with-composer`: a press in it leaves the
|
||||
composer open, as one in the items card does. -->
|
||||
<aside
|
||||
{#if showSideColumn}
|
||||
<!-- Beside the composer and the items card, as the page's cards, and like them its cards
|
||||
lose their frame while the composer is open. The page scrolls, so the column holds to
|
||||
the top and each list scrolls inside its card. `data-works-with-composer`: a press in
|
||||
it leaves the composer open, as one in the items card does. -->
|
||||
<div
|
||||
data-works-with-composer
|
||||
class="sticky top-3 self-start shrink-0 w-[380px] max-[1180px]:w-[300px] -ml-2 mr-4 mt-3 mb-6 max-h-[calc(100dvh-48px-1.5rem)] flex flex-col bg-surface-tertiary border border-border-light rounded-lg px-5 pt-2 pb-3 group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:border-transparent"
|
||||
aria-label="Recently run"
|
||||
class="sticky top-3 self-start shrink-0 w-[380px] max-[1180px]:w-[300px] -ml-2 mr-4 mt-3 mb-6 max-h-[calc(100dvh-48px-1.5rem)] flex flex-col gap-3"
|
||||
>
|
||||
<RecentRunsPanel
|
||||
runs={recentRuns}
|
||||
folder={runsFolder}
|
||||
onFocusItem={revealRunItem}
|
||||
onCollapse={() => (runsPanelOpen.val = false)}
|
||||
/>
|
||||
</aside>
|
||||
{#if showApprovalsPanel}
|
||||
<!-- At most half the column with Recently run below it: a long queue scrolls inside.
|
||||
The column has no height of its own, so a percentage would cap nothing. -->
|
||||
<aside
|
||||
class="{SIDE_CARD} min-h-0 {showRunsPanel
|
||||
? 'max-h-[calc((100dvh-48px-1.5rem)/2)]'
|
||||
: ''}"
|
||||
aria-label="Awaiting your approval"
|
||||
>
|
||||
<WaitingApprovalsPanel
|
||||
approvals={waitingApprovals}
|
||||
onCollapse={() => (approvalsSectionOpen.val = false)}
|
||||
/>
|
||||
</aside>
|
||||
{/if}
|
||||
{#if showRunsPanel}
|
||||
<aside class="{SIDE_CARD} min-h-0 flex-1" aria-label="Recently run">
|
||||
<RecentRunsPanel
|
||||
runs={recentRuns}
|
||||
folder={runsFolder}
|
||||
onFocusItem={revealRunItem}
|
||||
onCollapse={() => (runsPanelOpen.val = false)}
|
||||
/>
|
||||
</aside>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,13 +6,12 @@
|
||||
import FlowMetadata from '$lib/components/FlowMetadata.svelte'
|
||||
import JobArgs from '$lib/components/JobArgs.svelte'
|
||||
import { onDestroy, onMount, untrack } from 'svelte'
|
||||
import Tooltip from '$lib/components/Tooltip.svelte'
|
||||
import SchemaForm from '$lib/components/SchemaForm.svelte'
|
||||
import { enterpriseLicense, userStore, workspaceStore } from '$lib/stores'
|
||||
import Login from '$lib/components/Login.svelte'
|
||||
import { AlertTriangle, ExternalLink } from 'lucide-svelte'
|
||||
import { mergeSchema } from '$lib/common'
|
||||
import { emptyString } from '$lib/utils'
|
||||
import { displayDate, emptyString } from '$lib/utils'
|
||||
import { Alert } from '$lib/components/common'
|
||||
import DenyReason from '$lib/components/approvals/DenyReason.svelte'
|
||||
import { getUserExt } from '$lib/user'
|
||||
@@ -276,13 +275,19 @@
|
||||
<h2 class="text-sm font-semibold text-emphasis">Approvers</h2>
|
||||
<div class="mt-2 text-xs font-normal text-primary">
|
||||
{#if approvalInfo.approvers?.length > 0}
|
||||
<!-- Worded as the run page's Approvals card words it. -->
|
||||
{#if approvalInfo.required_events}
|
||||
<p class="text-secondary mb-1">
|
||||
{approvalInfo.approvers.length} of {approvalInfo.required_events} approvals
|
||||
</p>
|
||||
{/if}
|
||||
<ul>
|
||||
{#each approvalInfo.approvers as a}
|
||||
<li>
|
||||
<p>
|
||||
{a.approver}
|
||||
<Tooltip>Unique id of approval: {a.resume_id}</Tooltip>
|
||||
</p>
|
||||
{a.approver}
|
||||
{#if a.approved_at}
|
||||
<span class="text-hint">· {displayDate(a.approved_at)}</span>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
@@ -7,10 +7,11 @@
|
||||
import { setViewToken } from '$lib/viewToken'
|
||||
import { setLicense } from '$lib/enterpriseUtils'
|
||||
import { applyDarkModeVariant } from '$lib/darkModeVariant'
|
||||
import { displayDate, isNotFlow, truncateRev } from '$lib/utils'
|
||||
import { displayDate, isNotFlow, truncateRev, type StateStore } from '$lib/utils'
|
||||
import { Alert, Badge, Button, Skeleton } from '$lib/components/common'
|
||||
import DisplayResult from '$lib/components/DisplayResult.svelte'
|
||||
import FlowStatusViewer from '$lib/components/FlowStatusViewer.svelte'
|
||||
import FlowProgressBar from '$lib/components/flows/FlowProgressBar.svelte'
|
||||
import JobArgs from '$lib/components/JobArgs.svelte'
|
||||
import JobLoader from '$lib/components/JobLoader.svelte'
|
||||
import JobStatus from '$lib/components/JobStatus.svelte'
|
||||
@@ -54,6 +55,9 @@
|
||||
let loadError: { status?: number; message?: string } | undefined = $state(undefined)
|
||||
let jobLoader: JobLoader | undefined = $state(undefined)
|
||||
|
||||
// Runs nested under the flow that wait for events, filled by the graph as it loads them.
|
||||
let suspendStatus: StateStore<Record<string, { job: Job; nb: number }>> = $state({ val: {} })
|
||||
|
||||
let isFlow = $derived(job != undefined && !isNotFlow(job?.job_kind))
|
||||
|
||||
// Clear the previous run first: `isFlow` then falls back to false, which remounts the
|
||||
@@ -156,7 +160,16 @@
|
||||
</div>
|
||||
|
||||
{#if isFlow}
|
||||
<!-- Drawn from the loaded job alone: it reads nothing the share token does not. -->
|
||||
<FlowProgressBar
|
||||
{job}
|
||||
slim
|
||||
textPosition="bottom"
|
||||
showStepId
|
||||
waitingNested={Object.keys(suspendStatus.val).length > 0}
|
||||
/>
|
||||
<FlowStatusViewer
|
||||
bind:suspendStatus
|
||||
jobId={job.id}
|
||||
initialJob={job}
|
||||
workspaceId={workspace}
|
||||
|
||||
@@ -389,6 +389,12 @@ components:
|
||||
approval messages. 'detailed' (used when unset) shows the flow details
|
||||
(arguments, graph, approvers); 'minimal' shows only the request: the step
|
||||
description, form and approve/reject actions
|
||||
show_on_home:
|
||||
type: boolean
|
||||
description: >-
|
||||
If true, a run waiting on this step is listed on the Home page of each user who
|
||||
can approve it. Leave unset when the approval request is sent through another
|
||||
channel (Slack, Discord, email), so it does not sit there unanswered
|
||||
priority:
|
||||
type: number
|
||||
description: Execution priority for this step (higher numbers run first)
|
||||
@@ -1528,6 +1534,15 @@ components:
|
||||
type: integer
|
||||
approver:
|
||||
type: string
|
||||
approved_at:
|
||||
type: string
|
||||
format: date-time
|
||||
description: absent for approvals recorded before it was kept
|
||||
approved:
|
||||
type: boolean
|
||||
description: >
|
||||
false for a rejection the flow continued past; absent for approvals recorded
|
||||
before it was kept
|
||||
required:
|
||||
- resume_id
|
||||
- approver
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user