assay-workflow 0.1.8

Durable workflow engine with REST+SSE API, PostgreSQL/SQLite backends. Embeddable library or standalone server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* Assay Workflow Dashboard - Workflows Component */

var AssayWorkflows = (function () {
  'use strict';

  const PAGE_SIZE = 20;
  let currentOffset = 0;
  let currentFilter = '';
  let searchTerm = '';
  let searchAttrs = '';
  let ctx = null;
  let container = null;

  /**
   * Toggle the inline expansion row for a workflow. Click once to open,
   * click again to close. Opening another row auto-closes the previous
   * one — simpler to scan than a pile of open rows, matches the pattern
   * you'd get from a radio group.
   */
  function toggleRowDetail(linkEl) {
    var row = linkEl.closest('tr');
    if (!row) return;
    var id = linkEl.dataset.id;

    // Click-to-close on the already-expanded row.
    var next = row.nextElementSibling;
    if (next && next.classList.contains('wf-detail-row') && next.dataset.forId === id) {
      next.remove();
      row.classList.remove('wf-row-expanded');
      return;
    }
    // Close any other open detail rows in the same table first.
    var openDetails = row.parentNode.querySelectorAll('.wf-detail-row');
    for (var i = 0; i < openDetails.length; i++) openDetails[i].remove();
    var openParents = row.parentNode.querySelectorAll('.wf-row-expanded');
    for (var j = 0; j < openParents.length; j++) {
      openParents[j].classList.remove('wf-row-expanded');
    }

    // Expand this row.
    var colCount = row.children.length;
    var detailRow = document.createElement('tr');
    detailRow.className = 'wf-detail-row';
    detailRow.dataset.forId = id;
    detailRow.innerHTML =
      '<td colspan="' + colCount + '">' +
        '<div class="wf-inline-detail"></div>' +
      '</td>';
    row.parentNode.insertBefore(detailRow, row.nextSibling);
    row.classList.add('wf-row-expanded');

    var target = detailRow.querySelector('.wf-inline-detail');
    if (ctx.showDetail) {
      ctx.showDetail(id, ctx, {
        target: target,
        onClose: function () {
          detailRow.remove();
          row.classList.remove('wf-row-expanded');
        },
      });
    }
  }

  function render(el, context) {
    ctx = context;
    container = el;
    currentOffset = 0;
    currentFilter = '';
    searchTerm = '';
    searchAttrs = '';

    el.innerHTML =
      '<h2 class="section-title">Workflows</h2>' +
      '<div class="toolbar">' +
        '<input type="text" class="search-input" id="wf-search" placeholder="Search by ID or type...">' +
        '<select class="filter-select" id="wf-status-filter">' +
          '<option value="">All Statuses</option>' +
          '<option value="PENDING">Pending</option>' +
          '<option value="RUNNING">Running</option>' +
          '<option value="COMPLETED">Completed</option>' +
          '<option value="FAILED">Failed</option>' +
          '<option value="WAITING">Waiting</option>' +
          '<option value="CANCELLED">Cancelled</option>' +
        '</select>' +
        '<input type="text" class="search-input" id="wf-search-attrs" placeholder=\'Search attrs filter, e.g. {"env":"prod"}\' style="flex:1.2;">' +
        '<button type="button" class="btn-action btn-action-primary" id="wf-start-toggle">+ Start workflow</button>' +
      '</div>' +
      '<div id="wf-start-form-wrap"></div>' +
      '<div id="wf-table-wrap"></div>' +
      '<div id="wf-pagination" class="pagination"></div>';

    el.querySelector('#wf-search').addEventListener('input', function (e) {
      searchTerm = e.target.value.trim();
      currentOffset = 0;
      loadWorkflows();
    });

    el.querySelector('#wf-status-filter').addEventListener('change', function (e) {
      currentFilter = e.target.value;
      currentOffset = 0;
      loadWorkflows();
    });

    // Search-attributes filter: debounce so every keystroke doesn't hit
    // the API. 300ms matches common search-field latency heuristics.
    let searchAttrsTimer = null;
    el.querySelector('#wf-search-attrs').addEventListener('input', function (e) {
      const val = e.target.value.trim();
      clearTimeout(searchAttrsTimer);
      searchAttrsTimer = setTimeout(function () {
        searchAttrs = val;
        currentOffset = 0;
        loadWorkflows();
      }, 300);
    });

    el.querySelector('#wf-start-toggle').addEventListener('click', toggleStartForm);

    el.querySelector('#wf-table-wrap').addEventListener('click', function (e) {
      var link = e.target.closest('.wf-link');
      if (link) {
        e.preventDefault();
        toggleRowDetail(link);
        return;
      }

      var signalBtn = e.target.closest('.btn-signal');
      if (signalBtn) {
        e.preventDefault();
        handleSignal(signalBtn.dataset.id);
        return;
      }

      var cancelBtn = e.target.closest('.btn-cancel');
      if (cancelBtn) {
        e.preventDefault();
        handleCancel(cancelBtn.dataset.id);
        return;
      }

      var termBtn = e.target.closest('.btn-terminate');
      if (termBtn) {
        e.preventDefault();
        handleTerminate(termBtn.dataset.id);
      }
    });

    el.querySelector('#wf-pagination').addEventListener('click', function (e) {
      var btn = e.target.closest('.btn[data-offset]');
      if (!btn) return;
      currentOffset = parseInt(btn.dataset.offset, 10);
      loadWorkflows();
    });

    loadWorkflows();
  }

  async function loadWorkflows() {
    var wrap = container.querySelector('#wf-table-wrap');
    var params = '?limit=' + PAGE_SIZE + '&offset=' + currentOffset;
    if (currentFilter) params += '&status=' + currentFilter;
    if (searchTerm) params += '&type=' + encodeURIComponent(searchTerm);
    if (searchAttrs) {
      // Validate JSON client-side so bad input doesn't silently vanish.
      try {
        JSON.parse(searchAttrs);
        params += '&search_attrs=' + encodeURIComponent(searchAttrs);
      } catch (_) {
        // Invalid JSON: skip the param, leave a subtle hint on the input.
        var attrsInput = container.querySelector('#wf-search-attrs');
        if (attrsInput) attrsInput.style.borderColor = '#d04040';
        renderTable(wrap, []);
        return;
      }
    }
    var attrsInput = container.querySelector('#wf-search-attrs');
    if (attrsInput) attrsInput.style.borderColor = '';

    try {
      var workflows = await ctx.apiFetch('/workflows' + params);
      renderTable(wrap, workflows);
      renderPagination(workflows.length);
    } catch (err) {
      wrap.innerHTML = '<div class="empty-state"><p>Error loading workflows: ' + ctx.escapeHtml(err.message) + '</p></div>';
    }
  }

  function renderTable(wrap, workflows) {
    if (!workflows || workflows.length === 0) {
      wrap.innerHTML = '<div class="empty-state"><p>No workflows found</p></div>';
      return;
    }

    var html =
      '<table class="data-table">' +
      '<thead><tr>' +
        '<th>ID</th>' +
        '<th>Type</th>' +
        '<th>Status</th>' +
        '<th>Queue</th>' +
        '<th>Created</th>' +
        '<th>Actions</th>' +
      '</tr></thead><tbody>';

    for (var i = 0; i < workflows.length; i++) {
      var wf = workflows[i];
      var status = (wf.status || 'PENDING').toUpperCase();
      var terminal = ctx.isTerminal(status);

      html +=
        '<tr>' +
        // title= reveals the full workflow id on hover — ids are
        // truncated to 32 chars for table density, but operators debugging
        // a specific run need to see the whole value without opening the
        // detail panel or URL-bar surgery.
        '<td><a href="#" class="clickable wf-link mono" data-id="' + ctx.escapeHtml(wf.id) +
          '" title="' + ctx.escapeHtml(wf.id) + '">' +
          ctx.escapeHtml(ctx.truncate(wf.id, 32)) + '</a></td>' +
        '<td>' + ctx.escapeHtml(wf.workflow_type || '-') + '</td>' +
        '<td><span class="badge ' + ctx.badgeClass(status) + '">' + status + '</span></td>' +
        '<td class="mono">' + ctx.escapeHtml(wf.task_queue || 'main') + '</td>' +
        '<td>' + ctx.formatTime(wf.created_at) + '</td>' +
        '<td>';

      if (!terminal) {
        html +=
          '<button class="btn btn-sm btn-signal" data-id="' + ctx.escapeHtml(wf.id) + '">Signal</button> ' +
          '<button class="btn btn-sm btn-cancel" data-id="' + ctx.escapeHtml(wf.id) + '">Cancel</button> ' +
          '<button class="btn btn-sm btn-danger btn-terminate" data-id="' + ctx.escapeHtml(wf.id) + '">Terminate</button>';
      } else {
        html += '<span style="color: var(--text-muted)">-</span>';
      }

      html += '</td></tr>';
    }

    html += '</tbody></table>';
    wrap.innerHTML = html;
  }

  function renderPagination(count) {
    var pag = container.querySelector('#wf-pagination');

    // Don't render the pagination bar at all when there's only one
    // page of results (no prev page, current page isn't full). A
    // standalone "Page 1" on a three-row table is chrome-for-its-own-
    // sake; operators only need the controls once there's actually
    // something to page through.
    var hasPrev = currentOffset > 0;
    var hasNext = count === PAGE_SIZE;
    if (!hasPrev && !hasNext) {
      pag.innerHTML = '';
      return;
    }

    var html = '';
    if (hasPrev) {
      html += '<button class="btn btn-sm" data-offset="' + Math.max(0, currentOffset - PAGE_SIZE) + '">Prev</button>';
    }
    var page = Math.floor(currentOffset / PAGE_SIZE) + 1;
    html += '<span style="padding: 0 8px; color: var(--text-muted);">Page ' + page + '</span>';
    if (hasNext) {
      html += '<button class="btn btn-sm" data-offset="' + (currentOffset + PAGE_SIZE) + '">Next</button>';
    }
    pag.innerHTML = html;
  }

  /// Open/close the inline "start workflow" form. Collapsed by default so
  /// the list takes the full width; click the button to expand.
  function toggleStartForm() {
    var wrap = container.querySelector('#wf-start-form-wrap');
    if (wrap.innerHTML.trim() !== '') {
      wrap.innerHTML = '';
      return;
    }
    wrap.innerHTML =
      '<form class="inline-form" id="wf-start-form">' +
        '<label>Workflow type <span style="color:#d04040">*</span>' +
          '<input type="text" name="type" placeholder="e.g. IngestData" required>' +
        '</label>' +
        '<label>Workflow ID (optional — auto-generated if blank)' +
          '<input type="text" name="id" placeholder="e.g. ingest-2026-04-17">' +
        '</label>' +
        '<label>Task queue' +
          '<input type="text" name="task_queue" value="default">' +
        '</label>' +
        '<label>Input (JSON, optional)' +
          '<textarea name="input" placeholder=\'{"key":"value"}\'></textarea>' +
        '</label>' +
        '<label>Search attributes (JSON, optional)' +
          '<textarea name="search_attrs" placeholder=\'{"env":"prod","tenant":"acme"}\'></textarea>' +
        '</label>' +
        '<div class="form-actions">' +
          '<button type="button" class="btn-action" id="wf-start-cancel">Cancel</button>' +
          '<button type="submit" class="btn-action btn-action-primary">Start</button>' +
        '</div>' +
      '</form>';
    wrap.querySelector('#wf-start-cancel').addEventListener('click', function () {
      wrap.innerHTML = '';
    });
    wrap.querySelector('#wf-start-form').addEventListener('submit', handleStart);
  }

  async function handleStart(e) {
    e.preventDefault();
    var form = e.currentTarget;
    var data = new FormData(form);
    var body = {
      workflow_type: data.get('type').trim(),
      task_queue: (data.get('task_queue') || 'default').trim(),
      namespace: ctx.getNamespace(),
    };
    var idVal = (data.get('id') || '').trim();
    if (idVal) {
      body.workflow_id = idVal;
    } else {
      body.workflow_id =
        'wf-' + body.workflow_type.toLowerCase() + '-' + Date.now();
    }
    var inputRaw = (data.get('input') || '').trim();
    if (inputRaw) {
      try {
        body.input = JSON.parse(inputRaw);
      } catch (err) {
        ctx.toast('Input is not valid JSON', 'error');
        return;
      }
    }
    var attrsRaw = (data.get('search_attrs') || '').trim();
    if (attrsRaw) {
      try {
        body.search_attributes = JSON.parse(attrsRaw);
      } catch (err) {
        ctx.toast('Search attributes must be valid JSON', 'error');
        return;
      }
    }

    try {
      await ctx.apiFetchRaw('/workflows', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      ctx.toast('Started ' + body.workflow_id, 'success');
      container.querySelector('#wf-start-form-wrap').innerHTML = '';
      loadWorkflows();
    } catch (err) {
      ctx.toast('Start failed: ' + err.message, 'error');
    }
  }

  async function handleSignal(id) {
    var name = prompt('Signal name:');
    if (!name) return;
    var payloadStr = prompt('Signal payload (JSON, or leave empty):', '');
    var payload = null;
    if (payloadStr) {
      try {
        payload = JSON.parse(payloadStr);
      } catch (_) {
        payload = payloadStr;
      }
    }

    try {
      await ctx.apiFetch('/workflows/' + encodeURIComponent(id) + '/signal/' + encodeURIComponent(name), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ payload: payload }),
      });
      ctx.toast("Signal '" + name + "' sent", 'success');
      loadWorkflows();
    } catch (err) {
      ctx.toast('Signal failed: ' + err.message, 'error');
    }
  }

  async function handleCancel(id) {
    if (!confirm('Cancel workflow ' + id + '?')) return;
    try {
      await ctx.apiFetch('/workflows/' + encodeURIComponent(id) + '/cancel', {
        method: 'POST',
      });
      ctx.toast('Cancel requested', 'success');
      loadWorkflows();
    } catch (err) {
      ctx.toast('Cancel failed: ' + err.message, 'error');
    }
  }

  async function handleTerminate(id) {
    var reason = prompt(
      'Terminate workflow ' + id + '?\n\nReason (optional):',
      ''
    );
    if (reason === null) return; // user cancelled
    var body = reason ? { reason: reason } : {};
    try {
      await ctx.apiFetch('/workflows/' + encodeURIComponent(id) + '/terminate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      ctx.toast('Terminated', 'success');
      loadWorkflows();
    } catch (err) {
      ctx.toast('Terminate failed: ' + err.message, 'error');
    }
  }

  return { render: render };
})();