feat: show why a step waits: sleep, concurrency limit, approval (#12607)

* feat: show sleeping and concurrency-held steps in the run page and graph

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

* fix: keep waiting reasons live while a run or flow sits idle

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

* fix: stop polling waits a concurrency limit cannot hold

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

* fix: drop stale waiting-step reads and clear ended sleeps

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

* 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: show sleep and concurrency holds across the run graph, header and timeline

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

* fix: show sleeps in the blue of a job scheduled for later

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>

* fix: show a sleep as a wait, marked by its moon rather than a color

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>

* feat: say a step is retrying in the progress bar instead of above the graph

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: label a step waiting for approval and move concurrency holds above the step

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

* fix: label an approval wait above the step that waits for it

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>

* fix: count a hold live on the key badge, quote step ids, drop the step count from wait badges

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

* fix: keep wait text gray with the color in its icon, say waiting for approval in node status

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

* fix: stop counting the hold of a run canceled while held

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

* chore: update ee-repo-ref to 302da0e8e3817d5cbda5cf1053a9fe89019d7c27

This commit updates the EE repository reference after PR #1006 was merged in windmill-ee-private.

Previous ee-repo-ref: 6f6d8e3bf42a298c5eb90edab61d5a273d304a1a

New ee-repo-ref: 302da0e8e3817d5cbda5cf1053a9fe89019d7c27

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
hugocasa
2026-11-26 00:09:00 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot] Ruben Fiszel
parent 53ebb94ddb
commit 182356ec35
32 changed files with 1066 additions and 160 deletions
@@ -0,0 +1,28 @@
{
"db_name": "PostgreSQL",
"query": "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"\n FROM concurrency_key WHERE job_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "held!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
null
]
},
"hash": "0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE concurrency_key SET released_at = $2 WHERE job_id = $1 AND released_at IS NULL",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Timestamptz"
]
},
"nullable": []
},
"hash": "79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c"
}
@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "deferred_from",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "released_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true
]
},
"hash": "eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3"
}
+1 -1
View File
@@ -1 +1 @@
6302def89634fcf38db8c71122f1a4bdfe60f937
302da0e8e3817d5cbda5cf1053a9fe89019d7c27
@@ -0,0 +1 @@
ALTER TABLE concurrency_key DROP COLUMN IF EXISTS released_at;
@@ -0,0 +1,2 @@
-- When the concurrency limit let in a job it had held back: the time the job was last due.
ALTER TABLE concurrency_key ADD COLUMN IF NOT EXISTS released_at TIMESTAMPTZ;
+32
View File
@@ -27977,6 +27977,38 @@ paths:
application/json:
schema:
type: string
/concurrency_groups/{id}/key_status:
get:
summary: Get a job's concurrency key and whether its limit held it back
description: Requires read access to the job, the same as reading the run itself. Returns null when the job has no concurrency key.
operationId: getConcurrencyKeyStatus
tags:
- concurrencyGroups
parameters:
- $ref: "#/components/parameters/JobId"
responses:
"200":
description: concurrency key and deferral of the given job
content:
application/json:
schema:
type: object
nullable: true
properties:
key:
type: string
deferred_from:
type: string
format: date-time
nullable: true
description: When the job was first due. Set the first time its concurrency limit held it back, and kept after it ran.
released_at:
type: string
format: date-time
nullable: true
description: When the concurrency limit let in a job it had held back, as the time the job was last due. The rest until it started is queue time.
required:
- key
/w/{workspace}/concurrency_groups/list_jobs:
get:
summary: Get intervals of job runtime concurrency
+75 -29
View File
@@ -1,6 +1,8 @@
use std::sync::Arc;
use axum::{extract::Path, routing::get, Extension, Json, Router};
use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;
use windmill_common::{
db::UserDB,
@@ -18,6 +20,7 @@ use crate::{
pub fn global_service() -> Router {
windmill_api_jobs::concurrency_groups::global_service()
.route("/{job_id}/key", get(get_concurrency_key))
.route("/{job_id}/key_status", get(get_concurrency_key_status))
}
/// A concurrency key embeds the job's workspace, its runnable path and any
@@ -31,6 +34,44 @@ pub fn global_service() -> Router {
/// job's own workspace before evaluating access — that also rejects non-members, for whom
/// the job does not exist. Members reaching [`require_job_read_access`] get its 403, which
/// discloses existence only inside a workspace they belong to.
async fn require_concurrency_key_read(
token: &str,
cache: &AuthCache,
db: &DB,
user_db: &UserDB,
view_token: Option<&str>,
job_id: Uuid,
) -> Result<(), Error> {
let not_found = || Error::NotFound(format!("Job {job_id} not found"));
// A caller who cannot reach the job must not be able to tell it apart from a job
// that does not exist, so both answer with the same 404.
let job = sqlx::query!(
"SELECT workspace_id, created_by FROM v2_job WHERE id = $1",
job_id
)
.fetch_optional(db)
.await?
.ok_or_else(not_found)?;
let authed_in_workspace = cache
.get_authed(Some(job.workspace_id.clone()), token)
.await
.ok_or_else(not_found)?;
windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?;
require_job_read_access(
db,
user_db,
&authed_in_workspace,
&job.workspace_id,
&job_id,
&job.created_by,
view_token,
)
.await
}
async fn get_concurrency_key(
_authed: ApiAuthed,
Tokened { token }: Tokened,
@@ -40,37 +81,42 @@ async fn get_concurrency_key(
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<String>> {
let not_found = || Error::NotFound(format!("Job {job_id} not found"));
// A caller who cannot reach the job must not be able to tell it apart from a job
// that does not exist, so both answer with the same 404.
let job = sqlx::query!(
"SELECT workspace_id, created_by FROM v2_job WHERE id = $1",
job_id
)
.fetch_optional(&db)
.await?
.ok_or_else(not_found)?;
let authed_in_workspace = cache
.get_authed(Some(job.workspace_id.clone()), &token)
.await
.ok_or_else(not_found)?;
windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?;
require_job_read_access(
&db,
&user_db,
&authed_in_workspace,
&job.workspace_id,
&job_id,
&job.created_by,
view_token.as_deref(),
)
.await?;
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
let key = sqlx::query_scalar!("SELECT key FROM concurrency_key WHERE job_id = $1", job_id)
.fetch_optional(&db)
.await?;
Ok(Json(key))
}
#[derive(Serialize)]
struct ConcurrencyKeyStatus {
key: String,
/// When the job was first due. Set the first time its limit held it back, and kept
/// after it ran.
deferred_from: Option<DateTime<Utc>>,
/// When the limit let the job in: the time it was last due. The rest until it started
/// is queue time.
released_at: Option<DateTime<Utc>>,
}
async fn get_concurrency_key_status(
_authed: ApiAuthed,
Tokened { token }: Tokened,
Extension(cache): Extension<Arc<AuthCache>>,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<ConcurrencyKeyStatus>> {
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
let status = sqlx::query_as!(
ConcurrencyKeyStatus,
"SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1",
job_id
)
.fetch_optional(&db)
.await?;
Ok(Json(status))
}
+34
View File
@@ -5619,6 +5619,40 @@ pub async fn custom_concurrency_key(
.await
}
/// A job's concurrency key, and whether its limit has held it back without letting it in yet.
pub async fn concurrency_key_and_hold(
db: &Pool<Postgres>,
job_id: &Uuid,
) -> windmill_common::error::Result<Option<(String, bool)>> {
let fut = async || {
sqlx::query!(
"SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"
FROM concurrency_key WHERE job_id = $1",
job_id
)
.fetch_optional(db)
.await
};
fut.retry(
ConstantBuilder::default()
.with_delay(std::time::Duration::from_secs(3))
.with_max_times(5)
.build(),
)
.notify(|err, dur| {
tracing::error!(
"Could not get concurrency key for job {job_id}, retrying in {dur:#?}, err: {err:#?}"
);
})
.await
.map(|r| r.map(|r| (r.key, r.held)))
.map_err(|e| {
Error::internal_err(format!(
"Could not get concurrency key for job {job_id}: {e:#}"
))
})
}
pub async fn concurrency_key(
db: &Pool<Postgres>,
id: &Uuid,
@@ -638,6 +638,7 @@
slim
textPosition="bottom"
showStepId
stepStates={localModuleStates}
waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0}
/>
{/if}
@@ -97,13 +97,11 @@
let lastJobId: string = untrack(() => jobId)
let retryStatus = $state({ val: {} })
let globalRefreshes: Record<string, ((clear, root) => Promise<void>)[]> = $state({})
setContext<FlowStatusViewerContext>('FlowStatusViewer', {
flowState,
suspendStatus,
retryStatus,
hideDownloadInGraph: untrack(() => hideDownloadInGraph),
hideNodeDefinition: untrack(() => hideNodeDefinition),
hideTimeline: untrack(() => hideTimeline),
@@ -119,7 +117,6 @@
if (jobId !== lastJobId) {
console.log('updateJobId 3', jobId)
lastJobId = jobId
retryStatus.val = {}
suspendStatus.val = {}
globalRefreshes = {}
for (let key in localModuleStates) delete flowState[key]
@@ -13,8 +13,10 @@
type CompletedJob,
type WorkflowStatus,
type FlowNote,
type FlowValue
type FlowValue,
ConcurrencyGroupsService
} from '$lib/gen'
import { getDbClockNow } from '$lib/forLater'
import FlowJobResult from './FlowJobResult.svelte'
import WorkflowTimeline from './WorkflowTimeline.svelte'
import DisplayResult from './DisplayResult.svelte'
@@ -84,7 +86,6 @@
let {
flowState: flowStateStore,
retryStatus,
suspendStatus,
hideDownloadInGraph,
hideTimeline,
@@ -631,17 +632,6 @@
}
updateInnerModules(status)
// The preprocessor (step -1) and the error handler (past the steps) retry outside `modules`.
const outsideSteps = status.step < 0 || status.step >= status.modules.length
let count =
job?.type === 'CompletedJob' || (retryingStepId == undefined && !outsideSteps)
? undefined
: status.retry?.fail_count
if (count) {
retryStatus.val[jobId ?? ''] = count
} else if (retryStatus.val[jobId ?? ''] != undefined) {
delete retryStatus.val[jobId ?? '']
}
let jobStatus = job?.flow_status?.modules?.[job?.flow_status.step]
if (jobStatus && jobStatus.count != undefined) {
@@ -725,6 +715,94 @@
/** The step waiting for or running its next attempt, if any. */
let retryingStepId: string | undefined = undefined
// A concurrency limit moves a waiting step's due time each time it holds it back, often by
// only a few seconds, so a step still waiting once that time has passed is read again, at
// most every 5s. The parent flow does not change meanwhile, hence the timer below.
const waitingStepChecks = new Map<string, number>()
// A step's concurrency key is written as it is queued: one without can never be held, so
// past the end of its sleep only a change of the parent flow can change what it waits for.
const unlimitedSteps = new Set<string>()
function waitingStepDue(mod: FlowStatusModule): boolean {
const last = waitingStepChecks.get(mod.job ?? '')
if (last != undefined && Date.now() - last < 5000) return false
const scheduledFor = localModuleStates[mod.id ?? '']?.scheduled_for
return scheduledFor == undefined || new Date(scheduledFor) <= getDbClockNow()
}
function loadWaitingStep(mod: FlowStatusModule, retrying: boolean) {
waitingStepChecks.set(mod.job ?? '', Date.now())
const workspace = workspaceId ?? $operatingWorkspace ?? ''
Promise.all([
JobService.getJob({ workspace, id: mod.job ?? '', noLogs: true, noCode: true }),
ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: mod.job ?? '' }).catch(() => undefined)
])
.then(([job, held]) => {
// The step may have started or ended while this was in flight.
const now = innerModules?.find((m) => m.id === mod.id)
if (now?.type !== 'WaitingForExecutor' || now.job !== mod.job) return
if (held === null) unlimitedSteps.add(mod.job ?? '')
const scheduledFor: string | undefined = job?.['scheduled_for']
// Once let in, a held job only waits for a worker.
const waiting_reason: GraphModuleState['waiting_reason'] =
held?.deferred_from && !held.released_at
? 'concurrency'
: scheduledFor &&
new Date(scheduledFor) > getDbClockNow() &&
!retrying &&
sleepsBefore(mod.id)
? 'sleep'
: undefined
setModuleState(mod.id ?? '', {
type: mod.type,
scheduled_for: job?.['scheduled_for'],
waiting_reason,
concurrency_key: waiting_reason === 'concurrency' ? held?.key : undefined,
held_since:
waiting_reason === 'concurrency' ? (held?.deferred_from ?? undefined) : undefined,
job_id: job?.id,
parent_module: failedStepOf(mod),
args: job?.args,
tag: job?.tag,
script_hash: job?.script_hash
})
// So the timeline draws the wait while it lasts.
if (waiting_reason && job?.created_at)
setDurationStatusByJob(
mod.id ?? '',
job.id,
{ created_at: new Date(job.created_at).getTime() },
true
)
})
.catch((e) => {
console.error(`Could not load inner module for job ${mod.job}`, e)
})
}
$effect(() => {
if (job?.type !== 'QueuedJob' || isReplay) return
const id = setInterval(() => {
innerModules?.forEach((mod) => {
if (
mod.type === 'WaitingForExecutor' &&
(!unlimitedSteps.has(mod.job ?? '') ||
localModuleStates[mod.id ?? '']?.waiting_reason === 'sleep') &&
waitingStepDue(mod)
) {
loadWaitingStep(mod, mod.id === retryingStepId)
}
})
}, 5000)
return () => clearInterval(id)
})
/** Whether the step before `id` sleeps once done, which pushes `id` back by that long. */
function sleepsBefore(id: string | undefined): boolean {
const raw = job?.raw_flow?.modules ?? []
const i = raw.findIndex((m) => m.id === id)
return i > 0 && !!raw[i - 1].sleep
}
function updateInnerModules(status: FlowStatus) {
const found = findDeniedApproval(status)
const denied = found?.approval
@@ -750,6 +828,24 @@
if (mod.type === 'Failure' && localModuleStates[mod.id ?? '']?.type === 'Success') {
setModuleState(mod.id ?? '', { type: 'Failure' })
}
// The step after an approval step is the one that waits for it.
const approvalStep = innerModules?.[i - 1]
const approvalWait =
mod.id &&
job?.id &&
approvalStep?.id &&
approvalStep.type === 'Success' &&
mod.type === 'WaitingForEvents'
? {
job: job.id,
workspace: job.workspace_id,
step: approvalStep.id,
required: mod.count ?? 1
}
: undefined
if (mod.id && !deepEqual(approvalWait, localModuleStates[mod.id]?.approval_wait)) {
setModuleState(mod.id, { approval_wait: approvalWait })
}
if (mod.type === 'WaitingForEvents' && innerModules?.[i - 1]?.type === 'Success') {
setModuleState(mod.id ?? '', {
type: mod.type,
@@ -757,33 +853,9 @@
tag: job?.tag,
script_hash: job?.script_hash
})
} else if (
mod.type === 'WaitingForExecutor' &&
localModuleStates[mod.id ?? '']?.scheduled_for == undefined
) {
} else if (mod.type === 'WaitingForExecutor' && waitingStepDue(mod)) {
if (!isReplay) {
JobService.getJob({
workspace: workspaceId ?? $operatingWorkspace ?? '',
id: mod.job ?? '',
noLogs: true,
noCode: true
})
.then((job) => {
const newState = {
type: mod.type,
scheduled_for: job?.['scheduled_for'],
job_id: job?.id,
parent_module: failedStepOf(mod),
args: job?.args,
tag: job?.tag,
script_hash: job?.script_hash
}
setModuleState(mod.id ?? '', newState)
})
.catch((e) => {
console.error(`Could not load inner module for job ${mod.job}`, e)
})
loadWaitingStep(mod, mod.id === retryingId)
}
} else if (
(mod.flow_jobs || mod.branch_chosen) &&
@@ -1415,8 +1487,6 @@
let wrapperHeight: number = $state(0)
let retryStatusHeight: number = $state(0)
function removeFailureNode(id: string, parent_module: any) {
if (id?.startsWith('failure-') && parent_module) {
;[...globalModuleStates, localModuleStates].forEach((stateMap) => {
@@ -1437,12 +1507,33 @@
suspend?: boolean
/** Shown in place of the id. */
label?: string
/** The fixed sleep of the step before it, in seconds. */
sleepBefore?: number
/** An inline script with a concurrency limit, which can be held back. */
limited?: boolean
}
// Sleeps in branches and loop bodies are not looked at.
function timelineExtras(
modules: FlowModule[]
): Map<string, { sleepBefore?: number; limited?: boolean }> {
const extras = new Map<string, { sleepBefore?: number; limited?: boolean }>()
modules.forEach((m, i) => {
const sleep = modules[i - 1]?.sleep
const v = m.value
extras.set(m.id, {
sleepBefore: sleep?.type === 'static' ? Number(sleep.value) || undefined : undefined,
limited: v.type === 'rawscript' && (v.concurrent_limit ?? 0) > 0
})
})
return extras
}
function allModulesForTimeline(
modules: FlowModule[],
expandedSubflows: Record<string, { modules: FlowModule[]; groups?: any[] }>
): FlowModuleForTimeline[] {
const topExtras = timelineExtras(modules)
const ids = dfs(
modules,
(x) =>
@@ -1450,7 +1541,8 @@
id: x.id,
type: x.value.type,
suspend: x.suspend != undefined,
label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined
label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined,
...topExtras.get(x.id)
}) as FlowModuleForTimeline,
{
skipToolNodes: true
@@ -1469,6 +1561,7 @@
return []
}
let nprefix = buildPrefix(prefix, oid)
const extras = fms ? timelineExtras(fms) : undefined
return fms
? rec(
dfs(
@@ -1476,7 +1569,8 @@
(x) => ({
id: x.id.startsWith('subflow:') ? x.id : buildSubflowKey(x.id, nprefix),
type: x.value.type,
suspend: x.suspend != undefined
suspend: x.suspend != undefined,
...extras?.get(x.id)
}),
{ skipToolNodes: true }
),
@@ -2133,6 +2227,10 @@
<ModuleStatus
type={mod.type}
scheduled_for={localModuleStates?.[mod.id ?? '']?.scheduled_for}
waiting_reason={localModuleStates?.[mod.id ?? '']?.waiting_reason}
concurrency_key={localModuleStates?.[mod.id ?? '']?.concurrency_key}
held_since={localModuleStates?.[mod.id ?? '']?.held_since}
approval_wait={localModuleStates?.[mod.id ?? '']?.approval_wait}
/>
{/if}
</li>
@@ -2206,21 +2304,12 @@
<Splitpanes>
<Pane bind:size={graphPaneSize} minSize={30}>
<div class="bg-surface-secondary h-full {fillHeight ? '' : 'max-h-[1200px]'}">
<div class="flex flex-col" bind:clientHeight={retryStatusHeight}>
{#each Object.values(retryStatus?.val ?? {}) as count}
{#if count}
<span class="text-sm">
Retry in progress, # of failed attempts: {count}
</span>
{/if}
{/each}
</div>
<FlowGraphV2
{selectionManager}
triggerNode={true}
download={!hideDownloadInGraph}
minHeight={wrapperHeight - retryStatusHeight}
maxHeight={fillHeight ? wrapperHeight - retryStatusHeight : undefined}
minHeight={wrapperHeight}
maxHeight={fillHeight ? wrapperHeight : undefined}
fitOnLoad={fillHeight}
outerDivClass={fillHeight ? '' : 'max-h-[1200px]'}
success={jobId != undefined && isSuccess(job?.['success'])}
@@ -2441,6 +2530,10 @@
<ModuleStatus
type={node.type}
scheduled_for={node.scheduled_for}
waiting_reason={node.waiting_reason}
concurrency_key={node.concurrency_key}
held_since={node.held_since}
approval_wait={node.approval_wait}
skipped={node.skipped}
/>
{#if node.duration_ms}
+138 -15
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { displayDate, msToCompactDuration } from '$lib/utils'
import { ConcurrencyGroupsService } from '$lib/gen'
import { Loader2 } from 'lucide-svelte'
import TimelineBar from './TimelineBar.svelte'
import WaitTimeWarning from './common/waitTimeWarning/WaitTimeWarning.svelte'
@@ -135,6 +136,81 @@
})
const hasApprovalWait = $derived(Object.keys(approvalWaitByModule).length > 0)
// The hold of a limited step's job once it started; a live hold comes from the step's state.
let holds = $state<Record<string, { from?: number; to?: number } | null>>({})
$effect(() => {
for (const m of flowModules) {
if (!m.limited) continue
for (const j of items?.[m.id] ?? []) {
if (!j.started_at || j.id in untrack(() => holds)) continue
holds[j.id] = null
ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: j.id })
.then((s) => {
if (s?.deferred_from)
holds[j.id] = {
from: new Date(s.deferred_from).getTime(),
to: s.released_at ? new Date(s.released_at).getTime() : undefined
}
})
.catch(() => {})
}
}
})
type WaitSegment = { start: number; len: number; kind: 'sleep' | 'held' | 'wait' }
/** A job's wait split into the sleep before it, its concurrency hold and the rest. */
function waitSegments(
m: FlowModuleForTimeline,
job: { id: string; created_at?: number; started_at?: number },
single: boolean
): WaitSegment[] {
const b = { ...job, created_at: job.created_at ?? now }
const end = b.started_at ?? now
const state = localModuleStates[m.id]
const live = b.started_at == undefined && state?.type === 'WaitingForExecutor'
let sleepEnd: number | undefined
if (single && live && state?.waiting_reason === 'sleep' && state.scheduled_for)
sleepEnd = new Date(state.scheduled_for).getTime()
else if (single && m.sleepBefore) sleepEnd = b.created_at + m.sleepBefore * 1000
const hold =
live && state?.waiting_reason === 'concurrency' && state.held_since
? { from: new Date(state.held_since).getTime(), to: undefined }
: holds[b.id]
const clamp = (t: number) => Math.min(Math.max(t, b.created_at), end)
const segments: WaitSegment[] = []
let at = b.created_at
const push = (to: number, kind: WaitSegment['kind']) => {
to = clamp(to)
if (to > at) segments.push({ start: at, len: to - at, kind })
at = Math.max(at, to)
}
if (sleepEnd != undefined) push(sleepEnd, 'sleep')
if (hold?.from != undefined) {
push(hold.from, 'wait')
push(hold.to ?? end, 'held')
}
push(end, 'wait')
return segments
}
const segmentStyle = {
// A wait like the gray one, striped as one the flow asked for.
sleep: {
colorClass:
'bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)] !text-gray-700 dark:!text-gray-100',
label: 'Sleep'
},
held: { colorClass: 'bg-orange-400/90', label: 'Held by concurrency limit' },
wait: { colorClass: undefined, label: 'Wait' }
}
const hasSleep = $derived(
flowModules.some((m) => m.sleepBefore) ||
Object.values(localModuleStates).some((s) => s.waiting_reason === 'sleep')
)
const hasHold = $derived(
Object.values(holds).some((h) => h?.from != undefined) ||
Object.values(localModuleStates).some((s) => s.waiting_reason === 'concurrency')
)
</script>
<OnChange
@@ -160,6 +236,20 @@
<div class="h-2.5 w-2.5 rounded-sm bg-blue-500/90"></div>
<span>Execution</span>
</div>
{#if hasSleep}
<div class="flex gap-1.5 items-center">
<div
class="h-2.5 w-2.5 rounded-sm bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)]"
></div>
<span>Sleep</span>
</div>
{/if}
{#if hasHold}
<div class="flex gap-1.5 items-center">
<div class="h-2.5 w-2.5 rounded-sm bg-orange-400/90"></div>
<span>Concurrency limit</span>
</div>
{/if}
{#if hasApprovalWait}
<div class="flex gap-1.5 items-center">
<div class="h-2.5 w-2.5 rounded-sm bg-purple-400/80"></div>
@@ -184,8 +274,11 @@
/>
</div>
{/if}
{#each flowModules as { id: k, type: typ, suspend: isSuspend, label } (k)}
{@const subItems = items?.[k]?.filter((x) => x.created_at && x.started_at)}
{#each flowModules as m (m.id)}
{@const { id: k, type: typ, suspend: isSuspend, label } = m}
{@const subItems = items?.[k]?.filter(
(x) => x.created_at && (x.started_at || localModuleStates[k]?.waiting_reason)
)}
<div class="relative px-3 py-1.5">
<div class="flex items-center justify-between mb-0.5">
<div class="text-xs font-medium"
@@ -238,20 +331,50 @@
: now - b?.created_at
: 0}
{@const aw = isSuspend ? approvalWaitByModule[k] : undefined}
{@const segments =
waitingLen < 100 ? [] : waitSegments(m, b, subItems?.length === 1)}
<div class="flex w-full py-0.5 items-center" {style}>
<TimelineBar
position="left"
id={b?.id}
{total}
{min}
{compact}
gray
followedByBar={!!b.started_at}
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
started_at={b.created_at}
len={waitingLen < 100 ? 0 : waitingLen - 100}
running={b?.started_at == undefined}
/>
{#if segments.length <= 1}
<TimelineBar
position="left"
id={b?.id}
{total}
{min}
{compact}
gray
colorClass={segmentStyle[segments[0]?.kind ?? 'wait'].colorClass}
tooltip={segments[0] && segments[0].kind !== 'wait'
? `${segmentStyle[segments[0].kind].label} · ${msToCompactDuration(segments[0].len, 1)}`
: undefined}
followedByBar={!!b.started_at}
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
started_at={b.created_at}
len={waitingLen < 100 ? 0 : waitingLen - 100}
running={b?.started_at == undefined}
/>
{:else}
{#each segments as seg, i (i)}
<TimelineBar
position={i === 0 ? 'left' : 'none'}
id={b?.id}
{total}
{min}
{compact}
gray
concat={i > 0}
colorClass={segmentStyle[seg.kind].colorClass}
tooltip="{segmentStyle[seg.kind].label} · {msToCompactDuration(
seg.len,
1
)}"
followedByBar
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
started_at={seg.start}
len={i === segments.length - 1 ? Math.max(seg.len - 100, 0) : seg.len}
running={b?.started_at == undefined}
/>
{/each}
{/if}
{#if b.started_at}
<TimelineBar
position={aw || waitingLen < 100 ? 'center' : 'right'}
+17 -1
View File
@@ -14,9 +14,13 @@
interface Props {
job: QueuedJob | CompletedJob | undefined
large?: boolean
/** Its concurrency limit has held the job back, so a later due time is the next check. */
heldByConcurrency?: boolean
/** Why the step the flow is at has not started. */
stepWaiting?: 'sleep' | 'concurrency'
}
let { job, large = false }: Props = $props()
let { job, large = false, heldByConcurrency = false, stepWaiting }: Props = $props()
let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? [])
</script>
@@ -90,6 +94,12 @@
{/if}
</Badge>
</div>
{:else if job && 'running' in job && job.running && stepWaiting}
<div>
<Badge {large} color={stepWaiting === 'sleep' ? 'gray' : 'orange'}>
{stepWaiting === 'sleep' ? 'Sleeping' : 'Step held by concurrency limit'}
</Badge>
</div>
{:else if job && 'running' in job && job.running}
<div class="flex flex-row flex-wrap gap-1 items-center">
<Badge {large} color="yellow">
@@ -100,6 +110,12 @@
</Badge>
{@render continuedOnErrorBadge()}
</div>
{:else if job && 'running' in job && heldByConcurrency}
<div>
<Badge color="orange" {large} title="Next check by {displayDate(job.scheduled_for, true)}">
Held by concurrency limit
</Badge>
</div>
{:else if job && 'running' in job && 'scheduled_for' in job && job.scheduled_for && forLater(job.scheduled_for)}
<div>
<Badge color="blue" {large}>
+51 -10
View File
@@ -1,32 +1,73 @@
<script lang="ts">
import type { FlowStatusModule } from '$lib/gen'
import type { GraphModuleState } from './graph'
import { Badge } from './common'
import { forLater } from '$lib/forLater'
import { displayDate } from '$lib/utils'
import { Hourglass } from 'lucide-svelte'
import { displayDate, msToCompactDuration } from '$lib/utils'
import { Gauge, Hourglass, Moon } from 'lucide-svelte'
import { useApprovalCount } from './graph/approvalCount.svelte'
interface Props {
type: FlowStatusModule['type'];
scheduled_for: Date | undefined;
skipped?: boolean;
type: FlowStatusModule['type']
scheduled_for: Date | undefined
waiting_reason?: GraphModuleState['waiting_reason']
concurrency_key?: string
/** When its concurrency limit first held the step back. */
held_since?: string
approval_wait?: GraphModuleState['approval_wait']
skipped?: boolean
}
let { type, scheduled_for, skipped = false }: Props = $props();
let {
type,
scheduled_for,
waiting_reason = undefined,
concurrency_key = undefined,
held_since = undefined,
approval_wait = undefined,
skipped = false
}: Props = $props()
const approval = useApprovalCount(() => approval_wait)
let now = $state(Date.now())
$effect(() => {
if (!waiting_reason) return
const id = setInterval(() => (now = Date.now()), 1000)
return () => clearInterval(id)
})
let sleepLeft = $derived(Math.max(new Date(scheduled_for ?? now).getTime() - now, 0))
let heldFor = $derived(held_since ? Math.max(now - new Date(held_since).getTime(), 0) : undefined)
</script>
{#if type == 'WaitingForEvents'}
<span class="italic text-xs text-violet-700 dark:text-violet-400">
<Hourglass class="inline" size={14} />
Waiting to be resumed by resume events such as approvals
<span class="italic text-xs text-primary">
<Hourglass class="inline text-violet-500" size={14} />
{approval_wait ? approval.label : 'Waiting to be resumed by resume events such as approvals'}
</span>
{:else if type == 'WaitingForPriorSteps'}
<span class="italic text-xs text-primary">
<Hourglass class="inline" size={14} />
Waiting for prior steps to complete
</span>
{:else if type == 'WaitingForExecutor' && waiting_reason === 'sleep'}
<span class="italic text-xs text-primary">
<Moon class="inline" size={14} />
Sleeping until {displayDate(scheduled_for, true)} · {msToCompactDuration(sleepLeft, 0)} left
</span>
{:else if type == 'WaitingForExecutor' && waiting_reason === 'concurrency'}
<span class="italic text-xs text-primary">
<Gauge class="inline text-orange-500" size={14} />
Held by concurrency limit{heldFor != undefined
? ` · ${msToCompactDuration(heldFor, 0)}`
: ''}{concurrency_key ? ` (key ${concurrency_key})` : ''}, next check by {displayDate(
scheduled_for,
true
)}
</span>
{:else if type == 'WaitingForExecutor'}
<span class="italic text-xs text-primary">
<Hourglass class="inline" />
<Hourglass class="inline" size={14} />
{#if scheduled_for && forLater(scheduled_for.toString())}
Job is scheduled to be executed at {displayDate(scheduled_for, true)}
{:else}
@@ -4,7 +4,8 @@
import Popover from './Popover.svelte'
interface Props {
position?: 'center' | 'left' | 'right'
/** `none`: a middle piece of a bar split in several. */
position?: 'center' | 'left' | 'right' | 'none'
total: number
min: number | undefined
started_at: number | undefined
@@ -61,7 +62,9 @@
? 'rounded-l-md'
: position == 'right'
? 'rounded-r-md'
: 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black"
: position == 'none'
? ''
: 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black"
>
{#snippet text()}
{#if tooltip}
@@ -4,6 +4,8 @@
import { forLater } from '$lib/forLater'
import { waitingRequest } from '../agentRequest'
import type { Snippet } from 'svelte'
import type { GraphModuleState } from '../graph'
import { displayDate } from '$lib/utils'
interface Props {
job?: Job | undefined
@@ -13,6 +15,8 @@
textPosition?: 'top' | 'bottom'
// Prefer step ID over step index when both are available
showStepId?: boolean
/** The run graph's step states, which say why a step that has not started is waiting. */
stepStates?: Record<string, GraphModuleState>
errorAction?: Snippet
/** A run nested under this one waits on an approval, which its own steps don't show. */
waitingNested?: boolean
@@ -25,10 +29,42 @@
slim = false,
textPosition = 'top',
showStepId = false,
stepStates = undefined,
errorAction,
waitingNested = false
}: Props = $props()
// The current step, or a step waiting inside it when it is a subflow.
let waitingText = $derived.by(() => {
const current = job?.flow_status?.modules?.[job.flow_status.step]?.id
if (!current || !stepStates) return undefined
const inside = `subflow:${current}:`
const retrying = Object.entries(stepStates).find(
([key, s]) =>
(key === current || key.startsWith(inside)) &&
(s.type === 'WaitingForExecutor' || s.type === 'InProgress') &&
(s.retries ?? 0) > 0
)
if (retrying) {
const [key, s] = retrying
const n = s.retries ?? 0
return `Retrying step '${key.split(':').pop()}', ${n} failed attempt${n === 1 ? '' : 's'}`
}
const found = Object.entries(stepStates).find(
([key, s]) =>
(key === current || key.startsWith(inside)) &&
s.type === 'WaitingForExecutor' &&
s.waiting_reason
)
if (!found) return undefined
const [key, s] = found
const step = key.split(':').pop()
const until = displayDate(s.scheduled_for, true)
return s.waiting_reason === 'sleep'
? `Sleeping before step '${step}' until ${until}`
: `Step '${step}' held by concurrency limit, next check by ${until}`
})
let error: number | undefined = $state(undefined)
let index = $state(0)
let subIndex: number | undefined = $state(undefined)
@@ -196,5 +232,6 @@
{isCanceled}
{isScheduled}
{isSkipped}
{waitingText}
{errorAction}
/>
@@ -66,6 +66,8 @@
pathHref?: string
nodeState?: FlowNodeState
retries?: number | undefined
/** In a run, while its concurrency limit holds the step back. */
held?: { since?: string; nextCheck?: Date | string }
/** In a run, the attempts the retry badge picks from. */
attempts?: RetryAttempts | undefined
warningMessage?: string | undefined
@@ -101,6 +103,7 @@
pathHref = undefined,
nodeState,
retries = undefined,
held = undefined,
attempts = undefined,
warningMessage = undefined,
editMode = false,
@@ -311,6 +314,7 @@
<StepSettingsBar
{settings}
{retries}
{held}
{attempts}
onOpenChange={(o) => (settingsMenuOpen = o)}
onOpenSetting={editMode && id
@@ -32,6 +32,8 @@
nodeState?: FlowNodeState
duration_ms?: number | undefined
retries?: number | undefined
/** In a run, while its concurrency limit holds the step back. */
held?: { since?: string; nextCheck?: Date | string }
flowJobs:
| {
flowJobs: string[]
@@ -83,6 +85,7 @@
nodeState,
duration_ms = undefined,
retries = undefined,
held = undefined,
flowJobs,
attempts = undefined,
editMode = false,
@@ -283,6 +286,7 @@
{:else}
<FlowModuleSchemaItem
{retries}
{held}
attempts={attempts && !insertable
? {
jobs: attempts.flowJobs,
@@ -15,7 +15,7 @@
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import { Button } from '$lib/components/common'
import { fade } from 'svelte/transition'
import type { Item } from '$lib/utils'
import { msToCompactDuration, type Item } from '$lib/utils'
import AttemptPicker from './AttemptPicker.svelte'
import type { StepSettingKey, StepSettingView } from '../flowStepSettings'
@@ -25,6 +25,8 @@
/** Failed attempts so far. */
retries?: number
attempts?: RetryAttempts
/** In a run, while its concurrency limit holds the step back. */
held?: { since?: string; nextCheck?: Date | string }
/** Makes each setting's row open that setting in the step's settings panel. */
onOpenSetting?: (key: StepSettingKey) => void
onOpenChange?: (open: boolean) => void
@@ -34,6 +36,7 @@
settings,
retries = undefined,
attempts = undefined,
held = undefined,
onOpenSetting,
onOpenChange
}: Props = $props()
@@ -87,9 +90,26 @@
// With nothing else to list, the menu is the attempt list itself, one hover fewer.
let attemptsOnly = $derived(!!pickerProps && settings.length === 1)
// Read as the menu opens: the held time it shows does not tick.
let heldDetail = $derived(
held?.since && open
? ` · held ${msToCompactDuration(Math.max(Date.now() - new Date(held.since).getTime(), 0), 0)}`
: held
? ' · held'
: undefined
)
let items: Item[] = $derived(
ordered.map((s) => {
const action = onOpenSetting && (() => onOpenSetting(s.key))
if (s.key === 'concurrency' && heldDetail)
return {
displayName: s.label,
icon: s.icon,
iconColor: '#f97316',
detail: s.summary.text + heldDetail,
action
}
if (s.key !== 'retries')
return { displayName: s.label, icon: s.icon, detail: s.summary.text, action }
if (pickerProps) {
@@ -143,13 +163,14 @@
unifiedSize="2xs"
wrapperClasses="bg-surface rounded-md"
btnClasses="px-2"
title="Step settings"
title={held ? 'Step settings: held by its concurrency limit' : 'Step settings'}
>
<span class="flex flex-row items-center gap-1.5">
{#each shown as s (s.key)}
{@const Icon = s.icon}
<span
class="flex flex-row items-center gap-0.5 {s.key === 'retries' && retries
class="flex flex-row items-center gap-0.5 {(s.key === 'retries' && retries) ||
(s.key === 'concurrency' && held)
? 'text-orange-500'
: ''}"
>
@@ -0,0 +1,28 @@
import { JobService } from '$lib/gen'
import type { GraphModuleState } from './model'
/** How many approvals a waiting step has received so far. Approvals coming in do not change the
* run until the last one, so the count is read on its own, and only when there is more than one
* to count. */
export function useApprovalCount(wait: () => GraphModuleState['approval_wait']) {
let count = $state<number | undefined>(undefined)
$effect(() => {
const w = wait()
if (!w || w.required <= 1 || !w.workspace) return
const args = { workspace: w.workspace, jobId: w.job, stepId: w.step }
const read = () =>
JobService.getApprovalStepDetail(args)
.then((d) => (count = d.approvals.length))
.catch(() => {})
read()
const id = setInterval(read, 10000)
return () => clearInterval(id)
})
return {
/** "Waiting for approval", with "· 1 of 2" once some are in. */
get label() {
const w = wait()
return `Waiting for approval${count && w ? ` · ${count} of ${w.required}` : ''}`
}
}
}
@@ -44,6 +44,20 @@ export class FlowRunStatus {
return count
}
/** Steps inside the subflow step `id`, at any depth, waiting for an approval, waiting out a
* sleep or held by their concurrency limit. */
waitingStepsInside(id: string): { approval: number; sleep: number; concurrency: number } {
const prefix = (id.startsWith('subflow:') ? id : 'subflow:' + id) + ':'
const count = { approval: 0, sleep: 0, concurrency: 0 }
for (const [key, state] of this.#moduleStates) {
if (!key.startsWith(prefix)) continue
if (state.approval_wait) count.approval++
else if (state.type === 'WaitingForExecutor' && state.waiting_reason)
count[state.waiting_reason]++
}
return count
}
setModuleStates(next: Record<string, GraphModuleState> | undefined) {
const incoming = next ?? {}
for (const id of [...this.#moduleStates.keys()]) {
+9 -1
View File
@@ -29,7 +29,6 @@ export type DurationStatus = {
export type FlowStatusViewerContext = {
flowState?: FlowState
retryStatus: StateStore<Record<string, number | undefined>>
/** `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
@@ -48,6 +47,15 @@ export type GraphModuleState = {
result?: any
tag?: string
scheduled_for?: Date
/** Why a `WaitingForExecutor` step is due later: the previous step's sleep, or its own
* concurrency limit holding it back (`concurrency_key`). */
waiting_reason?: 'sleep' | 'concurrency'
/** On the step waiting for the approval step `step` before it: their run, and how many
* approvals it needs. */
approval_wait?: { job: string; workspace?: string; step: string; required: number }
/** When its concurrency limit first held the step back. */
held_since?: string
concurrency_key?: string
job_id?: string
parent_module?: string
selectedForloop?: string
@@ -8,10 +8,14 @@
StickyNote,
PictureInPicture2,
Bug,
RefreshCw
RefreshCw,
Gauge,
Hourglass,
Moon
} from 'lucide-svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import NodeWrapper from './NodeWrapper.svelte'
import WaitingMark from './WaitingMark.svelte'
import AiDecisionNodeBranch from './AiDecisionNodeBranch.svelte'
import type { ModuleN } from '../../graphBuilder.svelte'
import { jobToGraphModuleState } from '$lib/components/modulesTest.svelte'
@@ -219,6 +223,24 @@
: undefined
})
// Live, so it takes the slot of the retried and error handler counts while it lasts.
let waitingInside = $derived.by(() => {
if (!flowRunStatus?.showsRun || data.editMode || data.module?.value?.type !== 'flow') return
const { approval, sleep, concurrency } = flowRunStatus.waitingStepsInside(data.id)
if (approval > 0)
return {
reason: 'approval' as const,
label: `${approval === 1 ? 'Approval' : `${approval} approvals`} waiting inside`
}
if (concurrency > 0)
return {
reason: 'concurrency' as const,
label: `${concurrency} step${concurrency === 1 ? '' : 's'} held by concurrency limit`
}
if (sleep > 0)
return { reason: 'sleep' as const, label: `${sleep} step${sleep === 1 ? '' : 's'} sleeping` }
})
let type = $derived.by(() => {
let typ = state?.type
if (!typ && flowJobs) {
@@ -319,6 +341,9 @@
nodeState={state?.skipped ? '_Skipped' : type}
duration_ms={state?.duration_ms}
retries={state?.retries}
held={type === 'WaitingForExecutor' && state?.waiting_reason === 'concurrency'
? { since: state.held_since, nextCheck: state.scheduled_for }
: undefined}
{flowJobs}
{attempts}
on:delete={(e) => {
@@ -352,11 +377,61 @@
: undefined}
/>
{#await hiddenErrorHandlers}
{@render insideBar(retriedInside, undefined)}
{:then handlers}
{@render insideBar(retriedInside, handlers)}
{/await}
{#if type === 'WaitingForExecutor' && state?.waiting_reason}
<WaitingMark
reason={state.waiting_reason}
until={state.scheduled_for}
concurrencyKey={state.concurrency_key}
heldSince={state.held_since}
onclick={() => data.module && data.eventHandlers.select(data.module.id)}
/>
{:else if state?.approval_wait}
<WaitingMark
reason="approval"
approvalWait={state.approval_wait}
onclick={() => data.module && data.eventHandlers.select(data.module.id)}
/>
{/if}
{#if waitingInside}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="nodrag nopan absolute -left-1 top-[calc(100%+3px)] z-10"
onpointerdown={(e) => e.stopPropagation()}
>
<Button
variant="subtle"
unifiedSize="2xs"
startIcon={{
icon:
waitingInside.reason === 'approval'
? Hourglass
: waitingInside.reason === 'sleep'
? Moon
: Gauge,
classes:
waitingInside.reason === 'approval'
? 'text-violet-500'
: waitingInside.reason === 'sleep'
? ''
: 'text-orange-500'
}}
btnClasses="text-2xs text-secondary gap-1"
title="Expand to see the waiting steps"
onClick={(e) => {
e?.stopPropagation()
expandSubflow()
}}
>
{waitingInside.label}
</Button>
</div>
{:else}
{#await hiddenErrorHandlers}
{@render insideBar(retriedInside, undefined)}
{:then handlers}
{@render insideBar(retriedInside, handlers)}
{/await}
{/if}
{#if (data.module?.value?.type === 'branchall' || data.module?.value?.type === 'branchone') && data.insertable}
<div class="absolute -bottom-10 left-1/2 transform -translate-x-1/2 z-10 flex gap-1">
@@ -0,0 +1,79 @@
<script lang="ts">
import { Gauge, Hourglass, Moon } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import { useApprovalCount } from '../../approvalCount.svelte'
import { displayDate, msToCompactDuration } from '$lib/utils'
import type { GraphModuleState } from '../../model'
type Props = { onclick: () => void } & (
| {
reason: NonNullable<GraphModuleState['waiting_reason']>
until: Date | string | undefined
concurrencyKey?: string
heldSince?: string
}
| {
reason: 'approval'
approvalWait: NonNullable<GraphModuleState['approval_wait']>
}
)
let props: Props = $props()
let now = $state(Date.now())
$effect(() => {
if (props.reason === 'approval') return
const id = setInterval(() => (now = Date.now()), 1000)
return () => clearInterval(id)
})
const approval = useApprovalCount(() =>
props.reason === 'approval' ? props.approvalWait : undefined
)
let label = $derived.by(() => {
if (props.reason === 'approval') return approval.label
if (props.reason === 'sleep')
return `Sleeping · ${msToCompactDuration(Math.max(new Date(props.until ?? now).getTime() - now, 0), 0)}`
const held = props.heldSince
? msToCompactDuration(Math.max(now - new Date(props.heldSince).getTime(), 0), 0)
: undefined
return `Held by concurrency limit${held ? ` · ${held}` : ''}`
})
let title = $derived.by(() => {
if (props.reason === 'approval') return 'The run waits for this step to be approved'
if (props.reason === 'sleep')
return `Sleeping after the previous step until ${displayDate(props.until, true)}`
return `Held by its concurrency limit${props.concurrencyKey ? ` (key ${props.concurrencyKey})` : ''}, next check by ${displayDate(props.until, true)}`
})
</script>
<!-- What keeps a step from starting sits above it; finished steps show how long they ran at the
other end of that edge. -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="nodrag nopan absolute -left-1 bottom-[calc(100%+3px)] z-10"
onpointerdown={(e) => e.stopPropagation()}
>
<Button
variant="subtle"
unifiedSize="2xs"
startIcon={{
icon: props.reason === 'approval' ? Hourglass : props.reason === 'sleep' ? Moon : Gauge,
classes:
props.reason === 'approval'
? 'text-violet-500'
: props.reason === 'concurrency'
? 'text-orange-500'
: ''
}}
btnClasses="text-2xs text-secondary gap-1"
{title}
onClick={(e) => {
e?.stopPropagation()
props.onclick()
}}
>
{label}
</Button>
</div>
@@ -37,6 +37,8 @@
isScheduled?: boolean
// Whether the job was skipped (early-stop labelled as skipped)
isSkipped?: boolean
/** Why the next step has not started yet, e.g. a sleep or a concurrency limit. */
waitingText?: string
/** Rendered after "Error occurred" when the bar is in its error state. */
errorAction?: Snippet
}
@@ -60,6 +62,7 @@
isCanceled = false,
isScheduled = false,
isSkipped = false,
waitingText = undefined,
errorAction
}: Props = $props()
let duration = 200
@@ -166,7 +169,7 @@
{:else if status == 'running' && !isCanceled && !isScheduled && !isSkipped}
<Loader2 class="animate-spin" size={14} />
{/if}
{#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped}
{#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped + waitingText}
<span in:fade={{ duration: 150 }}>
{#if status == 'error'}
Error occurred
@@ -180,9 +183,11 @@
Waiting to be resumed
{:else if isScheduled}
(not started)
{:else if waitingText}
{waitingText}
{:else if showStepId}
{stepId
? `${isCanceled ? 'Canceled at' : 'Running'} step ${stepId}`
? `${isCanceled ? 'Canceled at' : 'Running'} step '${stepId}'`
: `${isCanceled ? 'Canceled' : ''}`}
{:else if hideStepTitle}
{isCanceled ? 'Canceled' : 'Running'}
@@ -52,6 +52,12 @@
displayPersistentScriptDefinition?: boolean
openPersistentScriptDrawer?: () => void
concurrencyKey?: string
/** When the job was first due, if its concurrency limit held it back. */
concurrencyDeferredFrom?: string
/** When its concurrency limit let in the job it had held back. */
concurrencyReleasedAt?: string
/** Why the step the flow is at has not started. */
stepWaiting?: 'sleep' | 'concurrency'
compact?: boolean
extraCompact?: boolean
onFilterByConcurrencyKey?: (key: string) => void
@@ -67,6 +73,9 @@
displayPersistentScriptDefinition = false,
openPersistentScriptDrawer,
concurrencyKey,
concurrencyDeferredFrom,
concurrencyReleasedAt,
stepWaiting,
compact = false,
extraCompact = false,
onFilterByConcurrencyKey,
@@ -75,6 +84,8 @@
onResolutionChanged
}: Props = $props()
let heldByConcurrency = $derived(!!concurrencyDeferredFrom && !concurrencyReleasedAt)
let togglingResolution = $state(false)
let resolutionNote = $state('')
@@ -386,7 +397,7 @@
<div class="flex flex-row flex-wrap justify-between items-center gap-x-4 py-2 px-3">
<div class="flex flex-row flex-wrap gap-2 items-center flex-1">
{#if job}
<JobStatus {job} />
<JobStatus {job} {heldByConcurrency} {stepWaiting} />
<div class="flex items-baseline gap-1 text-xs">
<span class="text-secondary flex-shrink-0">Job ID</span>
<span class="text-primary">
@@ -473,7 +484,7 @@
<div class="flex flex-wrap items-center gap-3 min-w-0 grow">
<!-- Status icon -->
<div class="flex-shrink-0">
<JobStatusIcon {job} roundedFull />
<JobStatusIcon {job} roundedFull {heldByConcurrency} {stepWaiting} />
</div>
<!-- Two-row section: title on top, badges on bottom -->
@@ -511,13 +522,15 @@
<!-- Job Status -->
<div class="flex items-baseline flex-wrap gap-x-2 gap-y-1">
<JobStatus {job} />
<JobStatus {job} {heldByConcurrency} {stepWaiting} />
<RunBadges
{job}
{displayPersistentScriptDefinition}
{openPersistentScriptDrawer}
{concurrencyKey}
{concurrencyDeferredFrom}
{concurrencyReleasedAt}
{onFilterByConcurrencyKey}
showScriptHash={showScriptHashInBadges}
large={false}
@@ -1,5 +1,6 @@
<script lang="ts">
import { ConcurrencyGroupsService, type Job, type WorkflowStatus } from '../../gen'
import { type Job, type WorkflowStatus } from '../../gen'
import { useConcurrencyKeyStatus } from './useConcurrencyKeyStatus.svelte'
import JobLoader from '../JobLoader.svelte'
import DisplayResult from '../DisplayResult.svelte'
import JobArgs from '../JobArgs.svelte'
@@ -34,12 +35,7 @@
let loadError: string | undefined = $state(undefined)
let isLoadingJobDetails: boolean = $state(false)
let lastJobId: string | undefined = $state(undefined)
let concurrencyKey: string | undefined = $state(undefined)
async function getConcurrencyKey(job: Job) {
lastJobId = job.id
concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id })
}
const concurrency = useConcurrencyKeyStatus(() => job)
let viewTab = $state('logs')
@@ -99,10 +95,6 @@
}
})
$effect(() => {
job?.id && lastJobId !== job.id && untrack(() => job && getConcurrencyKey(job))
})
let jobLoader: JobLoader | undefined = $state(undefined)
// Set all tabs content to the same height to prevent layout jumps
@@ -153,7 +145,9 @@
<JobDetailHeader
{job}
compact
{concurrencyKey}
concurrencyKey={concurrency.key}
concurrencyDeferredFrom={concurrency.deferredFrom}
concurrencyReleasedAt={concurrency.releasedAt}
onFilterByConcurrencyKey={handleFilterByConcurrencyKey}
onFilterByWorker={handleFilterByWorker}
{onResolutionChanged}
@@ -6,7 +6,9 @@
Calendar,
Check,
FastForward,
Gauge,
Hourglass,
Moon,
Play,
ShieldQuestion,
Wrench,
@@ -19,9 +21,19 @@
job: Job
isExternal?: boolean
roundedFull?: boolean
/** Its concurrency limit holds the job back. */
heldByConcurrency?: boolean
/** Why the step the flow is at has not started. */
stepWaiting?: 'sleep' | 'concurrency'
}
let { job, isExternal = false, roundedFull = false }: Props = $props()
let {
job,
isExternal = false,
roundedFull = false,
heldByConcurrency = false,
stepWaiting
}: Props = $props()
</script>
<div class="flex items-center justify-start">
@@ -65,10 +77,32 @@
<Badge color="violet" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'} title="Suspended">
<Hourglass size={14} />
</Badge>
{:else if 'running' in job && job.running && stepWaiting === 'sleep'}
<Badge {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'} title="Sleeping">
<Moon size={14} />
</Badge>
{:else if 'running' in job && job.running && stepWaiting === 'concurrency'}
<Badge
color="orange"
{roundedFull}
baseClass={roundedFull ? '' : '!px-1.5'}
title="Step held by concurrency limit"
>
<Gauge size={14} />
</Badge>
{:else if 'running' in job && job.running}
<Badge color="yellow" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'}>
<Play size={14} />
</Badge>
{:else if 'running' in job && heldByConcurrency}
<Badge
color="orange"
{roundedFull}
baseClass={roundedFull ? '' : '!px-1.5'}
title="Held by concurrency limit"
>
<Gauge size={14} />
</Badge>
{:else if job && 'running' in job && job.scheduled_for && forLater(job.scheduled_for)}
<Badge color="blue" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'}>
<Calendar size={14} />
@@ -1,11 +1,11 @@
<script lang="ts">
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
import PreprocessedArgsDisplay from '$lib/components/runs/PreprocessedArgsDisplay.svelte'
import { getJobKindDisplayLabel, truncateHash } from '$lib/utils'
import { getJobKindDisplayLabel, msToCompactDuration, truncateHash } from '$lib/utils'
import { truncateRev } from '$lib/utils'
import Badge from '$lib/components/common/badge/Badge.svelte'
import Button from '$lib/components/common/button/Button.svelte'
import { ListFilter, Tag } from 'lucide-svelte'
import { AlertTriangle, ListFilter, Tag } from 'lucide-svelte'
import type { Job } from '$lib/gen'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { userWorkspaces } from '$lib/stores'
@@ -24,6 +24,10 @@
displayPersistentScriptDefinition?: boolean
openPersistentScriptDrawer?: () => void
concurrencyKey?: string
/** When the job was first due, if its concurrency limit held it back. */
concurrencyDeferredFrom?: string
/** When its concurrency limit let in the job it had held back. */
concurrencyReleasedAt?: string
showScriptHash?: boolean
onFilterByConcurrencyKey?: (key: string) => void
large?: boolean
@@ -34,10 +38,52 @@
displayPersistentScriptDefinition,
openPersistentScriptDrawer,
concurrencyKey,
concurrencyDeferredFrom,
concurrencyReleasedAt,
showScriptHash = true,
onFilterByConcurrencyKey,
large = false
}: Props = $props()
// From when the limit first held the job to when it let it in, counting live while it holds
// it; the rest until it started is queue time. A job let in before the end of the hold was
// recorded shows nothing.
// A job canceled while held completes without ever being let in: it is not held any more.
let heldNow = $derived(
job.type === 'QueuedJob' &&
!!concurrencyDeferredFrom &&
!concurrencyReleasedAt &&
!job.started_at
)
let now = $state(Date.now())
$effect(() => {
if (!heldNow) return
const id = setInterval(() => (now = Date.now()), 1000)
return () => clearInterval(id)
})
let heldMs = $derived(
concurrencyDeferredFrom && (concurrencyReleasedAt || heldNow)
? (concurrencyReleasedAt ? new Date(concurrencyReleasedAt).getTime() : now) -
new Date(concurrencyDeferredFrom).getTime()
: undefined
)
let queuedAfterMs = $derived(
concurrencyReleasedAt && job.started_at
? Math.max(new Date(job.started_at).getTime() - new Date(concurrencyReleasedAt).getTime(), 0)
: undefined
)
// The steps of the wait-time warning on the status badge.
let heldColor = $derived(
heldMs == undefined
? ''
: heldMs > 300_000
? 'text-red-500'
: heldMs > 30_000
? 'text-orange-500'
: heldMs > 5_000
? 'text-yellow-500'
: 'text-gray-400'
)
</script>
{#if job.script_hash && showScriptHash && job.job_kind !== 'aiagent'}
@@ -110,10 +156,23 @@
</div>
{/each}
{/if}
{#snippet held()}
{#if heldMs != undefined && heldMs > 0}
<span class="ml-1 inline-flex items-center gap-0.5 {heldColor}">
<AlertTriangle size={10} />{msToCompactDuration(heldMs, 0)}
</span>
{/if}
{/snippet}
{#if concurrencyKey}
<div>
<Tooltip>
{#snippet text()}
{#if heldMs != undefined}
Held by its concurrency limit for {msToCompactDuration(heldMs, 0)}{queuedAfterMs
? `, then queued ${msToCompactDuration(queuedAfterMs, 0)}`
: ''}.
{/if}
This job has concurrency limits enabled with the key:
{#if onFilterByConcurrencyKey}
<Button
@@ -133,11 +192,11 @@
{/snippet}
{#if onFilterByConcurrencyKey}
<button onclick={() => onFilterByConcurrencyKey?.(concurrencyKey)}>
<Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge>
<Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}{@render held()}</Badge>
</button>
{:else}
<a href={`/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`}>
<Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge>
<Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}{@render held()}</Badge>
</a>
{/if}
</Tooltip>
@@ -6,7 +6,6 @@
type Script,
type WorkflowStatus,
type NewScript,
ConcurrencyGroupsService,
MetricsService,
WorkerService,
type ScriptArgs
@@ -74,6 +73,7 @@
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte'
import JobDetailHeader from '$lib/components/runs/JobDetailHeader.svelte'
import { useConcurrencyKeyStatus } from '$lib/components/runs/useConcurrencyKeyStatus.svelte'
import ScriptRetryChain from '$lib/components/runs/ScriptRetryChain.svelte'
import FlowApprovals from '$lib/components/runs/FlowApprovals.svelte'
import JobArgs from '$lib/components/JobArgs.svelte'
@@ -270,20 +270,13 @@
(localStorage.getItem('hideExplicitProgressTip') ?? 'false') == 'false'
)
let lastJobId: string | undefined = $state(undefined)
let concurrencyKey: string | undefined = $state(undefined)
const concurrency = useConcurrencyKeyStatus(() => job)
setContext(
'FlowGraphAssetContext',
initFlowGraphAssetsCtx({ getModules: () => job?.raw_flow?.modules ?? [] })
)
async function getConcurrencyKey(job: Job | undefined) {
if (!job) return
lastJobId = job.id
concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id })
}
// Share read link: if the URL carries a `view_token`, install it so every job
// read on this page (incl. flow steps, args, logs, SSE) is authorized by it.
// Set eagerly at init (before JobLoader mounts and fires its first fetch), and
@@ -710,9 +703,6 @@
return openEditInFork(kind, itemPath, workspaceId)
}
$effect(() => {
job?.id && lastJobId !== job.id && untrack(() => getConcurrencyKey(job))
})
$effect(() => {
workspaceId && runId && untrack(() => onRunsPageChange())
})
@@ -1432,7 +1422,14 @@
openPersistentScriptDrawer={() => {
persistentScriptDrawer?.open?.(persistentScriptDefinition)
}}
{concurrencyKey}
concurrencyKey={concurrency.key}
concurrencyDeferredFrom={concurrency.deferredFrom}
concurrencyReleasedAt={concurrency.releasedAt}
stepWaiting={job.type === 'QueuedJob'
? Object.values(graphModuleStates).find(
(s) => s.type === 'WaitingForExecutor' && s.waiting_reason
)?.waiting_reason
: undefined}
/>
{/if}
</div>
@@ -1455,6 +1452,7 @@
textPosition="bottom"
slim
showStepId
stepStates={graphModuleStates}
waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0}
>
{#snippet errorAction()}
@@ -0,0 +1,67 @@
import { ConcurrencyGroupsService, type Job } from '$lib/gen'
import { getDbClockNow } from '$lib/forLater'
/** A job's concurrency key and, if its limit held it back, when it was first due and when it was
* let in. */
export function useConcurrencyKeyStatus(getJob: () => Job | undefined) {
type Status = { key: string; deferred_from?: string | null; released_at?: string | null } | null
let loaded = $state<{ jobId: string; status: Status } | undefined>(undefined)
let id = $derived(getJob()?.id)
let phase = $derived.by(() => {
const job = getJob()
return job?.type === 'CompletedJob' ? 'done' : job?.['running'] ? 'running' : 'waiting'
})
let scheduledFor = $derived(getJob()?.['scheduled_for'] as string | undefined)
// Live updates do not carry a job's due time, so a limit holding it back is only seen by
// asking: once per phase (waiting, running, done), and every 5s while it waits once due.
$effect(() => {
const jobId = id
const waiting = phase === 'waiting'
const dueIn = scheduledFor ? new Date(scheduledFor).getTime() - getDbClockNow().getTime() : 0
if (!jobId) return
let current = true
let stopped = false
let timer: ReturnType<typeof setTimeout> | undefined = undefined
const stop = () => {
stopped = true
clearTimeout(timer)
}
const load = () =>
ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: jobId })
.then((status) => {
if (!current) return
loaded = { jobId, status }
// The key is written as the job is queued: none means it has no limit.
if (!status) stop()
})
.catch(stop)
const poll = () => {
if (stopped) return
load()
timer = setTimeout(poll, 5000)
}
load()
// setTimeout fires at once past 2^31 - 1 ms.
if (waiting) timer = setTimeout(poll, Math.min(Math.max(dueIn, 5000), 2 ** 31 - 1))
return () => {
current = false
stop()
}
})
let status = $derived(loaded?.jobId === id ? loaded?.status : undefined)
return {
get key() {
return status?.key
},
get deferredFrom() {
return status?.deferred_from ?? undefined
},
get releasedAt() {
return status?.released_at ?? undefined
}
}
}