loopengine 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -214,7 +214,7 @@ export const agentsConfigPageHtml = `<!doctype html>
214
214
  .wf-section { display: grid; gap: 10px; min-width: 0; }
215
215
  .wf-panel > .wf-section + .wf-section { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--line); }
216
216
  .wf-section .wf-sub { margin: 0; }
217
- .wf-run-lines, .wf-cand-list, .wf-change-list { min-width: 0; }
217
+ .wf-run-lines, .wf-cand-list { min-width: 0; }
218
218
  .wf-run-line, .wf-run-link { min-width: 0; overflow: hidden; }
219
219
  .wf-run-lines, .wf-cand-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
220
220
  .wf-run-line, .wf-cand-list li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding: 8px 12px; border-top: 1px solid var(--line); font-size: 13px; }
@@ -235,7 +235,6 @@ export const agentsConfigPageHtml = `<!doctype html>
235
235
  .wf-health-table table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
236
236
  .wf-health-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
237
237
  .wf-health-table td { padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
238
- .wf-audit-summary ul.wf-audit-lines { margin: 0; padding-left: 20px; display: grid; gap: 4px; font-size: 13.5px; line-height: 1.5; }
239
238
  .wf-audit-tools { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 4px; }
240
239
  .wf-audit-tools a { font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 12px; border: 1px solid var(--line); border-radius: 8px; }
241
240
  .wf-audit-tools a.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
@@ -253,16 +252,89 @@ export const agentsConfigPageHtml = `<!doctype html>
253
252
  .chg-ins { background: var(--good-soft); color: var(--good); padding: 1px 6px; }
254
253
  .chg-note { color: var(--ink-muted); font-family: inherit; font-weight: 400; }
255
254
  .chg details summary { cursor: pointer; color: var(--accent-ink); font-family: var(--font-sans, inherit); font-size: 12px; margin-top: 2px; }
256
- .wf-change-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; font-size: 13px; }
257
- .wf-change-list li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding-bottom: 8px; border-bottom: 1px solid var(--line); }
258
- .wf-change-kind { font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-faint); min-width: 64px; }
259
- .wf-change-kind.change { color: var(--accent-ink); }
260
- .wf-change-text { flex: 1 1 280px; }
261
- .wf-versions { display: grid; gap: 8px; margin-bottom: 12px; font-size: 13px; }
262
- .wf-versions[hidden], .wf-versions-list[hidden], .wf-version-text[hidden] { display: none; }
263
- .wf-versions-line, .wf-versions-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
264
- .wf-versions-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; border-left: 2px solid var(--line); padding-left: 12px; }
265
- .wf-versions-list li { display: grid; gap: 6px; }
255
+ .wf-page-meta-item[hidden] { display: none; }
256
+ .wf-sub-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
257
+ .wf-act-main[hidden], .wf-trace[hidden] { display: none; }
258
+ .wf-act-main > .wf-section + .wf-section { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--line); }
259
+ .wf-run-cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
260
+ .wf-run-card { display: grid; gap: 6px; padding: 10px 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg); min-width: 0; font-size: 13px; }
261
+ .wf-run-card.is-failed { border-left: 3px solid var(--bad); }
262
+ .wf-run-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; }
263
+ .wf-run-card-actions { display: flex; align-items: center; gap: 12px; margin-left: auto; }
264
+ .wf-run-card-actions .wf-run-trace { height: 28px; padding: 0 10px; border-radius: 8px; font-size: 12.5px; font-weight: 600; border: 1px solid var(--accent); background: var(--accent-soft); color: var(--accent-ink); }
265
+ .wf-run-card-actions .wf-run-trace:hover { background: var(--accent); color: var(--on-accent); }
266
+ .wf-run-version { font-family: var(--font-mono); font-size: 11.5px; font-weight: 700; padding: 1px 7px; border-radius: 999px; background: var(--surface-2); color: var(--ink-muted); }
267
+ .wf-run-card-inputs { color: var(--ink-muted); overflow-wrap: anywhere; }
268
+ .wf-run-card-out { overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
269
+ .wf-run-card-out.error { color: var(--bad); }
270
+ .wf-trace { display: grid; gap: 20px; min-width: 0; }
271
+ .wf-trace-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; }
272
+ .wf-trace-bar a.wf-link { text-decoration: none; }
273
+ .wf-trace-save-case { height: 30px; padding: 0 12px; border-radius: 8px; font-size: 13px; font-weight: 600; border: 1px solid var(--accent); background: var(--accent-soft); color: var(--accent-ink); }
274
+ .wf-trace-case { display: grid; gap: 8px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); font-size: 13px; }
275
+ .wf-trace-case[hidden] { display: none; }
276
+ .wf-trace-suggest { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
277
+ .wf-trace-suggest li { display: flex; gap: 12px; align-items: baseline; justify-content: space-between; }
278
+ .wf-xd { padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
279
+ .wf-xd-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 10px; }
280
+ .wf-xd-head h3 { margin: 0; font-size: 16px; }
281
+ .wf-xd-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px 16px; margin: 0; }
282
+ .wf-xd-item { display: grid; gap: 2px; min-width: 0; }
283
+ .wf-xd-item dt, .wf-xd-k { font-size: 11px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-faint); }
284
+ .wf-xd-item dd { margin: 0; font-size: 13px; overflow-wrap: anywhere; }
285
+ .wf-xd-item dd a { color: var(--accent-ink); font-weight: 600; text-decoration: none; }
286
+ .wf-xd-error { padding: 8px 12px; border-radius: 8px; background: var(--bad-soft); color: var(--bad); font-size: 13px; overflow-wrap: anywhere; }
287
+ .wf-xd-io { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; }
288
+ .wf-xd-io > div { display: grid; gap: 4px; align-content: start; min-width: 0; }
289
+ .wf-xd-params { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 2px 10px; margin: 0; font-size: 13px; }
290
+ .wf-xd-params dt { font-family: var(--font-mono); font-size: 12px; color: var(--ink-muted); }
291
+ .wf-xd-params dd { margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
292
+ .wf-tv-pre { margin: 0; padding: 8px 10px; border-radius: 8px; background: var(--bg); border: 1px solid var(--line); font-family: var(--font-mono); font-size: 12px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 360px; overflow: auto; }
293
+ .wf-tv-block { display: grid; gap: 4px; min-width: 0; }
294
+ .wf-tv-block summary { cursor: pointer; color: var(--accent-ink); font-size: 12.5px; font-weight: 600; }
295
+ .wf-tl-wrap { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 14px; align-items: start; }
296
+ .wf-tl { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; position: relative; }
297
+ .wf-tl::before { content: ""; position: absolute; left: 15px; top: 14px; bottom: 14px; width: 2px; background: var(--line); }
298
+ .wf-tl-step { position: relative; width: 100%; height: auto; display: grid; grid-template-columns: 14px minmax(0, 1fr) auto; grid-template-areas: "dot text time" ". bar bar"; gap: 2px 10px; align-items: start; padding: 8px 10px 8px 9px; border: 1px solid transparent; border-radius: 8px; background: none; text-align: left; font: inherit; font-size: 13px; color: var(--ink); cursor: pointer; }
299
+ .wf-tl-step:hover { background: var(--surface); }
300
+ .wf-tl-step[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent); }
301
+ .wf-tl-dot { grid-area: dot; width: 12px; height: 12px; margin-top: 3px; border-radius: 50%; background: var(--bg); border: 2px solid var(--ink-faint); position: relative; z-index: 1; }
302
+ .wf-tl-step.k-model .wf-tl-dot { border-color: var(--accent); }
303
+ .wf-tl-step.k-tool .wf-tl-dot { border-color: var(--good); }
304
+ .wf-tl-step.k-person .wf-tl-dot { border-color: var(--warn); }
305
+ .wf-tl-step.k-start .wf-tl-dot, .wf-tl-step.k-end .wf-tl-dot { background: var(--ink-faint); }
306
+ .wf-tl-step.is-bad .wf-tl-dot { border-color: var(--bad); background: var(--bad); }
307
+ .wf-tl-text { grid-area: text; display: grid; gap: 1px; min-width: 0; }
308
+ .wf-tl-kind { font-size: 10.5px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-faint); }
309
+ .wf-tl-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
310
+ .wf-tl-step.is-bad .wf-tl-title { color: var(--bad); }
311
+ .wf-tl-meta { font-size: 12px; color: var(--ink-muted); }
312
+ .wf-tl-time { grid-area: time; display: grid; justify-items: end; font-family: var(--font-mono); font-size: 11.5px; color: var(--ink-muted); }
313
+ .wf-tl-bar { grid-area: bar; position: relative; height: 4px; border-radius: 2px; background: var(--surface-2); margin-top: 4px; }
314
+ .wf-tl-bar span { position: absolute; top: 0; bottom: 0; border-radius: 2px; background: var(--ink-faint); }
315
+ .wf-tl-step.k-model .wf-tl-bar span { background: var(--accent); }
316
+ .wf-tl-step.k-tool .wf-tl-bar span { background: var(--good); }
317
+ .wf-tl-step.is-bad .wf-tl-bar span { background: var(--bad); }
318
+ .wf-tl-detail { position: sticky; top: 12px; display: grid; gap: 12px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); min-width: 0; }
319
+ .wf-tl-detail-head { display: grid; gap: 2px; }
320
+ .wf-tl-detail-head strong { font-size: 14px; overflow-wrap: anywhere; }
321
+ @media (max-width: 860px) { .wf-tl-wrap, .wf-xd-io { grid-template-columns: minmax(0, 1fr); } .wf-tl-detail { position: static; } }
322
+ .wf-versions { display: grid; gap: 10px; font-size: 13px; }
323
+ .wf-version-cards { margin: 0; padding: 0; list-style: none; display: grid; gap: 10px; }
324
+ .wf-version-card { display: grid; gap: 8px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); min-width: 0; }
325
+ .wf-version-card.is-current { border-color: var(--accent); }
326
+ .wf-version-head { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; }
327
+ .wf-version-head strong { font-size: 14px; }
328
+ .wf-version-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
329
+ .wf-version-actions button { height: 28px; padding: 0 10px; border-radius: 8px; font-size: 12.5px; font-weight: 600; border: 1px solid var(--line); background: var(--bg); color: var(--ink); }
330
+ .wf-version-actions button[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-ink); }
331
+ .wf-version-actions .wf-version-restore { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-ink); }
332
+ .wf-version-reason { margin: 0; color: var(--ink-muted); }
333
+ .wf-version-text[hidden], .wf-version-diff[hidden] { display: none; }
334
+ .wf-version-diff { margin: 0; }
335
+ .wf-version-diff .chg-lines { margin: 0; max-height: 480px; overflow: auto; }
336
+ .chg-same { color: var(--ink-muted); padding: 1px 6px; }
337
+ .chg-gap { color: var(--ink-faint); font-family: var(--font-sans, inherit); font-style: italic; padding: 2px 6px; }
266
338
  .wf-crit-form { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); }
267
339
  .wf-crit-form[hidden] { display: none; }
268
340
  .wf-crit-row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 180px auto; gap: 8px; align-items: center; }
@@ -1029,9 +1101,9 @@ ${renderMarkdownScript}
1029
1101
  // Activity now, Improve is Evaluation.
1030
1102
  var OLD_TABS = { evidence: 'activity', changes: 'activity', audit: 'activity', improve: 'evaluation' };
1031
1103
  if (workflowPageId && pageParams.get('wtab')) workflowTabs[workflowPageId] = OLD_TABS[pageParams.get('wtab')] || pageParams.get('wtab');
1032
- // A case's page, with a back link to here.
1033
- function caseHref(runId) {
1034
- return '/cases/' + encodeURIComponent(runId) + '?back=' + encodeURIComponent(location.pathname + location.search);
1104
+ // A run's conversation in the Inbox.
1105
+ function inboxHref(runId) {
1106
+ return '/inbox?item=' + encodeURIComponent(runId);
1035
1107
  }
1036
1108
 
1037
1109
  function workflowPageHref(agent, id, tab) {
@@ -1131,8 +1203,8 @@ ${renderMarkdownScript}
1131
1203
  if (!box) return;
1132
1204
  fetch(base + '/health', { headers: { accept: 'application/json' } })
1133
1205
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1134
- .then(function (h) { box.innerHTML = '<h4 class="wf-sub">At a glance</h4>' + workflowHealthHtml(h); })
1135
- .catch(function (err) { box.innerHTML = '<h4 class="wf-sub">Health</h4><p class="error">Could not load it: ' + escapeHtml(err.message) + '</p>'; });
1206
+ .then(function (h) { box.innerHTML = '<div class="wf-sub-row"><h4 class="wf-sub">Execution history</h4><span class="hint">Last ' + h.days + ' days</span></div>' + workflowHealthHtml(h); })
1207
+ .catch(function (err) { box.innerHTML = '<h4 class="wf-sub">Execution history</h4><p class="error">Could not load it: ' + escapeHtml(err.message) + '</p>'; });
1136
1208
  }
1137
1209
 
1138
1210
  function healthPct(part, whole) { return whole ? Math.round(100 * part / whole) + '%' : String.fromCharCode(8212); }
@@ -1184,38 +1256,6 @@ ${renderMarkdownScript}
1184
1256
  '<details class="wf-health-more"><summary>By version of its instructions</summary><div class="wf-health-table"><table><thead><tr><th>Version</th><th>Runs</th><th>Failed</th><th>Approved</th><th>Changed or denied</th><th>Questions per run</th><th>Used unedited</th><th>Time</th><th>Cost per run</th></tr></thead><tbody>' + rows + '</tbody></table></div></details>';
1185
1257
  }
1186
1258
 
1187
- // The Activity tab's summary: the workflow's last 30 days in sentences, the
1188
- // same as the Audit page's.
1189
- function loadAuditSummary(card, base) {
1190
- var box = card.querySelector('.wf-audit-summary');
1191
- if (!box) return;
1192
- fetch(base + '/audit', { headers: { accept: 'application/json' } })
1193
- .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1194
- .then(function (a) { box.innerHTML = '<h4 class="wf-sub">In the last 30 days</h4><ul class="wf-audit-lines">' + a.summary.map(function (line) { return '<li>' + escapeHtml(line) + '</li>'; }).join('') + '</ul>'; })
1195
- .catch(function (err) { box.innerHTML = '<p class="error">Could not load its summary: ' + escapeHtml(err.message) + '</p>'; });
1196
- }
1197
-
1198
- // The Activity tab's latest few settings changes, with what changed.
1199
- function loadLatestChanges(card, name) {
1200
- var box = card.querySelector('.wf-changes-latest');
1201
- if (!box) return;
1202
- fetch('/audit?agent=' + encodeURIComponent(name) + '&workflow=' + encodeURIComponent(card.dataset.workflow) + '&kind=change&limit=3', { headers: { accept: 'application/json' } })
1203
- .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1204
- .then(function (data) { box.innerHTML = (data.events || []).length ? workflowChangesHtml(data.events) : '<p class="hint" style="margin:0">No settings changed yet.</p>'; })
1205
- .catch(function (err) { box.innerHTML = '<p class="error">Could not load its changes: ' + escapeHtml(err.message) + '</p>'; });
1206
- }
1207
-
1208
- // A list of changes (and decisions): every change to this workflow's settings, and every
1209
- // decision, answer and feedback in its runs, newest first, with who.
1210
- function changeText(e) {
1211
- var d = e.data || {};
1212
- if (e.kind === 'change') return escapeHtml(d.label || 'Changed a setting');
1213
- if (e.kind === 'decision') return (d.approved ? (d.edited ? 'Approved as changed ' : 'Approved ') : 'Denied ') + '<code>' + escapeHtml(d.tool || '') + '</code>' + (d.reason ? ': ' + String.fromCharCode(8220) + escapeHtml(d.reason) + String.fromCharCode(8221) : '');
1214
- if (e.kind === 'answer') return 'Answered ' + String.fromCharCode(8220) + escapeHtml(String(d.answer || '').slice(0, 200)) + String.fromCharCode(8221);
1215
- if (e.kind === 'feedback') return 'Feedback: ' + escapeHtml([d.verdict, d.edit ? (d.edit === 'none' ? 'used unedited' : d.edit + ' edits') : '', d.note].filter(Boolean).join(', ') || 'given');
1216
- return escapeHtml(e.kind);
1217
- }
1218
-
1219
1259
  // A change's details: each setting from and to, and for long texts the
1220
1260
  // lines added (+) and removed (−), a few shown and the rest folded.
1221
1261
  function changeDetailsHtml(d) {
@@ -1239,17 +1279,6 @@ ${renderMarkdownScript}
1239
1279
  return '<div class="chg">' + rows + '</div>';
1240
1280
  }
1241
1281
 
1242
- function workflowChangesHtml(events) {
1243
- if (!events.length) return '<p class="hint" style="margin:0">Nothing yet. Edits to this workflow' + RSQ + 's settings, and every approval, answer and feedback in its runs, will be listed here with who and when.</p>';
1244
- return '<ol class="wf-change-list">' + events.map(function (e) {
1245
- var when = new Date(e.at).toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' });
1246
- var kind = e.kind === 'change' ? 'Setting' : e.kind === 'decision' ? 'Decision' : e.kind === 'answer' ? 'Answer' : 'Feedback';
1247
- return '<li><span class="wf-change-kind ' + escapeHtml(e.kind) + '">' + kind + '</span><span class="wf-change-text">' + changeText(e) + (e.kind === 'change' ? changeDetailsHtml(e.data || {}) : '') + '</span>' +
1248
- '<span class="hint">' + (e.by ? escapeHtml(e.by) + DOT : '') + escapeHtml(when) +
1249
- (e.run_id ? DOT + '<a href="' + caseHref(e.run_id) + '">case</a>' : '') + '</span></li>';
1250
- }).join('') + '</ol>';
1251
- }
1252
-
1253
1282
  // ---- A workflow in three parts: its contract (what the system holds it
1254
1283
  // to: how it starts, its inputs, lookups, tools, model and result), its
1255
1284
  // brief (what the agent reads) and its evidence (how it's doing). ----
@@ -1415,9 +1444,7 @@ ${renderMarkdownScript}
1415
1444
 
1416
1445
  function workflowBriefHtml(w) {
1417
1446
  var policies = workflowsMeta.policies;
1418
- // Filled by loadWorkflowVersions once the card is on the page.
1419
- return '<div class="wf-versions" hidden></div>' +
1420
- '<div class="workflow-steps-text">' + escapeHtml(w.instructions) + '</div>' +
1447
+ return '<div class="workflow-steps-text">' + escapeHtml(w.instructions) + '</div>' +
1421
1448
  (policies
1422
1449
  ? '<details class="wf-original"><summary>Shared policies, read by every workflow</summary><div class="workflow-steps-text">' + escapeHtml(policies) + '</div><p class="hint" style="margin:6px 0 0">Change them in <a href="/config?section=settings">Settings</a>.</p></details>'
1423
1450
  : '<p class="hint" style="margin:0">No shared policies yet. Rules every workflow should follow, like your refund window or who signs messages, go in <a href="/config?section=settings">Settings</a>, so you write them once.</p>') +
@@ -1448,18 +1475,363 @@ ${renderMarkdownScript}
1448
1475
  }
1449
1476
  var REFERENCE_CRIT = { id: 'reference', text: 'Matches the good result: the same facts and decisions', kind: 'reference' };
1450
1477
 
1451
- // The Activity tab: what happened and whether it can be trusted. The same
1452
- // summary as the Audit page's, its health over 30 days, its latest runs
1453
- // and changes, and the way to the report and the full log.
1478
+ // The Activity tab: its execution history over the last 30 days (runs
1479
+ // per day, failures, approvals, time and cost), then its runs, each a
1480
+ // card with the workflow version it ran and View trace. A trace takes
1481
+ // the tab's place: the run's execution details, then its execution
1482
+ // trace, step by step (see workflowTraceHtml).
1454
1483
  function workflowActivityHtml(w, runsHtml, name) {
1455
- var auditHref = '/audit?agent=' + encodeURIComponent(name) + '&workflow=' + encodeURIComponent(w.id);
1484
+ if (!workflowPageId) {
1485
+ return '<section class="wf-section"><h4 class="wf-sub">Latest runs</h4>' +
1486
+ (runsHtml ? '<ul class="wf-run-lines">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>') + '</section>';
1487
+ }
1456
1488
  var loading = '<p class="hint" style="margin:0">Loading' + String.fromCharCode(8230) + '</p>';
1457
- return (workflowPageId ? '<section class="wf-section wf-audit-summary">' + loading + '</section>' : '') +
1458
- (workflowPageId ? '<section class="wf-section wf-health">' + loading + '</section>' : '') +
1459
- '<section class="wf-section"><h4 class="wf-sub">Latest runs</h4>' +
1460
- (runsHtml ? '<ul class="wf-run-lines">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>') + '</section>' +
1461
- (workflowPageId ? '<section class="wf-section"><h4 class="wf-sub">Latest changes</h4><div class="wf-changes-latest">' + loading + '</div></section>' : '') +
1462
- (workflowPageId ? '<section class="wf-section"><div class="wf-audit-tools"><a class="primary" href="/agents/' + encodeURIComponent(name) + '/workflows/' + encodeURIComponent(w.id) + '/audit/report">Open the report</a><a href="' + auditHref + '">See everything in Audit ' + String.fromCharCode(8594) + '</a></div></section>' : '');
1489
+ var auditHref = '/audit?agent=' + encodeURIComponent(name) + '&workflow=' + encodeURIComponent(w.id);
1490
+ return '<div class="wf-act-main">' +
1491
+ '<section class="wf-section wf-health">' + loading + '</section>' +
1492
+ '<section class="wf-section"><div class="wf-sub-row"><h4 class="wf-sub">Runs</h4><span class="hint wf-runs-count"></span></div><div class="wf-runs">' + loading + '</div></section>' +
1493
+ '<section class="wf-section"><div class="wf-audit-tools"><a href="/agents/' + encodeURIComponent(name) + '/workflows/' + encodeURIComponent(w.id) + '/audit/report">Open the report</a><a href="' + auditHref + '">Who changed it, in Audit ' + String.fromCharCode(8594) + '</a></div></section>' +
1494
+ '</div>' +
1495
+ '<div class="wf-trace" hidden></div>';
1496
+ }
1497
+
1498
+ var RUN_PILLS = { done: ['good', 'Done'], error: ['bad', 'Failed'], awaiting_approval: ['ask', 'Waiting'], running: ['accent', 'Running'] };
1499
+ var RUN_SOURCES = { console: 'Run now', api: 'API', schedule: 'Schedule', webhook: 'Webhook', assignment: 'Assigned', chain: 'Another workflow' };
1500
+ function runPillHtml(status) {
1501
+ var p = RUN_PILLS[status] || ['', status];
1502
+ return '<span class="le-pill ' + p[0] + '">' + p[1] + '</span>';
1503
+ }
1504
+ function runWhen(iso) {
1505
+ return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
1506
+ }
1507
+ function runVersionOf(r) {
1508
+ return r.versions ? (r.versions.workflow || r.versions.brief || null) : null;
1509
+ }
1510
+
1511
+ // Its runs, newest first (the latest 50), each a card.
1512
+ function loadWorkflowRuns(name, card, base) {
1513
+ var box = card.querySelector('.wf-runs');
1514
+ if (!box) return;
1515
+ var w = workflowsById[card.dataset.workflow];
1516
+ fetch(base + '/runs', { headers: { accept: 'application/json' } })
1517
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1518
+ .then(function (data) {
1519
+ var runs = data.runs || [];
1520
+ var count = card.querySelector('.wf-runs-count');
1521
+ if (count) count.textContent = runs.length >= 50 ? 'Latest 50' : runs.length ? runs.length + ' run' + (runs.length === 1 ? '' : 's') : '';
1522
+ box.innerHTML = runs.length ? '<ol class="wf-run-cards">' + runs.map(function (r) { return runCardHtml(w, r); }).join('') + '</ol>'
1523
+ : '<p class="hint" style="margin:0">No runs yet. Start one from Triggers (Run now), an app, a schedule or a webhook.</p>';
1524
+ })
1525
+ .catch(function (err) { box.innerHTML = '<p class="error">Could not load its runs: ' + escapeHtml(err.message) + '</p>'; });
1526
+ box.addEventListener('click', function (ev) {
1527
+ var b = ev.target.closest('.wf-run-trace');
1528
+ if (!b) return;
1529
+ openRunTrace(name, card, b.getAttribute('data-run'));
1530
+ });
1531
+ }
1532
+
1533
+ function runCardHtml(w, r) {
1534
+ var version = runVersionOf(r);
1535
+ var values = r.params ? Object.keys(r.params).map(function (k) { return k + ': ' + r.params[k]; }).join(DOT) : '';
1536
+ var outcome = r.status === 'error' ? (r.error || '') : (r.result || '');
1537
+ var took = r.finished_at ? healthTime(Date.parse(r.finished_at) - Date.parse(r.started_at)) : '';
1538
+ return '<li class="wf-run-card' + (r.status === 'error' ? ' is-failed' : '') + '">' +
1539
+ '<div class="wf-run-card-head">' + runPillHtml(r.status) +
1540
+ '<strong>' + escapeHtml(runWhen(r.started_at)) + '</strong>' +
1541
+ (version ? '<span class="wf-run-version" title="The workflow version it ran">v' + version + '</span>' : '<span class="hint">before versions</span>') +
1542
+ '<span class="hint">' + escapeHtml(RUN_SOURCES[r.source] || r.source || '') + (took ? DOT + escapeHtml(took) : '') + '</span>' +
1543
+ '<span class="wf-run-card-actions"><a class="wf-link" href="' + inboxHref(r.run_id) + '">Open in Inbox</a><button type="button" class="wf-run-trace" data-run="' + escapeHtml(r.run_id) + '">View trace</button></span>' +
1544
+ '</div>' +
1545
+ (values ? '<div class="wf-run-card-inputs">' + escapeHtml(values.length > 200 ? values.slice(0, 200) + String.fromCharCode(8230) : values) + '</div>' : '') +
1546
+ (outcome ? '<div class="wf-run-card-out' + (r.status === 'error' ? ' error' : '') + '">' + escapeHtml(outcome.length > 280 ? outcome.slice(0, 280) + String.fromCharCode(8230) : outcome) + '</div>' : '') +
1547
+ runEvidenceHtml(w || {}, r) +
1548
+ '</li>';
1549
+ }
1550
+
1551
+ // The run whose trace is open on each workflow's page, and its step, so
1552
+ // a redraw (a running run refreshing) keeps it open.
1553
+ var openTraces = {};
1554
+ if (workflowPageId && pageParams.get('run')) openTraces[workflowPageId] = { run: pageParams.get('run'), step: null };
1555
+
1556
+ function setRunParam(runId) {
1557
+ var q = new URLSearchParams(location.search);
1558
+ if (runId) { q.set('run', runId); q.set('wtab', 'activity'); } else q.delete('run');
1559
+ history.replaceState(null, '', location.pathname + '?' + q.toString());
1560
+ }
1561
+
1562
+ function openRunTrace(name, card, runId) {
1563
+ var id = card.dataset.workflow;
1564
+ var prev = openTraces[id];
1565
+ openTraces[id] = { run: runId, step: prev && prev.run === runId ? prev.step : null };
1566
+ setRunParam(runId);
1567
+ var main = card.querySelector('.wf-act-main');
1568
+ var box = card.querySelector('.wf-trace');
1569
+ if (!main || !box) return;
1570
+ main.hidden = true;
1571
+ box.hidden = false;
1572
+ if (!box.innerHTML) box.innerHTML = '<p class="hint">Loading the trace' + String.fromCharCode(8230) + '</p>';
1573
+ fetch('/agents/' + encodeURIComponent(name) + '/runs/' + encodeURIComponent(runId) + '/trace', { headers: { accept: 'application/json' } })
1574
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1575
+ .then(function (t) {
1576
+ if (!openTraces[id] || openTraces[id].run !== runId) return;
1577
+ box.innerHTML = workflowTraceHtml(name, t);
1578
+ wireTrace(name, card, box, t);
1579
+ })
1580
+ .catch(function (err) {
1581
+ box.innerHTML = traceBarHtml(name, runId) + '<p class="error">Could not load the trace: ' + escapeHtml(err.message) + '</p>';
1582
+ wireTrace(name, card, box, null);
1583
+ });
1584
+ }
1585
+
1586
+ function closeRunTrace(card) {
1587
+ delete openTraces[card.dataset.workflow];
1588
+ setRunParam(null);
1589
+ var main = card.querySelector('.wf-act-main');
1590
+ var box = card.querySelector('.wf-trace');
1591
+ if (box) { box.hidden = true; box.innerHTML = ''; }
1592
+ if (main) main.hidden = false;
1593
+ }
1594
+
1595
+ // Back to the runs; the run's conversation in the Inbox; its record (the
1596
+ // run, every event in it, its trace, and the workflow version and
1597
+ // policies it ran under) or just its trace, as a file; and, for a run
1598
+ // that finished, saving it as an eval case.
1599
+ function traceBarHtml(name, runId, t) {
1600
+ return '<div class="wf-trace-bar"><button type="button" class="wf-link wf-trace-back">' + String.fromCharCode(8592) + ' All runs</button>' +
1601
+ '<span style="flex:1"></span><a class="wf-link" href="' + inboxHref(runId) + '">Open in Inbox</a>' +
1602
+ '<a class="wf-link" href="/inbox/cases/' + encodeURIComponent(runId) + '/export" download>Download record</a>' +
1603
+ '<a class="wf-link" href="/agents/' + encodeURIComponent(name) + '/runs/' + encodeURIComponent(runId) + '/trace" download="trace-' + escapeHtml(runId) + '.json">Download trace</a>' +
1604
+ (t && t.status === 'done' ? '<button type="button" class="wf-trace-save-case">Save as eval case</button>' : '') + '</div>' +
1605
+ '<div class="wf-trace-case" hidden></div>';
1606
+ }
1607
+
1608
+ var STEP_KINDS = {
1609
+ start: ['Run started', 'start'], end: ['Run finished', 'end'], prompt: ['Prompt', 'prompt'], model_call: ['Model call', 'model'],
1610
+ tool_call: ['Tool call', 'tool'], decision: ['Approval', 'person'], answer: ['Answer', 'person'], feedback: ['Feedback', 'person'],
1611
+ };
1612
+ function traceMs(ms) {
1613
+ if (ms == null) return String.fromCharCode(8212);
1614
+ if (ms < 1000) return Math.round(ms) + ' ms';
1615
+ return healthTime(ms);
1616
+ }
1617
+ function traceTokens(n) { return n == null ? String.fromCharCode(8212) : Number(n).toLocaleString(); }
1618
+
1619
+ // The steps from start to end: the run starting (its input), each step
1620
+ // the trace kept, and the run ending (its output or error).
1621
+ function traceSteps(t) {
1622
+ var steps = [{ type: 'start', at: t.started_at, input: t.input }].concat(t.step_events || []);
1623
+ if (t.finished_at) steps.push({ type: 'end', at: t.finished_at, status: t.status, output: t.final_output_json != null ? t.final_output_json : t.final_output, error: t.error });
1624
+ return steps;
1625
+ }
1626
+
1627
+ function stepTitle(s, t) {
1628
+ if (s.type === 'tool_call') return s.name;
1629
+ if (s.type === 'model_call') return s.model || (t.model && t.model.model) || 'Model';
1630
+ if (s.type === 'decision') return (s.approved ? (s.changed ? 'Approved as changed: ' : 'Approved: ') : 'Denied: ') + s.tool;
1631
+ if (s.type === 'answer') return s.question;
1632
+ if (s.type === 'feedback') return [s.verdict, s.edit ? (s.edit === 'none' ? 'used unedited' : s.edit + ' edits') : ''].filter(Boolean).join(', ') || 'Given';
1633
+ if (s.type === 'prompt') return s.resumed ? 'Resumed' : 'System prompt, tools and input';
1634
+ if (s.type === 'end') return s.status === 'error' ? 'Failed' : s.status === 'done' ? 'Done' : s.status;
1635
+ return RUN_SOURCES[t.source] || 'Started';
1636
+ }
1637
+ function stepFailed(s) {
1638
+ return Boolean(s.error) || (s.type === 'decision' && !s.approved) || (s.type === 'end' && s.status === 'error') || (s.type === 'tool_call' && /denied|error|fail/i.test(s.status || ''));
1639
+ }
1640
+
1641
+ function workflowTraceHtml(name, t) {
1642
+ var steps = traceSteps(t);
1643
+ var start = Date.parse(t.started_at);
1644
+ var end = t.finished_at ? Date.parse(t.finished_at) : start;
1645
+ steps.forEach(function (s) { var e = Date.parse(s.at) + (s.duration_ms || 0); if (e > end) end = e; });
1646
+ var total = Math.max(1, end - start);
1647
+ var cost = t.cost || {};
1648
+ // Its model calls as the trace kept them, where usage wasn't recorded.
1649
+ var calls = (t.step_events || []).filter(function (s) { return s.type === 'model_call'; });
1650
+ var sum = function (k) { return calls.reduce(function (n, s) { return n + (s[k] || 0); }, 0); };
1651
+ var tokensIn = cost.input_tokens || sum('input_tokens');
1652
+ var tokensOut = cost.output_tokens || sum('output_tokens');
1653
+ var item = function (k, v) { return '<div class="wf-xd-item"><dt>' + k + '</dt><dd>' + v + '</dd></div>'; };
1654
+ var params = Object.keys((t.input && t.input.params) || {});
1655
+ var details = '<section class="wf-section wf-xd">' +
1656
+ '<div class="wf-xd-head">' + runPillHtml(t.status) + '<h3>Run <code>' + escapeHtml(String(t.execution_id).slice(0, 8)) + '</code></h3>' +
1657
+ (t.workflow_version ? '<span class="wf-run-version">v' + t.workflow_version + '</span>' : '') + '</div>' +
1658
+ '<h4 class="wf-sub">Execution details</h4>' +
1659
+ '<dl class="wf-xd-grid">' +
1660
+ item('Status', escapeHtml((RUN_PILLS[t.status] || [0, t.status])[1])) +
1661
+ item('Started by', escapeHtml(RUN_SOURCES[t.source] || t.source || String.fromCharCode(8212))) +
1662
+ item('Workflow version', t.workflow_version ? '<a href="#" class="wf-xd-version" data-version="' + t.workflow_version + '">v' + t.workflow_version + '</a>' : '<span class="hint">before versions</span>') +
1663
+ item('Started', escapeHtml(new Date(t.started_at).toLocaleString())) +
1664
+ item('Finished', t.finished_at ? escapeHtml(new Date(t.finished_at).toLocaleString()) : '<span class="hint">not yet</span>') +
1665
+ item('Duration', escapeHtml(traceMs(t.duration_ms))) +
1666
+ item('Model', t.model ? escapeHtml((t.model.provider ? t.model.provider + ' ' : '') + t.model.model) : String.fromCharCode(8212)) +
1667
+ item('Steps', String(steps.length - (t.finished_at ? 2 : 1)) + ' <span class="hint">' + calls.length + ' model, ' + (t.tool_calls || []).length + ' tool</span>') +
1668
+ item('Tokens', traceTokens(tokensIn) + ' in' + DOT + traceTokens(tokensOut) + ' out') +
1669
+ item('Cost', escapeHtml(healthCost(cost.usd))) +
1670
+ item('Execution ID', '<code>' + escapeHtml(t.execution_id) + '</code>') +
1671
+ '</dl>' +
1672
+ (t.error ? '<div class="wf-xd-error" role="alert"><strong>Error</strong> ' + escapeHtml(t.error) + '</div>' : '') +
1673
+ '<div class="wf-xd-io">' +
1674
+ '<div><div class="wf-xd-k">Input</div>' + (params.length
1675
+ ? '<dl class="wf-xd-params">' + params.map(function (k) { return '<dt>' + escapeHtml(k) + '</dt><dd>' + escapeHtml(t.input.params[k]) + '</dd>'; }).join('') + '</dl>'
1676
+ : '<p class="hint" style="margin:0">No inputs</p>') + '</div>' +
1677
+ '<div><div class="wf-xd-k">Output</div>' + (t.final_output_json != null || t.final_output
1678
+ ? '<pre class="wf-tv-pre">' + escapeHtml(traceValueText(t.final_output_json != null ? t.final_output_json : t.final_output)) + '</pre>'
1679
+ : '<p class="hint" style="margin:0">' + (t.status === 'error' ? 'None: it failed' : 'None yet') + '</p>') +
1680
+ (t.output_schema_check && t.output_schema_check.valid === false ? '<p class="error" style="margin:4px 0 0">Didn' + RSQ + 't match the output schema: ' + escapeHtml((t.output_schema_check.errors || []).join('; ')) + '</p>' : '') +
1681
+ '</div>' +
1682
+ '</div>' +
1683
+ '</section>';
1684
+ var rows = steps.map(function (s, i) {
1685
+ var kind = STEP_KINDS[s.type] || [s.type, 'other'];
1686
+ var at = Date.parse(s.at);
1687
+ var left = Math.min(100, Math.max(0, (at - start) / total * 100));
1688
+ var width = s.duration_ms ? Math.max(0.6, Math.min(100 - left, s.duration_ms / total * 100)) : 0;
1689
+ var meta = s.type === 'model_call' ? traceTokens(s.input_tokens) + ' / ' + traceTokens(s.output_tokens) + ' tokens'
1690
+ : s.type === 'tool_call' ? (s.status || '')
1691
+ : s.by ? s.by : '';
1692
+ return '<li><button type="button" class="wf-tl-step k-' + kind[1] + (stepFailed(s) ? ' is-bad' : '') + '" data-step="' + i + '" aria-pressed="false">' +
1693
+ '<span class="wf-tl-dot" aria-hidden="true"></span>' +
1694
+ '<span class="wf-tl-text"><span class="wf-tl-kind">' + kind[0] + '</span><span class="wf-tl-title">' + escapeHtml(stepTitle(s, t)) + '</span>' +
1695
+ (meta ? '<span class="wf-tl-meta">' + escapeHtml(meta) + '</span>' : '') + '</span>' +
1696
+ '<span class="wf-tl-time"><span>+' + escapeHtml(traceMs(at - start)) + '</span>' + (s.duration_ms != null ? '<span class="hint">' + escapeHtml(traceMs(s.duration_ms)) + '</span>' : '') + '</span>' +
1697
+ '<span class="wf-tl-bar" aria-hidden="true"><span style="left:' + left.toFixed(2) + '%;width:' + (width ? width.toFixed(2) + '%' : '2px') + '"></span></span>' +
1698
+ '</button></li>';
1699
+ }).join('');
1700
+ return traceBarHtml(name, t.execution_id, t) + details +
1701
+ '<section class="wf-section"><div class="wf-sub-row"><h4 class="wf-sub">Execution trace</h4><span class="hint">' + steps.length + ' steps' + DOT + 'click one for its details</span></div>' +
1702
+ '<div class="wf-tl-wrap"><ol class="wf-tl">' + rows + '</ol><div class="wf-tl-detail" aria-live="polite"></div></div>' +
1703
+ '</section>';
1704
+ }
1705
+
1706
+ // A value as text: a string as it is; model messages and replies as
1707
+ // what each said (its text, the tools it called, what they returned);
1708
+ // anything else as JSON.
1709
+ function blockText(b) {
1710
+ if (!b || typeof b !== 'object') return String(b);
1711
+ if (b.type === 'text') return b.text || '';
1712
+ if (b.type === 'tool_use') return String.fromCharCode(8594) + ' ' + b.name + ' ' + JSON.stringify(b.input || {}, null, 2);
1713
+ if (b.type === 'tool_result') return String.fromCharCode(8592) + ' result' + (b.is_error ? ' (error)' : '') + ': ' + (typeof b.content === 'string' ? b.content : Array.isArray(b.content) ? b.content.map(blockText).join(String.fromCharCode(10)) : JSON.stringify(b.content, null, 2));
1714
+ return JSON.stringify(b, null, 2);
1715
+ }
1716
+ function traceValueText(v) {
1717
+ var NL = String.fromCharCode(10);
1718
+ if (v == null) return '';
1719
+ // A tool's JSON reply, laid out.
1720
+ if (typeof v === 'string' && /^[[{]/.test(v.trim())) {
1721
+ try { return JSON.stringify(JSON.parse(v), null, 2); } catch (e) { return v; }
1722
+ }
1723
+ if (typeof v === 'string') return v;
1724
+ if (Array.isArray(v) && v.length && v.every(function (m) { return m && typeof m === 'object' && m.role; })) {
1725
+ return v.map(function (m) { return '[' + m.role + ']' + NL + (typeof m.content === 'string' ? m.content : (m.content || []).map(blockText).join(NL)); }).join(NL + NL);
1726
+ }
1727
+ if (Array.isArray(v) && v.length && v.every(function (b) { return b && typeof b === 'object' && b.type; })) return v.map(blockText).join(NL);
1728
+ return JSON.stringify(v, null, 2);
1729
+ }
1730
+
1731
+ // A step's details: what it was (tool, model, status, who), how long it
1732
+ // took and its tokens, any error, then its input and output in full.
1733
+ function stepDetailHtml(s, t) {
1734
+ var start = Date.parse(t.started_at);
1735
+ var kind = STEP_KINDS[s.type] || [s.type];
1736
+ var rows = [];
1737
+ var row = function (k, v) { rows.push('<div class="wf-xd-item"><dt>' + k + '</dt><dd>' + v + '</dd></div>'); };
1738
+ var block = function (k, v) { return v == null || v === '' ? '' : '<div class="wf-tv-block"><div class="wf-xd-k">' + k + '</div><pre class="wf-tv-pre">' + escapeHtml(traceValueText(v)) + '</pre></div>'; };
1739
+ if (s.type === 'tool_call') { row('Tool', '<code>' + escapeHtml(s.name) + '</code>'); if (s.status) row('Status', escapeHtml(s.status)); }
1740
+ if (s.type === 'model_call') {
1741
+ row('Model', escapeHtml(s.model || (t.model && t.model.model) || String.fromCharCode(8212)));
1742
+ row('Tokens', traceTokens(s.input_tokens) + ' in' + DOT + traceTokens(s.output_tokens) + ' out');
1743
+ if (s.stop_reason) row('Stop reason', escapeHtml(s.stop_reason));
1744
+ if (s.messages_sent != null) row('Messages sent', String(s.messages_sent));
1745
+ }
1746
+ if (s.type === 'prompt') { if (t.model) row('Model', escapeHtml((t.model.provider ? t.model.provider + ' ' : '') + t.model.model)); row('Tools offered', (s.tools || []).length ? s.tools.map(function (x) { return '<code>' + escapeHtml(x) + '</code>'; }).join(', ') : 'none'); if (s.prior_messages) row('Earlier messages', String(s.prior_messages)); }
1747
+ if (s.type === 'decision') { row('Tool', '<code>' + escapeHtml(s.tool) + '</code>'); row('Decision', s.approved ? (s.changed ? 'Approved as changed' : 'Approved') : 'Denied'); }
1748
+ if (s.by) row('By', escapeHtml(s.by));
1749
+ if (s.type === 'start') row('Started by', escapeHtml(RUN_SOURCES[t.source] || t.source || ''));
1750
+ row('At', escapeHtml(new Date(s.at).toLocaleTimeString()) + ' <span class="hint">+' + escapeHtml(traceMs(Date.parse(s.at) - start)) + '</span>');
1751
+ if (s.duration_ms != null || s.type === 'model_call' || s.type === 'tool_call') row('Duration', escapeHtml(traceMs(s.duration_ms)));
1752
+ if (s.type === 'end') row('Total', escapeHtml(traceMs(t.duration_ms)));
1753
+ var io = '';
1754
+ if (s.type === 'start') io = block('Input', s.input && Object.keys(s.input.params || {}).length ? s.input.params : null) + block('Message', s.input && s.input.message);
1755
+ else if (s.type === 'prompt') io = block('Input', s.input) + (s.system ? '<details class="wf-tv-block"><summary>System prompt</summary><pre class="wf-tv-pre">' + escapeHtml(s.system) + '</pre></details>' : '');
1756
+ else if (s.type === 'model_call' || s.type === 'tool_call') io = block('Input', s.input) + block('Output', s.output);
1757
+ else if (s.type === 'decision') io = block('Reason', s.reason);
1758
+ else if (s.type === 'answer') io = block('Question', s.question) + block('Answer', s.answer);
1759
+ else if (s.type === 'feedback') io = block('Note', s.note);
1760
+ else if (s.type === 'end') io = block('Output', s.output);
1761
+ return '<div class="wf-tl-detail-head"><span class="wf-tl-kind">' + kind[0] + '</span><strong>' + escapeHtml(stepTitle(s, t)) + '</strong></div>' +
1762
+ (s.error ? '<div class="wf-xd-error" role="alert"><strong>Error</strong> ' + escapeHtml(s.error) + '</div>' : '') +
1763
+ '<dl class="wf-xd-grid">' + rows.join('') + '</dl>' + io;
1764
+ }
1765
+
1766
+ // Save as eval case, from a trace: the run becomes a test its workflow
1767
+ // must keep passing; then success criteria suggested from what people
1768
+ // corrected in it, each added to the workflow's draft.
1769
+ function wireTraceEvalCase(name, card, box, t) {
1770
+ var btn = box.querySelector('.wf-trace-save-case');
1771
+ if (!btn) return;
1772
+ var id = card.dataset.workflow;
1773
+ var base = '/agents/' + encodeURIComponent(name) + '/workflows/' + encodeURIComponent(id);
1774
+ var panel = box.querySelector('.wf-trace-case');
1775
+ var w = workflowsById[id];
1776
+ var saved = function () { btn.disabled = true; btn.textContent = 'Saved as an eval case'; };
1777
+ if (w && w.evals && (w.evals.cases || []).some(function (k) { return k.fromRun === t.execution_id; })) saved();
1778
+ btn.addEventListener('click', function () {
1779
+ btn.disabled = true;
1780
+ panel.hidden = false;
1781
+ panel.innerHTML = '<p class="hint" style="margin:0">Saving' + String.fromCharCode(8230) + '</p>';
1782
+ fetchJsonRetryOnce(base + '/evals/cases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: t.execution_id }) }).then(function (r) {
1783
+ if (!r.ok) { btn.disabled = false; panel.innerHTML = '<p class="error">' + escapeHtml(r.body.error || 'Could not save it') + '</p>'; return; }
1784
+ saved();
1785
+ if (w && w.evals) w.evals.cases = (w.evals.cases || []).concat([{ fromRun: t.execution_id }]);
1786
+ var have = (r.body.criteria || []).map(function (k) { return k.text; });
1787
+ var fresh = (r.body.suggestions || []).filter(function (x) { return have.indexOf(x.text) === -1; });
1788
+ panel.innerHTML = '<p style="margin:0"><span class="le-pill good">Saved</span> It' + RSQ + 's one of this workflow' + RSQ + 's eval cases now. <a href="#" class="wf-link wf-trace-evals">See them in Evaluation</a></p>' +
1789
+ (fresh.length ? '<h4 class="wf-sub">Add to its success criteria?</h4><p class="hint" style="margin:0">From what people corrected in this run. Each goes into the draft; publish it to judge every eval case on it.</p>' +
1790
+ '<ul class="wf-trace-suggest">' + fresh.map(function (x, i) { return '<li><span>' + escapeHtml(x.text) + '</span><button type="button" class="wf-link" data-suggest="' + i + '">Add to draft</button></li>'; }).join('') + '</ul>' : '');
1791
+ panel.querySelector('.wf-trace-evals').addEventListener('click', function (ev) { ev.preventDefault(); showWorkflowTab(card, 'evaluation'); });
1792
+ panel.addEventListener('click', function (ev) {
1793
+ var b = ev.target.closest('[data-suggest]');
1794
+ if (!b) return;
1795
+ b.disabled = true;
1796
+ var x = fresh[Number(b.getAttribute('data-suggest'))];
1797
+ // The criteria as drafted, else as published, with this one added.
1798
+ fetchJsonRetryOnce(base + '/draft').then(function (d) {
1799
+ var list = d.ok && d.body.draft && d.body.draft.criteria ? d.body.draft.criteria : ((workflowsById[id] && workflowsById[id].evals && workflowsById[id].evals.criteria) || []);
1800
+ list = list.map(function (k) { return { text: k.text, kind: k.kind, value: k.value }; }).concat([{ text: x.text, kind: x.kind }]);
1801
+ return fetchJsonRetryOnce(base + '/draft/criteria', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ criteria: list }) });
1802
+ }).then(function (p) {
1803
+ if (!p.ok) { b.disabled = false; b.textContent = p.body.error || 'Could not add it'; return; }
1804
+ b.textContent = 'Added to the draft';
1805
+ refreshDraft(name, card);
1806
+ });
1807
+ });
1808
+ });
1809
+ });
1810
+ }
1811
+
1812
+ function wireTrace(name, card, box, t) {
1813
+ var id = card.dataset.workflow;
1814
+ box.querySelector('.wf-trace-back').addEventListener('click', function () { closeRunTrace(card); });
1815
+ if (!t) return;
1816
+ wireTraceEvalCase(name, card, box, t);
1817
+ var steps = traceSteps(t);
1818
+ var detailBox = box.querySelector('.wf-tl-detail');
1819
+ var buttons = box.querySelectorAll('.wf-tl-step');
1820
+ function select(i) {
1821
+ for (var k = 0; k < buttons.length; k++) buttons[k].setAttribute('aria-pressed', String(k === i));
1822
+ detailBox.innerHTML = stepDetailHtml(steps[i], t);
1823
+ if (openTraces[id]) openTraces[id].step = i;
1824
+ }
1825
+ box.querySelector('.wf-tl').addEventListener('click', function (ev) {
1826
+ var b = ev.target.closest('.wf-tl-step');
1827
+ if (b) select(Number(b.getAttribute('data-step')));
1828
+ });
1829
+ // The step open before a redraw, else the first that failed, else the start.
1830
+ var kept = openTraces[id] && openTraces[id].step;
1831
+ var failed = steps.map(stepFailed).indexOf(true);
1832
+ select(kept != null && kept < steps.length ? kept : failed >= 0 ? failed : 0);
1833
+ var v = box.querySelector('.wf-xd-version');
1834
+ if (v) v.addEventListener('click', function (ev) { ev.preventDefault(); showWorkflowTab(card, 'versions'); });
1463
1835
  }
1464
1836
 
1465
1837
  // The Evaluation tab: the success criteria, the eval cases (saved, then
@@ -1552,7 +1924,7 @@ ${renderMarkdownScript}
1552
1924
  // cases, each with why (a person denied or changed what it did, a bad
1553
1925
  // result, a question it asked, a failure, or a typical good run).
1554
1926
  var WHY = { denied: ['bad', 'Denied'], changed: ['ask', 'Changed'], bad: ['bad', 'Bad result'], asked: ['ask', 'Asked'], failed: ['bad', 'Failed'], typical: ['good', 'Typical'] };
1555
- function loadCandidates(card, base) {
1927
+ function loadCandidates(name, card, base) {
1556
1928
  var box = card.querySelector('.wf-candidates');
1557
1929
  if (!box) return;
1558
1930
  fetch(base + '/evals/candidates', { headers: { accept: 'application/json' } })
@@ -1560,15 +1932,24 @@ ${renderMarkdownScript}
1560
1932
  .then(function (data) {
1561
1933
  var list = data.candidates || [];
1562
1934
  if (!list.length) { box.innerHTML = '<p class="hint" style="margin:0">Nothing new to suggest from the last 30 days.</p>'; return; }
1563
- box.innerHTML = '<p class="hint" style="margin:0 0 6px">Runs from the last 30 days worth adding, best first: where a person denied or changed what it did, a bad result, a question it asked, or a typical good run. Open one to read it in full first.</p><ul class="wf-cand-list">' + list.map(function (c) {
1935
+ box.innerHTML = '<p class="hint" style="margin:0 0 6px">Runs from the last 30 days worth adding, best first: where a person denied or changed what it did, a bad result, a question it asked, or a typical good run. Open one' + RSQ + 's trace to read it in full first.</p><ul class="wf-cand-list">' + list.map(function (c) {
1564
1936
  var why = WHY[c.why] || ['', c.why];
1565
1937
  return '<li><span class="le-pill ' + why[0] + '">' + why[1] + '</span>' +
1566
1938
  '<span class="wf-cand-text"><strong>' + escapeHtml(c.detail) + '</strong><span class="hint">' + escapeHtml(new Date(c.at).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })) + (c.inputs ? DOT + escapeHtml(c.inputs) : '') + '</span></span>' +
1567
- '<a class="wf-link" href="' + caseHref(c.runId) + '">Open</a>' +
1939
+ '<a class="wf-link wf-cand-trace" href="' + workflowPageHref(name, card.dataset.workflow, 'activity') + '&run=' + encodeURIComponent(c.runId) + '" data-run="' + escapeHtml(c.runId) + '">Open trace</a>' +
1568
1940
  '<button type="button" class="wf-link wf-save-case" data-run="' + escapeHtml(c.runId) + '">Add as eval case</button></li>';
1569
1941
  }).join('') + '</ul>';
1570
1942
  })
1571
1943
  .catch(function (err) { box.innerHTML = '<p class="error">Could not look through its runs: ' + escapeHtml(err.message) + '</p>'; });
1944
+ // Open trace: the run's trace on the Activity tab, without leaving.
1945
+ box.addEventListener('click', function (ev) {
1946
+ var a = ev.target.closest('.wf-cand-trace');
1947
+ if (!a || !card.querySelector('.wf-trace') || ev.metaKey || ev.ctrlKey) return;
1948
+ ev.preventDefault();
1949
+ showWorkflowTab(card, 'activity');
1950
+ openRunTrace(name, card, a.getAttribute('data-run'));
1951
+ card.scrollIntoView({ block: 'start' });
1952
+ });
1572
1953
  }
1573
1954
 
1574
1955
  // A run's evidence line: its feedback, and saving it as an eval case.
@@ -1616,7 +1997,7 @@ ${renderMarkdownScript}
1616
1997
  var outcome = r.status === 'error' ? (r.error || '') : (r.result || '');
1617
1998
  var line = (values ? values + DOT : '') + outcome;
1618
1999
  return '<li class="wf-run-line">' + pill +
1619
- '<a class="wf-run-link" href="' + caseHref(r.run_id) + '"><span class="wf-run-when">' + escapeHtml(new Date(r.started_at).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })) + '</span>' +
2000
+ '<a class="wf-run-link" href="' + inboxHref(r.run_id) + '"><span class="wf-run-when">' + escapeHtml(new Date(r.started_at).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })) + '</span>' +
1620
2001
  '<span class="wf-run-text">' + escapeHtml(line.length > 160 ? line.slice(0, 160) + String.fromCharCode(8230) : line) + '</span></a>' +
1621
2002
  (r.versions && (r.versions.workflow || r.versions.brief) ? '<span class="hint">v' + (r.versions.workflow || r.versions.brief) + '</span>' : '') +
1622
2003
  runEvidenceHtml(w, r) + '</li>';
@@ -1634,24 +2015,27 @@ ${renderMarkdownScript}
1634
2015
  '<div class="wf-page-crumb-row"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">&#9776;</button>' +
1635
2016
  '<a class="wf-page-crumb" href="/agents/config?agent=' + encodeURIComponent(name) + '&tab=workflows">' + String.fromCharCode(8592) + ' ' + escapeHtml(agentLabel) + ' ' + String.fromCharCode(183) + ' Workflows</a></div>' +
1636
2017
  '<div class="wf-page-title-row"><h1>' + escapeHtml(w.title) + '</h1>' +
1637
- '<span class="wf-row-actions"><button type="button" class="workflow-edit">Edit</button></span></div>' +
2018
+ '<span class="wf-row-actions"><button type="button" class="workflow-edit">Edit workflow</button></span></div>' +
1638
2019
  (w.description && w.description !== w.title ? '<p class="wf-page-desc">' + escapeHtml(w.description) + '</p>' : '') +
1639
2020
  '<div class="wf-page-meta">' +
1640
2021
  '<span class="wf-page-meta-item"><span class="wf-page-meta-k">Agent</span><a href="/agents/config?agent=' + encodeURIComponent(name) + '">' + escapeHtml(agentLabel) + '</a></span>' +
1641
2022
  '<span class="wf-page-meta-item"><span class="wf-page-meta-k">Starts</span><span class="wf-page-starts">' + workflowStartsSummary(w) + '</span></span>' +
1642
2023
  '<span class="wf-page-meta-item"><span class="wf-page-meta-k">Last run</span><span class="wf-page-last">' + workflowLastRunHtml(last) + '</span></span>' +
2024
+ // Filled by loadWorkflowVersions.
2025
+ '<span class="wf-page-meta-item wf-page-version-item" hidden><span class="wf-page-meta-k">Version</span><span class="wf-page-version"></span></span>' +
1643
2026
  (w.jobs && w.jobs.length ? '<span class="wf-page-meta-item"><span class="wf-page-meta-k">For goal</span><span>' + w.jobs.map(function (j) { return '<a href="/goals?goal=' + encodeURIComponent(j.id) + '">' + escapeHtml(j.title) + '</a>'; }).join(', ') + '</span></span>' : '') +
1644
2027
  '</div>' +
1645
2028
  '</header>' +
1646
2029
  workflowDraftBannerHtml(w) +
1647
2030
  '<div class="wf-row-body wf-page-body">' +
1648
- '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Brief') + tabBtn('activity', 'Activity') + tabBtn('evaluation', 'Evaluation') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('contract', 'Contract') + '</div>' +
2031
+ '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Prompt') + tabBtn('activity', 'Activity') + tabBtn('evaluation', 'Evaluation') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + '</div>' +
1649
2032
  panel('brief', workflowBriefHtml(w)) +
1650
2033
  panel('activity', workflowActivityHtml(w, runs, name)) +
1651
2034
  panel('evaluation', workflowEvaluationHtml(w)) +
1652
2035
  panel('triggers', workflowTriggersHtml(w, name, params)) +
1653
2036
  panel('messages', workflowMessagesHtml(w, name)) +
1654
2037
  panel('contract', workflowContractHtml(w, name, params)) +
2038
+ panel('versions', workflowVersionsHtml()) +
1655
2039
  '<div class="hint workflow-result"></div>' +
1656
2040
  '<div class="wf-row-foot"><span class="hint">ID <code>' + escapeHtml(w.id) + '</code>, used by the API, schedules and webhooks</span><button type="button" class="wf-remove workflow-forget" title="Its schedules and webhooks go; its instructions stay as a skill for Chat">Remove</button></div>' +
1657
2041
  '</div>' +
@@ -1670,8 +2054,9 @@ ${renderMarkdownScript}
1670
2054
  '<div class="wf-row-body"' + (open ? '' : ' hidden') + '>' +
1671
2055
  // What it does, in full, once it's open (the row shows just its name).
1672
2056
  (w.description && w.description !== w.title ? '<p class="wf-desc">' + escapeHtml(w.description) + '</p>' : '') +
1673
- '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Brief') + tabBtn('activity', 'Activity') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + '</div>' +
2057
+ '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Prompt') + tabBtn('activity', 'Activity') + tabBtn('evaluation', 'Evaluation') + tabBtn('contract', 'Contract') + tabBtn('versions', 'Versions') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messaging') + '</div>' +
1674
2058
  panel('contract', workflowContractHtml(w, name, params)) +
2059
+ panel('versions', workflowVersionsHtml()) +
1675
2060
  panel('triggers', workflowTriggersHtml(w, name, params)) +
1676
2061
  panel('messages', workflowMessagesHtml(w, name)) +
1677
2062
  panel('brief', workflowBriefHtml(w)) +
@@ -1866,7 +2251,7 @@ ${renderMarkdownScript}
1866
2251
  '<span class="hint">ID: <code>' + escapeHtml(w.id) + '</code>, used by the API, schedules and webhooks; it doesn' + String.fromCharCode(8217) + 't change when you edit.</span></label>' +
1867
2252
  '<label>Description <span class="hint">(one line on what this workflow does; the agent uses it to recognise the workflow when you ask in Chat)</span>' +
1868
2253
  '<input name="description" maxlength="500" required value="' + escapeHtml(w.description) + '"></label>' +
1869
- '<h4 class="wf-editor-part">Brief <span class="hint">what the agent reads on every run</span></h4>' +
2254
+ '<h4 class="wf-editor-part">Prompt <span class="hint">what the agent reads on every run</span></h4>' +
1870
2255
  '<div class="body-field"><div class="wp-instructions-head"><label for="wpInstructions">Instructions <span class="hint">(everything the agent needs for this job: what to get done, the rules it keeps, and your policies, special cases and examples. It handles each case on its own judgment, so describe the job rather than every step. Read in full on every run; $name puts in a parameter&#39;s value. Chat uses them too.)</span></label>' +
1871
2256
  '<button type="button" class="wp-preview">Preview</button></div>' +
1872
2257
  '<div class="wp-preview-box" hidden><div class="hint">What a run starts with, with sample values (not saved):</div><pre class="wp-preview-text"></pre></div>' +
@@ -1996,7 +2381,7 @@ ${renderMarkdownScript}
1996
2381
  '<p class="wf-pub-version">' + (v.current ? 'Publishing makes this <strong>version ' + v.next + '</strong>, replacing version ' + v.current + ' for every run from now on.' : 'Publishing makes this the version every run uses from now on.') + '</p>' +
1997
2382
  (v.stale ? '<p class="wf-pub-stale">The published workflow changed since this draft began (it was version ' + v.draft.basedOn + '). Publishing replaces those changes with the draft' + String.fromCharCode(8217) + 's: check below.</p>' : '') +
1998
2383
  '<h4>What' + String.fromCharCode(8217) + 's changed</h4>' + changeDetailsHtml({ changes: v.changes }) +
1999
- '<label>Note <span class="hint">(optional: what changed and why, kept with the version)</span><textarea class="wf-pub-note" rows="2" maxlength="500" placeholder="e.g. Ask for the order number before looking it up"></textarea></label>' +
2384
+ '<label>Note <span class="hint">(optional: what changed and why, kept with the version)</span><textarea class="wf-pub-note" rows="2" maxlength="500" placeholder="e.g. Ask for the order number before looking it up">' + (v.draft.restoredFrom ? 'Restored version ' + v.draft.restoredFrom : '') + '</textarea></label>' +
2000
2385
  '<div class="ed-actions"><span class="hint wf-pub-result" role="status"></span><button type="button" class="wf-pub-cancel">Cancel</button><button type="button" class="primary wf-pub-go">Publish version ' + (v.next || '') + '</button></div>';
2001
2386
  body.querySelector('.wf-pub-cancel').addEventListener('click', close);
2002
2387
  var go = body.querySelector('.wf-pub-go');
@@ -2434,16 +2819,33 @@ ${renderMarkdownScript}
2434
2819
  render(shown ? shown.url : null, shown ? shown.id : null);
2435
2820
  }
2436
2821
 
2437
- // The workflow's versions (its name, inputs, model, instructions and
2438
- // result format), on the Brief tab: which one is in use, who saved it
2439
- // and why, and every earlier one to read or restore (restoring saves it
2440
- // as a new version). Hidden where the workspace keeps no versions.
2441
- function loadWorkflowVersions(card, base) {
2822
+ // The Versions tab: each version of the workflow (its name, inputs,
2823
+ // model, tools, triggers, success criteria, instructions and result
2824
+ // format) as a card, newest first, with who saved it, when and why.
2825
+ // View shows it in full, Compare what changed from the version before
2826
+ // it, and Restore makes it the workflow's draft, to review and publish
2827
+ // as the next version. Filled by loadWorkflowVersions.
2828
+ function workflowVersionsHtml() {
2829
+ return '<div class="wf-versions"><p class="hint" style="margin:0">Loading' + String.fromCharCode(8230) + '</p></div>';
2830
+ }
2831
+
2832
+ function loadWorkflowVersions(name, card, base) {
2442
2833
  var box = card.querySelector('.wf-versions');
2443
- if (!box) return;
2834
+ var meta = card.querySelector('.wf-page-version');
2444
2835
  fetch(base + '/versions', { headers: { accept: 'application/json' } })
2445
2836
  .then(function (r) { return r.ok ? r.json() : null; })
2446
- .then(function (data) { if (data) renderWorkflowVersions(box, base, data); })
2837
+ .then(function (data) {
2838
+ if (!data) { if (box) box.innerHTML = '<p class="hint" style="margin:0">This workspace keeps no versions.</p>'; return; }
2839
+ var versions = data.versions || [];
2840
+ var current = versions.filter(function (v) { return v.number === data.current; })[0] || versions[0];
2841
+ if (meta && current) {
2842
+ var draft = workflowsById[card.dataset.workflow] && workflowsById[card.dataset.workflow].draft;
2843
+ meta.innerHTML = '<a href="' + workflowPageHref(name, card.dataset.workflow, 'versions') + '">v' + current.number + '</a>' + (draft ? ' <span class="hint">+ draft</span>' : '');
2844
+ meta.querySelector('a').addEventListener('click', function (ev) { ev.preventDefault(); showWorkflowTab(card, 'versions'); });
2845
+ meta.parentNode.hidden = false;
2846
+ }
2847
+ if (box) renderWorkflowVersions(name, card, box, base, data);
2848
+ })
2447
2849
  .catch(function () {});
2448
2850
  }
2449
2851
 
@@ -2451,47 +2853,143 @@ ${renderMarkdownScript}
2451
2853
  return new Date(v.at).toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' });
2452
2854
  }
2453
2855
 
2454
- function renderWorkflowVersions(box, base, data) {
2856
+ // Two texts line by line (longest common subsequence): each line kept,
2857
+ // added or removed, in order. A very long pair is told by which lines
2858
+ // each has that the other hasn't.
2859
+ function versionLineDiff(before, after) {
2860
+ var NL = String.fromCharCode(10);
2861
+ var a = before.split(NL);
2862
+ var b = after.split(NL);
2863
+ var out = [];
2864
+ if (a.length * b.length > 4000000) {
2865
+ var inA = {}, inB = {};
2866
+ a.forEach(function (l) { inA[l] = true; });
2867
+ b.forEach(function (l) { inB[l] = true; });
2868
+ a.forEach(function (l) { if (!inB[l]) out.push({ t: '-', l: l }); });
2869
+ b.forEach(function (l) { out.push({ t: inA[l] ? ' ' : '+', l: l }); });
2870
+ return out;
2871
+ }
2872
+ var t = [];
2873
+ for (var i = a.length; i >= 0; i--) {
2874
+ t[i] = [];
2875
+ for (var j = b.length; j >= 0; j--) t[i][j] = i === a.length || j === b.length ? 0 : a[i] === b[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]);
2876
+ }
2877
+ i = 0; j = 0;
2878
+ while (i < a.length && j < b.length) {
2879
+ if (a[i] === b[j]) { out.push({ t: ' ', l: a[i] }); i++; j++; }
2880
+ else if (t[i + 1][j] >= t[i][j + 1]) out.push({ t: '-', l: a[i++] });
2881
+ else out.push({ t: '+', l: b[j++] });
2882
+ }
2883
+ while (i < a.length) out.push({ t: '-', l: a[i++] });
2884
+ while (j < b.length) out.push({ t: '+', l: b[j++] });
2885
+ return out;
2886
+ }
2887
+
2888
+ // The diff with three lines of context around each change; the
2889
+ // unchanged stretches between are folded into a line saying how many.
2890
+ function versionDiffHtml(before, after) {
2891
+ var lines = versionLineDiff(before, after);
2892
+ if (!lines.some(function (x) { return x.t !== ' '; })) return '<p class="hint" style="margin:0">Nothing changed from the version before.</p>';
2893
+ var near = lines.map(function () { return false; });
2894
+ lines.forEach(function (x, k) {
2895
+ if (x.t === ' ') return;
2896
+ for (var d = Math.max(0, k - 3); d <= Math.min(lines.length - 1, k + 3); d++) near[d] = true;
2897
+ });
2898
+ var html = '';
2899
+ var skipped = 0;
2900
+ var MINUS = String.fromCharCode(8722);
2901
+ lines.forEach(function (x, k) {
2902
+ if (!near[k]) { skipped++; return; }
2903
+ if (skipped) { html += '<div class="chg-gap">' + skipped + ' unchanged line' + (skipped === 1 ? '' : 's') + '</div>'; skipped = 0; }
2904
+ var cls = x.t === '+' ? 'chg-ins' : x.t === '-' ? 'chg-del' : 'chg-same';
2905
+ html += '<div class="' + cls + '">' + (x.t === '+' ? '+' : x.t === '-' ? MINUS : ' ') + ' ' + escapeHtml(x.l) + '</div>';
2906
+ });
2907
+ if (skipped) html += '<div class="chg-gap">' + skipped + ' unchanged line' + (skipped === 1 ? '' : 's') + '</div>';
2908
+ return '<div class="chg-lines">' + html + '</div>';
2909
+ }
2910
+
2911
+ function renderWorkflowVersions(name, card, box, base, data) {
2455
2912
  var versions = data.versions || [];
2456
- if (!versions.length) { box.hidden = true; return; }
2913
+ if (!versions.length) { box.innerHTML = '<p class="hint" style="margin:0">No versions yet: the first is numbered when it' + RSQ + 's first run or published.</p>'; return; }
2457
2914
  var current = versions.filter(function (v) { return v.number === data.current; })[0] || versions[0];
2458
- var about = function (v) { return [v.by ? 'by ' + escapeHtml(v.by) : '', escapeHtml(versionWhen(v)), v.reason ? escapeHtml(v.reason) : ''].filter(Boolean).join(DOT); };
2459
- box.innerHTML = '<div class="wf-versions-line"><strong>Workflow version ' + current.number + '</strong><span class="hint">' + about(current) + '</span>' +
2460
- (versions.length > 1 ? '<button type="button" class="wf-link wf-versions-toggle">History (' + versions.length + ')</button>' : '') + '</div>' +
2461
- '<ol class="wf-versions-list" hidden>' + versions.map(function (v) {
2915
+ var byNumber = {};
2916
+ versions.forEach(function (v) { byNumber[v.number] = v; });
2917
+ // The version before each: the next older one kept.
2918
+ var previous = function (v) {
2919
+ var older = versions.filter(function (x) { return x.number < v.number; });
2920
+ return older.length ? older[0] : null;
2921
+ };
2922
+ var hasDraft = Boolean(workflowsById[card.dataset.workflow] && workflowsById[card.dataset.workflow].draft);
2923
+ box.innerHTML = '<p class="hint" style="margin:0">Every published change is numbered and kept. Restoring one makes it the draft' + (hasDraft ? ' (replacing what the draft changes in the prompt, inputs, model, result format and success criteria)' : '') + ': review it, then publish it as version ' + (versions[0].number + 1) + '.</p>' +
2924
+ '<ol class="wf-version-cards">' + versions.map(function (v) {
2462
2925
  var isCurrent = v.number === current.number;
2463
- return '<li data-version="' + v.number + '"><div class="wf-versions-row"><strong>v' + v.number + '</strong><span class="hint">' + about(v) + '</span>' +
2464
- (isCurrent ? '<span class="le-pill good">In use</span>' : '') +
2465
- '<button type="button" class="wf-link wf-version-view">View</button>' +
2466
- (isCurrent ? '' : '<button type="button" class="wf-link wf-version-restore">Restore</button>') + '</div>' +
2467
- '<div class="workflow-steps-text wf-version-text" hidden>' + escapeHtml(v.content) + '</div></li>';
2468
- }).join('') + '</ol><span class="hint wf-versions-status" role="status"></span>';
2469
- box.hidden = false;
2470
- var list = box.querySelector('.wf-versions-list');
2471
- var toggle = box.querySelector('.wf-versions-toggle');
2472
- if (toggle) toggle.addEventListener('click', function () {
2473
- list.hidden = !list.hidden;
2474
- toggle.textContent = list.hidden ? 'History (' + versions.length + ')' : 'Hide history';
2475
- });
2476
- list.addEventListener('click', function (ev) {
2926
+ var prev = previous(v);
2927
+ var about = [v.by ? 'by ' + escapeHtml(v.by) : '', escapeHtml(versionWhen(v))].filter(Boolean).join(DOT);
2928
+ return '<li class="wf-version-card' + (isCurrent ? ' is-current' : '') + '" data-version="' + v.number + '">' +
2929
+ '<div class="wf-version-head"><strong>Version ' + v.number + '</strong>' +
2930
+ (isCurrent ? '<span class="le-pill good">In use</span>' : '') +
2931
+ '<span class="hint">' + about + '</span>' +
2932
+ '<span class="wf-version-actions">' +
2933
+ '<button type="button" class="wf-version-view" aria-pressed="false">View</button>' +
2934
+ (prev ? '<button type="button" class="wf-version-compare" aria-pressed="false" title="What changed from version ' + prev.number + '">Compare</button>' : '') +
2935
+ (isCurrent ? '' : '<button type="button" class="wf-version-restore">Restore</button>') +
2936
+ '</span></div>' +
2937
+ (v.reason ? '<p class="wf-version-reason">' + escapeHtml(v.reason) + '</p>' : '') +
2938
+ '<div class="workflow-steps-text wf-version-text" hidden>' + escapeHtml(v.content) + '</div>' +
2939
+ '<div class="wf-version-diff" hidden></div>' +
2940
+ '<span class="hint wf-version-status" role="status"></span>' +
2941
+ '</li>';
2942
+ }).join('') + '</ol>';
2943
+ box.querySelector('.wf-version-cards').addEventListener('click', function (ev) {
2477
2944
  var item = ev.target.closest('li[data-version]');
2478
- if (!item) return;
2479
- if (ev.target.closest('.wf-version-view')) {
2480
- var text = item.querySelector('.wf-version-text');
2481
- text.hidden = !text.hidden;
2482
- ev.target.textContent = text.hidden ? 'View' : 'Hide';
2945
+ var btn = ev.target.closest('button');
2946
+ if (!item || !btn) return;
2947
+ var v = byNumber[item.getAttribute('data-version')];
2948
+ var text = item.querySelector('.wf-version-text');
2949
+ var diff = item.querySelector('.wf-version-diff');
2950
+ var viewBtn = item.querySelector('.wf-version-view');
2951
+ var compareBtn = item.querySelector('.wf-version-compare');
2952
+ // View and Compare show one at a time.
2953
+ var show = function (which) {
2954
+ text.hidden = which !== 'view';
2955
+ diff.hidden = which !== 'compare';
2956
+ viewBtn.setAttribute('aria-pressed', String(which === 'view'));
2957
+ viewBtn.textContent = which === 'view' ? 'Hide' : 'View';
2958
+ if (compareBtn) {
2959
+ compareBtn.setAttribute('aria-pressed', String(which === 'compare'));
2960
+ compareBtn.textContent = which === 'compare' ? 'Hide changes' : 'Compare';
2961
+ }
2962
+ };
2963
+ if (btn.classList.contains('wf-version-view')) { show(text.hidden ? 'view' : null); return; }
2964
+ if (btn.classList.contains('wf-version-compare')) {
2965
+ if (!diff.hidden) { show(null); return; }
2966
+ var prev = previous(v);
2967
+ if (!diff.innerHTML) diff.innerHTML = '<p class="hint" style="margin:0 0 6px">What changed from version ' + prev.number + ' to version ' + v.number + '.</p>' + versionDiffHtml(prev.content, v.content);
2968
+ show('compare');
2483
2969
  return;
2484
2970
  }
2485
- var restore = ev.target.closest('.wf-version-restore');
2486
- if (!restore) return;
2487
- if (restore.getAttribute('data-confirming') !== '1') { restore.setAttribute('data-confirming', '1'); restore.textContent = 'Click again to restore'; return; }
2488
- restore.disabled = true;
2489
- var status = box.querySelector('.wf-versions-status');
2490
- status.textContent = 'Restoring' + String.fromCharCode(8230);
2491
- fetch(base + '/versions/' + item.getAttribute('data-version') + '/restore', { method: 'POST' })
2492
- .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'That did not work'); return b; }); })
2493
- .then(function () { location.reload(); })
2494
- .catch(function (err) { status.textContent = err.message; restore.disabled = false; });
2971
+ if (btn.classList.contains('wf-version-restore')) {
2972
+ if (btn.getAttribute('data-confirming') !== '1') { btn.setAttribute('data-confirming', '1'); btn.textContent = 'Click again to restore as a draft'; return; }
2973
+ btn.disabled = true;
2974
+ var status = item.querySelector('.wf-version-status');
2975
+ status.textContent = 'Making a draft from version ' + v.number + String.fromCharCode(8230);
2976
+ fetchJsonRetryOnce(base + '/versions/' + v.number + '/restore', { method: 'POST' }).then(function (r) {
2977
+ if (!r.ok) { status.textContent = r.body.error || 'That did not work'; btn.disabled = false; return; }
2978
+ if (!r.body.draft || !r.body.changes.length) {
2979
+ status.textContent = 'Version ' + v.number + ' is the same as the published workflow: there' + RSQ + 's nothing to restore.';
2980
+ btn.disabled = false;
2981
+ btn.removeAttribute('data-confirming');
2982
+ btn.textContent = 'Restore';
2983
+ return;
2984
+ }
2985
+ var id = card.dataset.workflow;
2986
+ if (workflowsById[id]) workflowsById[id].draft = r.body.draft;
2987
+ workflowTabs[id] = 'versions';
2988
+ loadWorkflowsSection(name);
2989
+ // Straight to the review: what it changes, then Publish.
2990
+ openPublishDialog(name, workflowsById[id] || { id: id, title: '' });
2991
+ });
2992
+ }
2495
2993
  });
2496
2994
  }
2497
2995
 
@@ -2514,12 +3012,12 @@ ${renderMarkdownScript}
2514
3012
  }
2515
3013
  var tabs = card.querySelectorAll('.wf-tab');
2516
3014
  for (var t = 0; t < tabs.length; t++) tabs[t].addEventListener('click', function (ev) { showWorkflowTab(card, ev.currentTarget.dataset.tab); });
2517
- loadWorkflowVersions(card, base);
3015
+ loadWorkflowVersions(name, card, base);
2518
3016
  wireDraftBanner(name, card);
2519
3017
  loadWorkflowHealth(card, base);
2520
- loadCandidates(card, base);
2521
- loadAuditSummary(card, base);
2522
- loadLatestChanges(card, name);
3018
+ loadCandidates(name, card, base);
3019
+ loadWorkflowRuns(name, card, base);
3020
+ if (openTraces[id] && card.querySelector('.wf-trace')) openRunTrace(name, card, openTraces[id].run);
2523
3021
  card.querySelector('.workflow-edit').addEventListener('click', function () { openWorkflowEditor(name, card); });
2524
3022
  // Opens the workflow's page on its Triggers tab.
2525
3023
  var triggersBtn = card.querySelector('.workflow-triggers-open');