Skip to content

A platform for community discussion. Free, open, simple.

UX: Stream workflow execution progress (#41963)

Samfa61f4c7a32d
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs
index bb91ed3815b..1a20d2aaff4 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs
@@ -7,14 +7,22 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import DButton from "discourse/ui-kit/d-button";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";
import { i18n } from "discourse-i18n";
+import {
+ ExecutionProgressStream,
+ formatDuration,
+ isRunning,
+} from "../../../lib/workflows/execution-progress";
import AdminTable from "../admin-table";
import EmptyState from "../empty-state";
+const EXECUTIONS_CHANNEL = "/discourse-workflows/executions";
+
const STATUS_ICONS = {
+ pending: "clock",
success: "circle-check",
error: "circle-xmark",
- running: "spinner",
waiting: "clock",
};
@@ -29,17 +37,24 @@ function formatTime(timestamp) {
return new Date(timestamp).toLocaleString();
}
-function runTime(execution) {
- const ms = execution.run_time_ms;
- if (ms == null) {
+function runTime(execution, currentTime) {
+ if (isRunning(execution)) {
+ return formatDuration(execution.started_at, null, currentTime);
+ }
+
+ const milliseconds = execution.run_time_ms;
+ if (milliseconds == null) {
return "—";
}
- return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
+ return milliseconds < 1000
+ ? `${milliseconds}ms`
+ : `${(milliseconds / 1000).toFixed(1)}s`;
}
export default class ExecutionsManager extends Component {
@service currentUser;
@service dialog;
+ @service messageBus;
@service router;
@tracked executions = null;
@@ -47,21 +62,103 @@ export default class ExecutionsManager extends Component {
@tracked loadingMore = false;
@tracked bulkMode = false;
+ #loadMoreToken = 0;
+ #loading = false;
+ #progress;
+
constructor() {
super(...arguments);
+ this.#progress = new ExecutionProgressStream(this.messageBus, {
+ onMessage: (message) => this.#applyProgress(message),
+ onGap: () => this.loadExecutions(),
+ onRetry: () => this.loadExecutions(),
+ });
this.loadExecutions();
}
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#progress.destroy();
+ }
+
+ get currentTime() {
+ return this.#progress.currentTime;
+ }
+
async loadExecutions() {
+ if (this.#loading) {
+ return;
+ }
+
+ this.#loading = true;
+ this.#loadMoreToken++;
+ this.#progress.unsubscribe();
+
try {
const url = this.args.workflowId
? `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/executions.json`
: "/admin/plugins/discourse-workflows/executions.json";
const result = await ajax(url);
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
this.executions = result.executions;
this.loadMoreUrl = result.meta?.load_more_executions;
- } catch (e) {
- popupAjaxError(e);
+ this.#progress.resetRetry();
+ this.#progress.lastMessageId = result.meta?.message_bus_last_id ?? 0;
+ this.#progress.subscribe(EXECUTIONS_CHANNEL);
+ this.#syncTimer();
+ } catch (error) {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.#progress.scheduleRetry(error);
+ }
+ } finally {
+ this.#loading = false;
+ }
+ }
+
+ #applyProgress(message) {
+ if (!this.executions) {
+ this.loadExecutions();
+ return;
+ }
+
+ if (
+ !["execution_created", "execution_update"].includes(message.type) ||
+ !message.execution
+ ) {
+ return;
+ }
+
+ const update = message.execution;
+ if (
+ this.args.workflowId &&
+ update.workflow_id !== Number(this.args.workflowId)
+ ) {
+ return;
+ }
+
+ const current = this.executions.find(
+ (execution) => execution.id === update.id
+ );
+ if (current) {
+ this.executions = this.executions.map((execution) =>
+ execution.id === update.id ? { ...execution, ...update } : execution
+ );
+ } else if (message.type === "execution_created") {
+ this.executions = [...this.executions, update].sort(
+ (left, right) => right.id - left.id
+ );
+ }
+ this.#syncTimer();
+ }
+
+ #syncTimer() {
+ if ((this.executions || []).some(isRunning)) {
+ this.#progress.startTicker();
+ } else {
+ this.#progress.stopTicker();
}
}
@@ -76,14 +173,36 @@ export default class ExecutionsManager extends Component {
}
this.loadingMore = true;
+ const loadMoreToken = ++this.#loadMoreToken;
try {
const result = await ajax(this.loadMoreUrl);
- this.executions = [...this.executions, ...result.executions];
+ if (
+ this.isDestroying ||
+ this.isDestroyed ||
+ loadMoreToken !== this.#loadMoreToken
+ ) {
+ return;
+ }
+
+ const existingIds = new Set(
+ this.executions.map((execution) => execution.id)
+ );
+ this.executions = [
+ ...this.executions,
+ ...result.executions.filter(
+ (execution) => !existingIds.has(execution.id)
+ ),
+ ];
this.loadMoreUrl = result.meta?.load_more_executions;
+ this.#syncTimer();
} catch (e) {
- popupAjaxError(e);
+ if (!this.isDestroying && !this.isDestroyed) {
+ popupAjaxError(e);
+ }
} finally {
- this.loadingMore = false;
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.loadingMore = false;
+ }
}
}
@@ -217,7 +336,11 @@ export default class ExecutionsManager extends Component {
<span
class="workflows-executions-manager__status --{{execution.status}}"
>
- {{dIcon (statusIcon execution.status)}}
+ {{#if (isRunning execution)}}
+ {{dLoadingSpinner size="small"}}
+ {{else}}
+ {{dIcon (statusIcon execution.status)}}
+ {{/if}}
{{i18n
(concat
"discourse_workflows.executions.statuses." execution.status
@@ -238,7 +361,11 @@ export default class ExecutionsManager extends Component {
<span
class="workflows-executions-manager__status --{{execution.status}}"
>
- {{dIcon (statusIcon execution.status)}}
+ {{#if (isRunning execution)}}
+ {{dLoadingSpinner size="small"}}
+ {{else}}
+ {{dIcon (statusIcon execution.status)}}
+ {{/if}}
{{i18n
(concat
"discourse_workflows.executions.statuses." execution.status
@@ -253,11 +380,13 @@ export default class ExecutionsManager extends Component {
{{formatTime execution.started_at}}
</td>
{{/if}}
- <td class="d-table__cell --detail">
+ <td
+ class="d-table__cell --detail workflows-executions-manager__run-time"
+ >
<div class="d-table__mobile-label">
{{i18n "discourse_workflows.executions.run_time"}}
</div>
- {{runTime execution}}
+ {{runTime execution this.currentTime}}
</td>
<td class="d-table__cell --controls">
<div class="d-table__cell-actions">
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs
index 5105f3c8fb8..e564da76e96 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs
@@ -1,12 +1,23 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
import { array, concat } from "@ember/helper";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
import DButton from "discourse/ui-kit/d-button";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";
import { i18n } from "discourse-i18n";
+import {
+ ExecutionProgressStream,
+ formatDuration,
+ isLive,
+ isPending,
+ isRunning,
+} from "../../../lib/workflows/execution-progress";
import {
localeKeyPart,
propertyOptionLabel,
@@ -113,12 +124,12 @@ function itemCount(data) {
: null;
}
-function formatDuration(startedAt, finishedAt) {
- if (!startedAt || !finishedAt) {
- return "—";
- }
- const ms = new Date(finishedAt) - new Date(startedAt);
- return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
+function stepDuration(step, currentTime) {
+ return formatDuration(
+ step.started_at,
+ step.finished_at,
+ step.status === "running" ? currentTime : null
+ );
}
function formatValue(value) {
@@ -198,8 +209,11 @@ function conditionPassed(step) {
}
export default class ExecutionDetail extends Component {
+ @service messageBus;
@service workflowsNodeTypes;
+ @tracked liveExecution;
+
operationLabel = (step) => {
const value = step?.metadata?.operation;
if (!value) {
@@ -219,14 +233,187 @@ export default class ExecutionDetail extends Component {
return propertyOptionLabel(definition, "operation", { value });
};
+ #progress;
+
+ #refreshing = false;
+
+ #refreshRequested = false;
+
+ #refreshToken = 0;
+
+ constructor() {
+ super(...arguments);
+ this.#progress = new ExecutionProgressStream(this.messageBus, {
+ onMessage: (message) => this.#applyProgress(message),
+ onGap: () => this.#resyncExecution(),
+ onRetry: () => this.#refreshExecution(),
+ });
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#refreshToken++;
+ this.#progress.destroy();
+ }
+
+ get currentTime() {
+ return this.#progress.currentTime;
+ }
+
+ get execution() {
+ return this.liveExecution?.id === this.args.execution.id
+ ? this.liveExecution
+ : this.args.execution;
+ }
+
+ set execution(value) {
+ this.liveExecution = value;
+ }
+
+ get isPending() {
+ return isPending(this.execution);
+ }
+
+ get isRunning() {
+ return isRunning(this.execution);
+ }
+
+ get isActive() {
+ return this.isPending || this.isRunning;
+ }
+
+ get isLive() {
+ return isLive(this.execution);
+ }
+
@action
- async ensureNodeTypes() {
+ async initialize() {
+ this.#progress.lastMessageId = this.execution.message_bus_last_id ?? 0;
+ this.#syncLiveUpdates();
await this.workflowsNodeTypes.load();
}
+ @action
+ executionChanged() {
+ this.#refreshToken++;
+ this.#refreshing = false;
+ this.#refreshRequested = false;
+ this.#progress.resetRetry();
+ this.liveExecution = null;
+ this.#progress.unsubscribe();
+ this.#progress.lastMessageId = this.execution.message_bus_last_id ?? 0;
+ this.#syncLiveUpdates();
+ }
+
+ #syncLiveUpdates() {
+ if (this.isLive) {
+ this.#progress.subscribe(
+ `/discourse-workflows/execution/${this.execution.id}`
+ );
+ } else {
+ this.#progress.unsubscribe();
+ }
+
+ if (this.isRunning) {
+ this.#progress.startTicker();
+ } else {
+ this.#progress.stopTicker();
+ }
+ }
+
+ #applyProgress(message) {
+ if (
+ message.type !== "execution_progress" ||
+ message.execution?.id !== this.execution.id
+ ) {
+ return;
+ }
+
+ if (this.#refreshing && message.refresh) {
+ this.#refreshRequested = true;
+ }
+
+ const steps = [...(this.execution.steps || [])];
+ if (message.step) {
+ const index = steps.findIndex(
+ (step) => step.position === message.step.position
+ );
+ if (index === -1) {
+ steps.push(message.step);
+ } else {
+ steps[index] = { ...steps[index], ...message.step };
+ }
+ }
+
+ this.execution = {
+ ...this.execution,
+ ...message.execution,
+ steps,
+ };
+
+ if (message.refresh) {
+ this.#refreshExecution();
+ } else {
+ this.#syncLiveUpdates();
+ }
+ }
+
+ #resyncExecution() {
+ this.#progress.unsubscribe();
+ this.#refreshExecution();
+ }
+
+ async #refreshExecution() {
+ if (this.#refreshing) {
+ this.#refreshRequested = true;
+ return;
+ }
+
+ const executionId = this.execution.id;
+ const refreshToken = ++this.#refreshToken;
+ this.#refreshing = true;
+ try {
+ const result = await ajax(
+ `/admin/plugins/discourse-workflows/executions/${executionId}`
+ );
+ if (
+ this.isDestroying ||
+ this.isDestroyed ||
+ refreshToken !== this.#refreshToken ||
+ executionId !== this.execution.id
+ ) {
+ return;
+ }
+
+ this.execution = {
+ ...result.execution,
+ message_bus_last_id: result.meta?.message_bus_last_id ?? 0,
+ };
+ this.#progress.lastMessageId = this.execution.message_bus_last_id;
+ this.#progress.resetRetry();
+ this.#syncLiveUpdates();
+ } catch (error) {
+ if (
+ !this.isDestroying &&
+ !this.isDestroyed &&
+ refreshToken === this.#refreshToken
+ ) {
+ this.#progress.scheduleRetry(error);
+ }
+ } finally {
+ if (refreshToken === this.#refreshToken) {
+ this.#refreshing = false;
+ if (this.#refreshRequested && !this.isDestroying && !this.isDestroyed) {
+ this.#refreshRequested = false;
+ this.#refreshExecution();
+ }
+ }
+ }
+ }
+
@action
exportAsText() {
- const execution = this.args.execution;
+ const execution = this.execution;
const lines = [];
lines.push(`Workflow: ${execution.workflow_name ?? "Unknown"}`);
@@ -235,7 +422,11 @@ export default class ExecutionDetail extends Component {
lines.push(`Started: ${execution.started_at ?? "—"}`);
lines.push(`Finished: ${execution.finished_at ?? "—"}`);
lines.push(
- `Total time: ${formatDuration(execution.started_at, execution.finished_at)}`
+ `Total time: ${formatDuration(
+ execution.started_at,
+ execution.finished_at,
+ this.isRunning ? this.currentTime : null
+ )}`
);
if (execution.error) {
@@ -307,31 +498,59 @@ export default class ExecutionDetail extends Component {
}
<template>
- <div class="workflows-execution-detail" {{didInsert this.ensureNodeTypes}}>
- {{#if @execution.workflow_call_caller}}
+ <div
+ class="workflows-execution-detail"
+ {{didInsert this.initialize}}
+ {{didUpdate this.executionChanged @execution}}
+ >
+ {{#if this.isActive}}
+ <div class="workflows-execution-detail__progress">
+ {{#if this.isRunning}}
+ {{dLoadingSpinner size="small"}}
+ {{else}}
+ {{dIcon "clock"}}
+ {{/if}}
+ <span class="workflows-execution-detail__progress-label">
+ {{i18n
+ (concat
+ "discourse_workflows.executions.statuses." this.execution.status
+ )
+ }}
+ </span>
+ <span class="workflows-execution-detail__progress-time">
+ {{formatDuration
+ this.execution.started_at
+ this.execution.finished_at
+ this.currentTime
+ }}
+ </span>
+ </div>
+ {{/if}}
+
+ {{#if this.execution.workflow_call_caller}}
<div class="workflows-execution-detail__workflow-call --caller">
<div class="workflows-execution-detail__workflow-call-main">
<span class="workflows-execution-detail__workflow-call-label">
{{i18n "discourse_workflows.executions.workflow_call_called_by"}}
</span>
<span class="workflows-execution-detail__workflow-call-name">
- {{#if @execution.workflow_call_caller.workflow_name}}
- {{@execution.workflow_call_caller.workflow_name}}
+ {{#if this.execution.workflow_call_caller.workflow_name}}
+ {{this.execution.workflow_call_caller.workflow_name}}
{{else}}
{{i18n
"discourse_workflows.executions.workflow_call_workflow"
- [email protected]_call_caller.workflow_id
+ id=this.execution.workflow_call_caller.workflow_id
}}
{{/if}}
</span>
</div>
- {{#if @execution.workflow_call_caller.execution_url}}
+ {{#if this.execution.workflow_call_caller.execution_url}}
<DButton
@route="adminPlugins.show.discourse-workflows.show.executions.show"
@routeModels={{array
- @execution.workflow_call_caller.workflow_id
- @execution.workflow_call_caller.execution_id
+ this.execution.workflow_call_caller.workflow_id
+ this.execution.workflow_call_caller.execution_id
}}
@icon="up-right-from-square"
@label="discourse_workflows.executions.workflow_call_open_parent"
@@ -342,7 +561,7 @@ export default class ExecutionDetail extends Component {
{{/if}}
<div class="workflows-execution-detail__steps">
- {{#each @execution.steps as |step|}}
+ {{#each this.execution.steps as |step|}}
<div
class="workflows-execution-detail__step --{{step.status}}
--kind-{{nodeKind step.node_type}}"
@@ -397,7 +616,7 @@ export default class ExecutionDetail extends Component {
{{/if}}
</span>
<span class="workflows-execution-detail__step-time">
- {{formatDuration step.started_at step.finished_at}}
+ {{stepDuration step this.currentTime}}
{{#if step.metadata.js_elapsed_ms}}
<span
class="workflows-execution-detail__step-js-time"
@@ -566,7 +785,11 @@ export default class ExecutionDetail extends Component {
<div class="workflows-execution-detail__footer">
<div class="workflows-execution-detail__total">
{{i18n "discourse_workflows.executions.total_time"}}
- {{formatDuration @execution.started_at @execution.finished_at}}
+ {{formatDuration
+ this.execution.started_at
+ this.execution.finished_at
+ (if this.isRunning this.currentTime)
+ }}
</div>
<DButton
@action={{this.exportAsText}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/execution-progress.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/execution-progress.js
new file mode 100644
index 00000000000..1f9379312e0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/execution-progress.js
@@ -0,0 +1,159 @@
+import { tracked } from "@glimmer/tracking";
+import { cancel } from "@ember/runloop";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import discourseLater from "discourse/lib/later";
+
+const MAX_RETRIES = 3;
+const RETRY_BACKOFF_MS = 2000;
+const RETRY_COOLDOWN_MS = 10_000;
+const TICKER_INTERVAL_MS = 1000;
+
+export function isPending(execution) {
+ return execution.status === "pending";
+}
+
+export function isRunning(execution) {
+ return execution.status === "running";
+}
+
+export function isLive(execution) {
+ return (
+ isPending(execution) ||
+ isRunning(execution) ||
+ execution.status === "waiting"
+ );
+}
+
+export function formatDuration(startedAt, finishedAt, currentTime) {
+ if (!startedAt || (!finishedAt && !currentTime)) {
+ return "—";
+ }
+
+ const end = finishedAt ? new Date(finishedAt) : currentTime;
+ const milliseconds = Math.max(0, end - new Date(startedAt));
+
+ if (!finishedAt && currentTime) {
+ return `${Math.floor(milliseconds / 1000)}s`;
+ }
+
+ return milliseconds < 1000
+ ? `${milliseconds}ms`
+ : `${(milliseconds / 1000).toFixed(1)}s`;
+}
+
+export class ExecutionProgressStream {
+ @tracked currentTime = Date.now();
+
+ #channel = null;
+ #lastMessageId = 0;
+ #messageBus;
+ #messageHandler = null;
+ #onGap;
+ #onMessage;
+ #onRetry;
+ #retryCount = 0;
+ #retryTimer = null;
+ #ticker = null;
+
+ constructor(messageBus, { onMessage, onGap, onRetry }) {
+ this.#messageBus = messageBus;
+ this.#onMessage = onMessage;
+ this.#onGap = onGap;
+ this.#onRetry = onRetry;
+ }
+
+ set lastMessageId(value) {
+ this.#lastMessageId = value;
+ }
+
+ subscribe(channel) {
+ if (this.#channel) {
+ return;
+ }
+
+ this.#channel = channel;
+ this.#messageHandler = (message, _globalId, messageId) =>
+ this.#deliver(message, messageId);
+ this.#messageBus.subscribe(
+ channel,
+ this.#messageHandler,
+ this.#lastMessageId
+ );
+ }
+
+ unsubscribe() {
+ if (!this.#channel) {
+ return;
+ }
+
+ this.#messageBus.unsubscribe(this.#channel, this.#messageHandler);
+ this.#channel = null;
+ this.#messageHandler = null;
+ }
+
+ scheduleRetry(error) {
+ if (this.#retryTimer !== null) {
+ return;
+ }
+
+ if (this.#retryCount >= MAX_RETRIES) {
+ this.#retryCount = 0;
+ popupAjaxError(error);
+ this.#retryTimer = discourseLater(
+ () => this.#runRetry(),
+ RETRY_COOLDOWN_MS
+ );
+ return;
+ }
+
+ this.#retryCount += 1;
+ this.#retryTimer = discourseLater(
+ () => this.#runRetry(),
+ RETRY_BACKOFF_MS * this.#retryCount
+ );
+ }
+
+ resetRetry() {
+ this.#retryCount = 0;
+ if (this.#retryTimer !== null) {
+ cancel(this.#retryTimer);
+ this.#retryTimer = null;
+ }
+ }
+
+ startTicker() {
+ this.currentTime = Date.now();
+ this.#ticker ||= window.setInterval(() => {
+ this.currentTime = Date.now();
+ }, TICKER_INTERVAL_MS);
+ }
+
+ stopTicker() {
+ if (this.#ticker) {
+ window.clearInterval(this.#ticker);
+ this.#ticker = null;
+ }
+ }
+
+ destroy() {
+ this.unsubscribe();
+ this.stopTicker();
+ this.resetRetry();
+ }
+
+ #deliver(message, messageId) {
+ if (messageId !== this.#lastMessageId + 1) {
+ this.#onGap();
+ return;
+ }
+
+ this.#lastMessageId = messageId;
+ this.resetRetry();
+ this.#onMessage(message);
+ }
+
+ #runRetry() {
+ this.#retryTimer = null;
+ this.#onRetry();
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js
index e9acd941ce3..d6f5bad6274 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js
@@ -6,6 +6,9 @@ export default class DiscourseWorkflowsShowExecutionsShowRoute extends Discourse
const result = await ajax(
`/admin/plugins/discourse-workflows/executions/${params.execution_id}`
);
- return result.execution;
+ return {
+ ...result.execution,
+ message_bus_last_id: result.meta?.message_bus_last_id ?? 0,
+ };
}
}
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb
index b87d6120587..d5758bfba87 100644
--- a/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb
@@ -25,12 +25,18 @@ module DiscourseWorkflows
end
def index
+ message_bus_last_id =
+ MessageBus.last_id(DiscourseWorkflows::ExecutionProgressPublisher::EXECUTIONS_CHANNEL)
+
DiscourseWorkflows::Execution::List.call(service_params) do |result|
on_success do |executions:, load_more_url:|
render json: {
executions:
serialize_data(executions, DiscourseWorkflows::ExecutionListSerializer),
- meta: { load_more_executions: load_more_url }.compact,
+ meta: {
+ load_more_executions: load_more_url,
+ message_bus_last_id: message_bus_last_id,
+ }.compact,
}
end
on_failure { render(json: failed_json, status: :unprocessable_entity) }
@@ -49,11 +55,24 @@ module DiscourseWorkflows
end
def show
+ channel = DiscourseWorkflows::ExecutionProgressPublisher.execution_channel(params[:id])
+ message_bus_last_id = MessageBus.last_id(channel)
+
DiscourseWorkflows::Execution::Show.call(
service_params.deep_merge(params: { execution_id: params[:id] }),
) do |result|
on_success do |execution:|
- render_serialized(execution, DiscourseWorkflows::ExecutionSerializer, root: "execution")
+ render json: {
+ execution:
+ serialize_data(
+ execution,
+ DiscourseWorkflows::ExecutionSerializer,
+ root: false,
+ ),
+ meta: {
+ message_bus_last_id: message_bus_last_id,
+ },
+ }
end
on_failure { render(json: failed_json, status: :unprocessable_entity) }
on_model_not_found(:execution) { raise Discourse::NotFound }
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
index e0be6f70113..3128a5079b8 100644
--- a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
@@ -12,6 +12,7 @@ module Jobs
if !SiteSetting.enable_discourse_workflows
execution.update!(status: :skipped, finished_at: Time.current)
+ ::DiscourseWorkflows::ExecutionProgressPublisher.publish(execution, refresh: true)
return
end
@@ -49,6 +50,7 @@ module Jobs
error: "Workflow snapshot missing",
finished_at: Time.current,
)
+ ::DiscourseWorkflows::ExecutionProgressPublisher.publish(execution, refresh: true)
return
end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
index ee791ee2084..bb6f4c8f4e6 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
@@ -53,6 +53,8 @@ module DiscourseWorkflows
workflow_data: WorkflowSnapshot.from_workflow(workflow, published: false).to_h,
)
end
+ end.tap do |execution|
+ ExecutionProgressPublisher.publish_created(execution, workflow_name: workflow.name)
end
end
@@ -80,6 +82,8 @@ module DiscourseWorkflows
},
)
end
+ end.tap do |execution|
+ ExecutionProgressPublisher.publish_created(execution, workflow_name: workflow.name)
end
end
@@ -114,6 +118,7 @@ module DiscourseWorkflows
execution.status = :running
execution.updated_at = now
+ ExecutionProgressPublisher.publish(execution)
execution
end
@@ -130,6 +135,7 @@ module DiscourseWorkflows
execution.status = :running
execution.started_at = now
execution.updated_at = now
+ ExecutionProgressPublisher.publish(execution)
execution
end
@@ -188,7 +194,11 @@ module DiscourseWorkflows
)
end
- DiscourseWorkflows::WorkflowCallContinuation.child_failed!(reload) if claimed
+ if claimed
+ reload
+ DiscourseWorkflows::ExecutionProgressPublisher.publish(self, refresh: true)
+ DiscourseWorkflows::WorkflowCallContinuation.child_failed!(self)
+ end
claimed
end
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
index cc17e4b728b..b4af59ee035 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
@@ -1,4 +1,25 @@
.workflows-execution-detail {
+ &__progress {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin-bottom: var(--space-3);
+ padding: var(--space-2) var(--space-3);
+ border: 1px solid var(--workflow-status-running);
+ border-radius: 0.375em;
+ background: var(--workflow-status-running-low);
+ color: var(--workflow-status-running);
+ }
+
+ &__progress-label {
+ font-weight: bold;
+ }
+
+ &__progress-time {
+ margin-inline-start: auto;
+ font-variant-numeric: tabular-nums;
+ }
+
&__step {
border: 1.5px solid var(--primary-low);
border-radius: 0.375em;
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss
index dfd00a27891..6edfb8640bb 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss
@@ -4,10 +4,15 @@
align-items: center;
gap: var(--space-2);
- .d-icon {
+ .d-icon,
+ .spinner {
font-size: var(--font-up-1);
}
+ .spinner {
+ margin: 0;
+ }
+
&.--success .d-icon {
color: var(--workflow-status-success);
}
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb b/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb
new file mode 100644
index 00000000000..4b73f86b1ad
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/execution_progress_publisher.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExecutionProgressPublisher
+ EXECUTIONS_CHANNEL = "/discourse-workflows/executions"
+ MAX_BACKLOG_AGE = 1.hour.to_i
+ MAX_BACKLOG_SIZE = 100
+
+ STEP_FIELDS = %w[
+ node_id
+ node_name
+ node_type
+ position
+ status
+ error
+ started_at
+ finished_at
+ ].freeze
+
+ def self.execution_channel(execution_id)
+ "/discourse-workflows/execution/#{execution_id}"
+ end
+
+ def self.publish_created(execution, workflow_name:)
+ MessageBus.publish(
+ EXECUTIONS_CHANNEL,
+ {
+ type: "execution_created",
+ execution: execution_summary(execution, workflow_name: workflow_name),
+ },
+ **publish_options,
+ )
+ end
+
+ def self.publish(execution, step: nil, refresh: false)
+ payload = {
+ type: "execution_progress",
+ execution: execution_progress(execution),
+ refresh: refresh,
+ }
+ payload[:step] = step.to_h.slice(*STEP_FIELDS).merge("error" => step.error) if step
+
+ MessageBus.publish(execution_channel(execution.id), payload, **publish_options)
+ publish_list_update(execution) unless step
+ end
+
+ def self.publish_list_update(execution)
+ MessageBus.publish(
+ EXECUTIONS_CHANNEL,
+ {
+ type: "execution_update",
+ execution: execution_summary(execution).except(:workflow_name),
+ },
+ **publish_options,
+ )
+ end
+
+ def self.execution_progress(execution)
+ {
+ id: execution.id,
+ status: execution.status,
+ error: execution.error,
+ run_time_ms: execution.run_time_ms,
+ started_at: execution.started_at,
+ finished_at: execution.finished_at,
+ }
+ end
+ private_class_method :execution_progress
+
+ def self.execution_summary(execution, workflow_name: nil)
+ {
+ id: execution.id,
+ workflow_id: execution.workflow_id,
+ workflow_name: workflow_name,
+ status: execution.status,
+ error: execution.error,
+ run_time_ms: execution.run_time_ms,
+ started_at: execution.started_at,
+ finished_at: execution.finished_at,
+ created_at: execution.created_at,
+ }
+ end
+ private_class_method :execution_summary
+
+ def self.publish_options
+ {
+ group_ids: [Group::AUTO_GROUPS[:admins]],
+ max_backlog_age: MAX_BACKLOG_AGE,
+ max_backlog_size: MAX_BACKLOG_SIZE,
+ }
+ end
+ private_class_method :publish_options
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
index 87431f0d07d..3b8d20c82d1 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -173,6 +173,7 @@ module DiscourseWorkflows
step&.add_metadata("handled_error", error_metadata(error))
step&.succeed!(output: all_items)
step&.apply_updates!("error" => nil)
+ @store.publish_progress(step: step) if step
@context.store_node_output(waiting_node, all_items)
@context.store_node_run(
waiting_node,
@@ -184,6 +185,7 @@ module DiscourseWorkflows
route_downstream(waiting_node, handled_outputs)
else
step&.fail!(error.message)
+ @store.publish_progress(step: step) if step
raise error
end
end
@@ -221,6 +223,7 @@ module DiscourseWorkflows
step = record_step(node, [])
step.succeed!(output: output_groups.flatten(1))
step.add_metadata("cached", true)
+ @store.publish_progress(step: step)
route_downstream(node, output_groups)
end
@@ -431,6 +434,7 @@ module DiscourseWorkflows
js_elapsed = (sandbox_budget_tracker.current_elapsed_ms - js_elapsed_before).round(1)
step.add_metadata("js_elapsed_ms", js_elapsed) if js_elapsed > 0
runtime_state.step_metadata.each { |key, value| step.add_metadata(key, value) }
+ @store.publish_progress(step: step)
end
end
@@ -474,6 +478,7 @@ module DiscourseWorkflows
)
step = record_step(node, input_items)
step.skip!(output: input_items, reason: reason)
+ @store.publish_progress(step: step)
@context.store_node_output(node, input_items)
@context.store_node_run(node, inputs: [input_items], outputs: [input_items])
enqueue_downstream(node, 0, input_items)
@@ -483,6 +488,7 @@ module DiscourseWorkflows
reason = issues.map { |i| "#{i[:path]}: #{i[:message]}" }.join(", ")
step = record_step(node, input_items)
step.skip!(output: input_items, reason: reason)
+ @store.publish_progress(step: step)
@context.store_node_output(node, input_items)
@context.store_node_run(node, inputs: [input_items], outputs: [input_items])
enqueue_downstream(node, 0, input_items)
@@ -492,6 +498,7 @@ module DiscourseWorkflows
step = record_step(node, input_items)
step.succeed!(output: pinned_items)
step.add_metadata("pinned", true)
+ @store.publish_progress(step: step)
@context.store_node_output(node, pinned_items)
@context.store_node_run(
node,
@@ -902,6 +909,7 @@ module DiscourseWorkflows
error: error,
)
@steps << step
+ @store.publish_progress(step: step)
step
end
@@ -919,6 +927,7 @@ module DiscourseWorkflows
"output" => response_items,
"finished_at" => Time.current.iso8601,
)
+ @store.publish_progress(step: step)
end
def begin_wait!(wait_request)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
index ada16c2582f..9a2af9f55ce 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -61,6 +61,7 @@ module DiscourseWorkflows
timeout_action: nil,
)
publish_execution_run_data
+ publish_progress(refresh: true)
if @options.workflow_call_child?
DiscourseWorkflows::WorkflowCallContinuation.child_succeeded!(execution)
end
@@ -83,6 +84,7 @@ module DiscourseWorkflows
publish_execution_run_data(
force: @options.draft_execution || @options.workflow_snapshot.present?,
)
+ publish_progress(refresh: true)
if @options.workflow_call_child?
DiscourseWorkflows::WorkflowCallContinuation.child_failed!(execution)
end
@@ -107,6 +109,7 @@ module DiscourseWorkflows
)
save!(steps)
publish_waiting_form_notification(node)
+ publish_progress(refresh: true)
execution
end
@@ -120,6 +123,10 @@ module DiscourseWorkflows
)
end
+ def publish_progress(step: nil, refresh: false)
+ ExecutionProgressPublisher.publish(execution, step: step, refresh: refresh)
+ end
+
private
def create_execution!
@@ -128,6 +135,7 @@ module DiscourseWorkflows
def persist_execution!(status:, trigger_data:, finished_at: nil)
@execution = @options.existing_execution || DiscourseWorkflows::Execution.new
+ created = @execution.new_record?
@execution_context.execution = @execution if @options.existing_execution
@execution.update!(
workflow_id: workflow.id,
@@ -140,6 +148,9 @@ module DiscourseWorkflows
finished_at: finished_at,
)
attach_workflow_call_run!
+ if created
+ ExecutionProgressPublisher.publish_created(@execution, workflow_name: workflow.name)
+ end
@execution
end
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
index 5f8322a09b6..e0d55d07003 100644
--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
@@ -43,11 +43,17 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
},
)
- described_class.new.execute(execution_id: execution.id, user_id: admin.id)
+ messages =
+ MessageBus.track_publish(
+ DiscourseWorkflows::ExecutionProgressPublisher.execution_channel(execution.id),
+ ) { described_class.new.execute(execution_id: execution.id, user_id: admin.id) }
execution.reload
expect(execution.status).to eq("skipped")
expect(execution.finished_at).to be_present
+ expect(messages.one?).to eq(true)
+ expect(messages.first.data).to include(type: "execution_progress", refresh: true)
+ expect(messages.first.data[:execution]).to include(id: execution.id, status: "skipped")
end
it "leaves a non-pending execution untouched" do
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/execution_progress_publisher_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/execution_progress_publisher_spec.rb
new file mode 100644
index 00000000000..4dfba30506d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/execution_progress_publisher_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExecutionProgressPublisher do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ it "publishes compact admin-only updates to list and detail channels" do
+ execution = Fabricate(:discourse_workflows_execution, workflow: workflow)
+ secret = "private-input-#{SecureRandom.hex(8)}"
+ step =
+ DiscourseWorkflows::Executor::Step.build(
+ node: OpenStruct.new(id: "node-1", name: "Node", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [{ "json" => { "secret" => secret } }],
+ )
+
+ detail_messages =
+ MessageBus.track_publish(described_class.execution_channel(execution.id)) do
+ described_class.publish(execution, step: step)
+ end
+
+ detail_message = detail_messages.first
+ expect(detail_message.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(detail_message.data).to include(type: "execution_progress", refresh: false)
+ expect(detail_message.data[:step]).to include("node_id" => "node-1", "status" => "running")
+ expect(detail_message.data.to_json).not_to include(secret)
+
+ step_list_messages =
+ MessageBus.track_publish(described_class::EXECUTIONS_CHANNEL) do
+ described_class.publish(execution, step: step)
+ end
+ expect(step_list_messages).to be_empty
+
+ list_messages =
+ MessageBus.track_publish(described_class::EXECUTIONS_CHANNEL) do
+ described_class.publish(execution)
+ end
+ expect(list_messages.one?).to eq(true)
+ expect(list_messages.first.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(list_messages.first.data).to include(type: "execution_update")
+ expect(list_messages.first.data[:execution]).to include(
+ id: execution.id,
+ workflow_id: workflow.id,
+ status: "pending",
+ )
+ expect(list_messages.first.data[:execution]).not_to have_key(:workflow_name)
+ expect(list_messages.first.data[:execution]).not_to have_key(:trigger_data)
+
+ created_messages =
+ MessageBus.track_publish(described_class::EXECUTIONS_CHANNEL) do
+ described_class.publish_created(execution, workflow_name: workflow.name)
+ end
+ expect(created_messages.first.data).to include(type: "execution_created")
+ expect(created_messages.first.data[:execution]).to include(workflow_name: workflow.name)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
index 3283e6ad899..e785bce3e42 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
@@ -32,6 +32,51 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
end
end
+ describe "#publish_progress" do
+ it "publishes a compact step update to the admin-secured execution channel" do
+ execution = store.start!
+ step =
+ DiscourseWorkflows::Executor::Step.build(
+ node: OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [{ "json" => { "secret" => "not published" } }],
+ )
+
+ messages =
+ MessageBus.track_publish("/discourse-workflows/execution/#{execution.id}") do
+ store.publish_progress(step: step)
+ end
+
+ expect(messages.length).to eq(1)
+ expect(messages.first.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ payload = messages.first.data
+ expect(payload).to include(type: "execution_progress", refresh: false)
+ expect(payload[:execution]).to include(id: execution.id, status: "running")
+ expect(payload[:step]).to include(
+ "node_id" => "1",
+ "node_name" => "Node A",
+ "status" => "running",
+ )
+ expect(messages.first.data.to_json).not_to include("not published")
+ end
+ it "publishes terminal state after persistence" do
+ execution = store.start!
+
+ messages =
+ MessageBus.track_publish("/discourse-workflows/execution/#{execution.id}") do
+ store.finish!(steps: [])
+ end
+
+ expect(messages.length).to eq(1)
+ expect(messages.first.data).to include(type: "execution_progress", refresh: true)
+ expect(messages.first.data[:execution]).to include(
+ id: execution.id,
+ status: "success",
+ finished_at: be_present,
+ )
+ end
+ end
+
describe "#save! via finish!" do
before { store.start! }
@@ -73,21 +118,21 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
),
]
- allow(MessageBus).to receive(:publish)
-
- store.finish!(steps: steps)
+ messages =
+ MessageBus.track_publish("/discourse-workflows/workflow/#{workflow.id}") do
+ store.finish!(steps: steps)
+ end
- expect(MessageBus).to have_received(:publish) do |channel, payload, opts|
- expect(channel).to eq("/discourse-workflows/workflow/#{workflow.id}")
- expect(opts).to eq(group_ids: [Group::AUTO_GROUPS[:admins]])
- expect(payload[:type]).to eq("execution_completed")
- published_run = payload.dig(:lastExecutionRunData, "Node A", 0)
- expect(published_run).to include("node_name" => "Node A")
- expect(published_run["outputs"]).to include(
- hash_including("index" => 0, "item_count" => 1),
- hash_including("index" => 1, "item_count" => 1),
- )
- end
+ expect(messages.length).to eq(1)
+ payload = messages.first.data
+ expect(messages.first.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(payload[:type]).to eq("execution_completed")
+ published_run = payload.dig(:lastExecutionRunData, "Node A", 0)
+ expect(published_run).to include("node_name" => "Node A")
+ expect(published_run["outputs"]).to include(
+ hash_including("index" => 0, "item_count" => 1),
+ hash_including("index" => 1, "item_count" => 1),
+ )
run = store.execution.execution_data.run_data.dig("Node A", 0)
expect(run).to include(
@@ -281,22 +326,22 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
let(:options) { DiscourseWorkflows::Executor::ExecutionOptions.new(draft_execution: true) }
it "publishes completion data when the execution fails before node output exists" do
- allow(MessageBus).to receive(:publish)
-
- store.fail!(error: StandardError.new("boom"), steps: [])
-
- expect(MessageBus).to have_received(:publish) do |channel, payload, opts|
- expect(channel).to eq("/discourse-workflows/workflow/#{workflow.id}")
- expect(opts).to eq(group_ids: [Group::AUTO_GROUPS[:admins]])
- expect(payload[:type]).to eq("execution_completed")
- expect(payload[:execution]).to include(
- id: store.execution.id,
- workflow_id: workflow.id,
- trigger_node_id: "node_1",
- status: "error",
- )
- expect(payload[:lastExecutionRunData]).to eq({})
- end
+ messages =
+ MessageBus.track_publish("/discourse-workflows/workflow/#{workflow.id}") do
+ store.fail!(error: StandardError.new("boom"), steps: [])
+ end
+
+ expect(messages.length).to eq(1)
+ payload = messages.first.data.deep_symbolize_keys
+ expect(messages.first.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(payload[:type]).to eq("execution_completed")
+ expect(payload[:execution]).to include(
+ id: store.execution.id,
+ workflow_id: workflow.id,
+ trigger_node_id: "node_1",
+ status: "error",
+ )
+ expect(payload[:lastExecutionRunData]).to eq({})
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
index 68184aedc4a..5d96691f30b 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
@@ -36,6 +36,22 @@ RSpec.describe DiscourseWorkflows::Executor do
expect(topic.reload.tags).to include(tag)
end
+ it "publishes step and terminal progress" do
+ messages =
+ MessageBus.track_publish { described_class.new(workflow, "trigger-1", trigger_data).run }
+ progress_messages =
+ messages.select do |message|
+ message.channel.start_with?("/discourse-workflows/execution/")
+ end
+
+ expect(progress_messages.map { |message| message.data.dig(:step, "status") }.compact).to eq(
+ %w[success running success],
+ )
+ expect(progress_messages.last.data).to include(type: "execution_progress", refresh: true)
+ expect(progress_messages.last.data[:execution]).to include(status: "success")
+ expect(progress_messages.map(&:group_ids).uniq).to eq([[Group::AUTO_GROUPS[:admins]]])
+ end
+
it "creates an execution record" do
expect { described_class.new(workflow, "trigger-1", trigger_data).run }.to change {
DiscourseWorkflows::Execution.count
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
index ddab1bb4d52..3730bb2c531 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
@@ -245,9 +245,22 @@ RSpec.describe DiscourseWorkflows::Executor do
expect(execution.status).to eq("waiting")
response_items = [{ "json" => { "approved" => true } }]
- claimed = DiscourseWorkflows::Execution.claim_for_resume(execution)
- resumed = DiscourseWorkflows::Executor.resume(claimed, response_items)
+ claimed = nil
+ resumed = nil
+ messages =
+ MessageBus.track_publish("/discourse-workflows/execution/#{execution.id}") do
+ claimed = DiscourseWorkflows::Execution.claim_for_resume(execution)
+ resumed = DiscourseWorkflows::Executor.resume(claimed, response_items)
+ end
+ resumed_wait_step = messages.find { |message| message.data.dig(:step, "node_id") == "wait-1" }
+ expect(resumed_wait_step.data.dig(:step, "status")).to eq("success")
+ expect(resumed_wait_step.data.dig(:step, "error")).to be_nil
+ resumed_status =
+ messages.find do |message|
+ message.data[:step].nil? && message.data.dig(:execution, :status) == "running"
+ end
+ expect(resumed_status.data[:refresh]).to eq(false)
expect(resumed).to have_attributes(
status: "success",
finished_at: be_present,
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb
index f1e3aeb1758..276f5a8dcfc 100644
--- a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb
@@ -90,7 +90,10 @@ RSpec.describe DiscourseWorkflows::Execution do
end
it "transitions a waiting execution to error and clears waiting fields" do
- expect(execution.fail_with_timeout!).to eq(true)
+ messages =
+ MessageBus.track_publish("/discourse-workflows/execution/#{execution.id}") do
+ expect(execution.fail_with_timeout!).to eq(true)
+ end
execution.reload
expect(execution).to have_attributes(
@@ -100,6 +103,10 @@ RSpec.describe DiscourseWorkflows::Execution do
resume_token: nil,
timeout_action: nil,
)
+ expect(messages.length).to eq(1)
+ expect(messages.first.group_ids).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(messages.first.data).to include(type: "execution_progress", refresh: true)
+ expect(messages.first.data[:execution]).to include(id: execution.id, status: "error")
end
it "returns false and does not transition when the execution is no longer waiting" do
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
index 8d247967e3c..26c2434ff05 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
@@ -113,9 +113,10 @@ RSpec.describe DiscourseWorkflows::ExecutionsController do
json = response.parsed_body
expect(json["executions"].map { |execution| execution["id"] }).to eq([execution_2.id])
- expect(json["meta"]).to eq(
+ expect(json["meta"]).to include(
"load_more_executions" =>
"/admin/plugins/discourse-workflows/executions.json?cursor=#{execution_2.id}&limit=1",
+ "message_bus_last_id" => be_a(Integer),
)
end
end
@@ -185,6 +186,7 @@ RSpec.describe DiscourseWorkflows::ExecutionsController do
expect(json["execution"]["id"]).to eq(execution.id)
expect(json["execution"]["workflow_name"]).to eq(workflow.name)
expect(json["execution"]["steps"].length).to eq(1)
+ expect(json.dig("meta", "message_bus_last_id")).to be_a(Integer)
end
it "returns caller workflow data for child executions" do
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/execution/manager-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/execution/manager-test.gjs
new file mode 100644
index 00000000000..0dd50ecffa2
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/execution/manager-test.gjs
@@ -0,0 +1,212 @@
+import Service from "@ember/service";
+import { render, settled, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { fakeTime } from "discourse/tests/helpers/qunit-helpers";
+import ExecutionsManager from "discourse/plugins/discourse-workflows/admin/components/workflows/execution/manager";
+
+class MessageBusStub extends Service {
+ subscriptions = new Map();
+
+ subscribe(channel, handler, lastId) {
+ this.subscriptions.set(channel, { handler, lastId });
+ }
+
+ unsubscribe(channel) {
+ this.subscriptions.delete(channel);
+ }
+
+ publish(channel, message, messageId) {
+ this.subscriptions.get(channel)?.handler(message, null, messageId);
+ }
+}
+
+module(
+ "Integration | Component | Workflows | Execution | ExecutionsManager",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.owner.unregister("service:message-bus");
+ this.owner.register("service:message-bus", MessageBusStub);
+ this.clock = fakeTime("2026-08-13T05:00:02Z", "UTC", true);
+ this.executionStatus = "running";
+ this.requestCount = 0;
+ this.messageBusLastId = 40;
+
+ pretender.get(
+ "/admin/plugins/discourse-workflows/workflows/30/executions.json",
+ () => {
+ this.requestCount++;
+ return response(200, {
+ executions: [
+ {
+ id: 11473,
+ workflow_id: 30,
+ workflow_name: "Running workflow",
+ status: this.executionStatus,
+ run_time_ms: null,
+ started_at: "2026-08-13T05:00:00Z",
+ finished_at: null,
+ },
+ ],
+ meta: { message_bus_last_id: this.messageBusLastId },
+ });
+ }
+ );
+ });
+
+ hooks.afterEach(function () {
+ this.clock.restore();
+ });
+
+ test("uses one aggregate subscription for lifecycle updates", async function (assert) {
+ await render(
+ <template><ExecutionsManager @workflowId={{30}} /></template>
+ );
+ await waitFor(".workflows-executions-manager__status");
+
+ const messageBus = this.owner.lookup("service:message-bus");
+ const channel = "/discourse-workflows/executions";
+ assert.strictEqual(
+ messageBus.subscriptions.get(channel).lastId,
+ 40,
+ "the subscription continues from the list response cursor"
+ );
+ assert.strictEqual(
+ messageBus.subscriptions.size,
+ 1,
+ "the list has one subscription regardless of live execution count"
+ );
+ assert
+ .dom(".workflows-executions-manager__status .spinner")
+ .exists("running rows use an animated spinner");
+ assert
+ .dom(".workflows-executions-manager__run-time")
+ .containsText("2s", "running rows show deterministic elapsed time");
+
+ messageBus.publish(
+ channel,
+ {
+ type: "execution_update",
+ execution: {
+ id: 11473,
+ workflow_id: 30,
+ status: "success",
+ run_time_ms: 3456,
+ finished_at: "2026-08-13T05:00:02Z",
+ },
+ },
+ 41
+ );
+ await settled();
+
+ assert
+ .dom(".workflows-executions-manager__status")
+ .hasText("Completed", "the terminal status updates without reloading");
+ assert
+ .dom(".workflows-executions-manager__run-time")
+ .containsText(
+ "3.5s",
+ "the final processing time comes from the server"
+ );
+ assert.true(
+ messageBus.subscriptions.has(channel),
+ "the aggregate subscription remains for future executions"
+ );
+ });
+
+ test("inserts newly created executions in id order and ignores unloaded updates", async function (assert) {
+ await render(
+ <template><ExecutionsManager @workflowId={{30}} /></template>
+ );
+ await waitFor(".workflows-executions-manager__status");
+
+ const messageBus = this.owner.lookup("service:message-bus");
+ const channel = "/discourse-workflows/executions";
+ messageBus.publish(
+ channel,
+ {
+ type: "execution_update",
+ execution: { id: 100, workflow_id: 30, status: "waiting" },
+ },
+ 41
+ );
+ messageBus.publish(
+ channel,
+ {
+ type: "execution_created",
+ execution: {
+ id: 12000,
+ workflow_id: 30,
+ workflow_name: "New workflow",
+ status: "pending",
+ },
+ },
+ 42
+ );
+ await settled();
+
+ assert
+ .dom(".workflows-executions-manager__status")
+ .exists(
+ { count: 2 },
+ "only created executions are added to the loaded page"
+ );
+ assert
+ .dom(".d-table__row:first-child .workflows-executions-manager__status")
+ .hasText("Pending", "the newer execution is placed first");
+ });
+
+ test("distinguishes queued executions from active processing", async function (assert) {
+ this.executionStatus = "pending";
+
+ await render(
+ <template><ExecutionsManager @workflowId={{30}} /></template>
+ );
+ await waitFor(".workflows-executions-manager__status");
+
+ assert
+ .dom(".workflows-executions-manager__status")
+ .hasText("Pending", "the queued state is shown");
+ assert
+ .dom(".workflows-executions-manager__status .spinner")
+ .doesNotExist("queued work does not look like active processing");
+ assert
+ .dom(".workflows-executions-manager__run-time")
+ .containsText("—", "queued work has no elapsed processing time");
+ });
+
+ test("reloads authoritative data when aggregate messages have a gap", async function (assert) {
+ await render(
+ <template><ExecutionsManager @workflowId={{30}} /></template>
+ );
+ await waitFor(".workflows-executions-manager__status");
+
+ this.executionStatus = "success";
+ this.messageBusLastId = 45;
+ this.owner.lookup("service:message-bus").publish(
+ "/discourse-workflows/executions",
+ {
+ type: "execution_update",
+ execution: { id: 11473, workflow_id: 30, status: "running" },
+ },
+ 44
+ );
+ await settled();
+
+ assert.strictEqual(this.requestCount, 2, "the list is fetched again");
+ assert
+ .dom(".workflows-executions-manager__status")
+ .hasText("Completed", "the response replaces the skipped event state");
+ assert.strictEqual(
+ this.owner
+ .lookup("service:message-bus")
+ .subscriptions.get("/discourse-workflows/executions").lastId,
+ 45,
+ "the replacement subscription uses the refreshed cursor"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs
index 2d227591a34..1b35dc7afe9 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs
@@ -1,7 +1,9 @@
import Service from "@ember/service";
-import { click, render } from "@ember/test-helpers";
+import { click, render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { fakeTime } from "discourse/tests/helpers/qunit-helpers";
import ExecutionDetail from "discourse/plugins/discourse-workflows/admin/components/workflows/executions/detail";
let transitions;
@@ -46,6 +48,49 @@ function executionWithOutput(output) {
};
}
+class MessageBusStub extends Service {
+ subscriptions = new Map();
+
+ subscribe(channel, handler, lastId) {
+ this.subscriptions.set(channel, { handler, lastId });
+ }
+
+ unsubscribe(channel) {
+ this.subscriptions.delete(channel);
+ }
+
+ publish(channel, message, messageId) {
+ this.subscriptions.get(channel)?.handler(message, null, messageId);
+ }
+}
+
+class ReplayMessageBusStub extends Service {
+ subscribe(channel, handler, lastId) {
+ if (lastId === 40) {
+ handler(
+ {
+ type: "execution_progress",
+ execution: { id: 11474, status: "running" },
+ refresh: false,
+ step: {
+ node_id: "node-1",
+ node_name: "Already running",
+ node_type: "action:code",
+ position: 0,
+ status: "running",
+ started_at: new Date().toISOString(),
+ finished_at: null,
+ },
+ },
+ null,
+ 41
+ );
+ }
+ }
+
+ unsubscribe() {}
+}
+
module(
"Integration | Component | Workflows | Executions | ExecutionDetail",
function (hooks) {
@@ -61,6 +106,13 @@ module(
"service:workflows-node-types",
WorkflowsNodeTypesStub
);
+ this.owner.unregister("service:message-bus");
+ this.owner.register("service:message-bus", MessageBusStub);
+ this.clock = fakeTime("2026-08-13T05:00:02Z", "UTC", true);
+ });
+
+ hooks.afterEach(function () {
+ this.clock.restore();
});
test("explains when a successful node returns no output", async function (assert) {
@@ -207,5 +259,219 @@ module(
"the button transitions to the parent execution route"
);
});
+ test("replays progress emitted before the detail page subscribes", async function (assert) {
+ this.owner.unregister("service:message-bus");
+ this.owner.register("service:message-bus", ReplayMessageBusStub);
+ this.execution = {
+ id: 11474,
+ workflow_id: 30,
+ workflow_name: "Running workflow",
+ status: "running",
+ message_bus_last_id: 40,
+ started_at: new Date().toISOString(),
+ finished_at: null,
+ steps: [],
+ };
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+
+ assert
+ .dom(".workflows-execution-detail__step-name")
+ .hasText(
+ "Already running",
+ "a step emitted before navigation is restored from the channel backlog"
+ );
+ });
+
+ test("refreshes authoritative details at a terminal boundary", async function (assert) {
+ this.execution = {
+ id: 11475,
+ workflow_id: 30,
+ workflow_name: "Running workflow",
+ status: "running",
+ message_bus_last_id: 40,
+ started_at: new Date(Date.now() - 2000).toISOString(),
+ finished_at: null,
+ steps: [],
+ };
+ pretender.get("/admin/plugins/discourse-workflows/executions/11475", () =>
+ response(200, {
+ execution: {
+ ...this.execution,
+ status: "success",
+ run_time_ms: 2500,
+ finished_at: new Date().toISOString(),
+ steps: [
+ {
+ node_id: "node-1",
+ node_name: "Authoritative step",
+ node_type: "action:code",
+ position: 0,
+ status: "success",
+ input: [],
+ output: [{ json: { result: "complete" } }],
+ started_at: this.execution.started_at,
+ finished_at: new Date().toISOString(),
+ },
+ ],
+ },
+ meta: { message_bus_last_id: 41 },
+ })
+ );
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+ this.owner.lookup("service:message-bus").publish(
+ "/discourse-workflows/execution/11475",
+ {
+ type: "execution_progress",
+ execution: { id: 11475, status: "success", run_time_ms: 2500 },
+ refresh: true,
+ },
+ 41
+ );
+ await settled();
+
+ assert
+ .dom(".workflows-execution-detail__step-name")
+ .hasText(
+ "Authoritative step",
+ "the persisted execution replaces the compact live summary"
+ );
+ assert
+ .dom(".workflows-execution-detail__progress")
+ .doesNotExist("the running indicator is removed");
+ });
+
+ test("replaces partial progress when a message gap is detected", async function (assert) {
+ this.execution = {
+ id: 11476,
+ workflow_id: 30,
+ workflow_name: "Running workflow",
+ status: "running",
+ message_bus_last_id: 40,
+ started_at: new Date(Date.now() - 2000).toISOString(),
+ finished_at: null,
+ steps: [],
+ };
+ pretender.get("/admin/plugins/discourse-workflows/executions/11476", () =>
+ response(200, {
+ execution: {
+ ...this.execution,
+ steps: [
+ {
+ node_id: "node-authoritative",
+ node_name: "Recovered step",
+ node_type: "action:code",
+ position: 0,
+ status: "success",
+ input: [],
+ output: [],
+ started_at: "2026-08-13T05:00:00Z",
+ finished_at: "2026-08-13T05:00:01Z",
+ },
+ ],
+ },
+ meta: { message_bus_last_id: 45 },
+ })
+ );
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+ this.owner.lookup("service:message-bus").publish(
+ "/discourse-workflows/execution/11476",
+ {
+ type: "execution_progress",
+ execution: { id: 11476, status: "running" },
+ step: {
+ node_id: "node-partial",
+ node_name: "Skipped partial step",
+ node_type: "action:code",
+ position: 1,
+ status: "running",
+ },
+ },
+ 44
+ );
+ await settled();
+
+ assert
+ .dom(".workflows-execution-detail__step-name")
+ .hasText(
+ "Recovered step",
+ "the authoritative response repairs the gap"
+ );
+ assert
+ .dom(".workflows-execution-detail__step")
+ .exists({ count: 1 }, "the out-of-sequence event is not merged");
+ assert.strictEqual(
+ this.owner
+ .lookup("service:message-bus")
+ .subscriptions.get("/discourse-workflows/execution/11476").lastId,
+ 45,
+ "the recovered stream resumes at the response cursor"
+ );
+ });
+
+ test("shows live progress for a running execution", async function (assert) {
+ this.execution = {
+ id: 11473,
+ workflow_id: 30,
+ workflow_name: "Running workflow",
+ status: "running",
+ message_bus_last_id: 40,
+ started_at: new Date(Date.now() - 2000).toISOString(),
+ finished_at: null,
+ steps: [],
+ };
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+
+ assert
+ .dom(".workflows-execution-detail__progress-label")
+ .hasText("Running", "the running status is visible");
+ assert
+ .dom(".workflows-execution-detail__progress .spinner")
+ .exists("a spinner communicates ongoing work");
+ assert
+ .dom(".workflows-execution-detail__progress-time")
+ .hasText("2s", "the elapsed time advances in whole seconds");
+
+ this.owner.lookup("service:message-bus").publish(
+ "/discourse-workflows/execution/11473",
+ {
+ type: "execution_progress",
+ execution: { id: 11473, status: "running" },
+ refresh: false,
+ step: {
+ node_id: "node-1",
+ node_name: "Fetch topic",
+ node_type: "action:code",
+ position: 0,
+ status: "running",
+ started_at: new Date().toISOString(),
+ finished_at: null,
+ },
+ },
+ 41
+ );
+ await settled();
+
+ assert
+ .dom(".workflows-execution-detail__step")
+ .exists({ count: 1 }, "the server event adds the running step");
+ assert
+ .dom(".workflows-execution-detail__step-name")
+ .hasText("Fetch topic", "the live step name is visible");
+ assert
+ .dom(".workflows-execution-detail__step-badge")
+ .hasText("Running", "the live step status is visible");
+ });
}
);