loopengine 0.4.4 → 0.4.6

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.
@@ -7,6 +7,12 @@
7
7
  // placeholders, since it lives inside a template literal.
8
8
  import { devUiCss } from './dev-ui-styles.js';
9
9
  import { consoleShellScript, consoleSidebarHtml } from './console-shell.js';
10
+ /** The page with its filters' choices in it (agents, workflows, people),
11
+ * so they show at once instead of after another request. */
12
+ export function auditPageFor(filters) {
13
+ // In a script element: no "</" may end it early.
14
+ return auditPageHtml.replace('null/*AUDIT_FILTERS*/', JSON.stringify(filters).replace(/</g, '\\u003c'));
15
+ }
10
16
  export const auditPageHtml = `<!doctype html>
11
17
  <html lang="en">
12
18
  <head>
@@ -19,10 +25,21 @@ export const auditPageHtml = `<!doctype html>
19
25
  .au-tabs button { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 8px 12px; font-size: 14px; font-weight: 600; color: var(--ink-muted); margin-bottom: -1px; }
20
26
  .au-tabs button[aria-selected="true"] { color: var(--accent-ink); border-bottom-color: var(--accent); }
21
27
  .au-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
22
- .au-bar select, .au-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); max-width: 220px; }
28
+ .au-bar select, .au-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); max-width: 180px; }
23
29
  .au-bar input[type="search"] { flex: 1; min-width: 160px; max-width: none; }
24
30
  .au-bar [hidden] { display: none; }
25
- .au-export { margin-left: auto; font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; }
31
+ .au-actions { display: inline-flex; gap: 8px; margin-left: auto; }
32
+ .au-verify { font-size: 13px; }
33
+ .au-check { padding: 10px 14px; border-radius: 10px; font-size: 13px; background: var(--good-soft); color: var(--good); }
34
+ .au-check.bad { background: var(--bad-soft); color: var(--bad); font-weight: 600; }
35
+ .au-check .hint { display: block; margin-top: 2px; font-weight: 400; }
36
+ .au-summary { border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; display: grid; gap: 10px; background: var(--bg); }
37
+ .au-summary h2 { margin: 0; font-size: 15px; }
38
+ .au-summary ul { margin: 0; padding-left: 20px; display: grid; gap: 4px; font-size: 13.5px; line-height: 1.5; }
39
+ .au-summary-tools { display: flex; gap: 8px; flex-wrap: wrap; }
40
+ .au-summary-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; }
41
+ .au-summary-tools a.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
42
+ .au-export { font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; }
26
43
  .au-list { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--bg); }
27
44
  .au-row { display: grid; grid-template-columns: 136px 80px minmax(0, 1fr) auto; gap: 12px; align-items: baseline; padding: 10px 16px; border-top: 1px solid var(--line); font-size: 13px; }
28
45
  .au-row:first-child { border-top: 0; }
@@ -42,6 +59,7 @@ export const auditPageHtml = `<!doctype html>
42
59
  .au-state.bad { background: var(--bad-soft); color: var(--bad); }
43
60
  .au-state.warn { background: var(--warn-soft); color: var(--warn); }
44
61
  .au-state.run { background: var(--accent-soft); color: var(--accent-ink); }
62
+ .au-evalcase { color: var(--accent-ink); font-weight: 600; }
45
63
  .au-empty { padding: 28px 16px; text-align: center; color: var(--ink-muted); font-size: 13.5px; }
46
64
  .au-more { justify-self: center; }
47
65
  .error { font-size: 13px; color: var(--bad); margin: 0; }
@@ -74,6 +92,9 @@ ${consoleSidebarHtml}
74
92
  <select id="auKind" aria-label="Kind">
75
93
  <option value="">Everything</option><option value="change">Settings changed</option><option value="decision">Approvals</option><option value="answer">Answers</option><option value="feedback">Feedback</option>
76
94
  </select>
95
+ <select id="auFlag" aria-label="Worth a look" hidden>
96
+ <option value="">Any case</option><option value="overruled">Denied or changed</option><option value="bad">Marked bad</option><option value="asked">Asked a question</option>
97
+ </select>
77
98
  <select id="auStatus" aria-label="Status" hidden>
78
99
  <option value="">Any outcome</option><option value="done">Done</option><option value="error">Failed</option><option value="awaiting_approval">Waiting for a decision</option><option value="running">Running</option>
79
100
  </select>
@@ -81,14 +102,18 @@ ${consoleSidebarHtml}
81
102
  <option value="7">Last 7 days</option><option value="30" selected>Last 30 days</option><option value="90">Last 90 days</option><option value="365">Last year</option><option value="">All time</option>
82
103
  </select>
83
104
  <input type="search" id="auQ" placeholder="Search" aria-label="Search">
84
- <a class="au-export" id="auExport" href="/audit/events.csv" download>Export CSV</a>
105
+ <span class="au-actions"><button type="button" class="au-verify" id="auVerify">Verify log</button>
106
+ <a class="au-export" id="auExport" href="/audit/events.csv" download>Export CSV</a></span>
85
107
  </div>
108
+ <div class="au-check" id="auCheck" role="status" hidden></div>
109
+ <section class="au-summary" id="auSummary" hidden></section>
86
110
  <div id="auList"><p class="hint">Loading&hellip;</p></div>
87
111
  <button type="button" class="au-more" id="auMore" hidden>Load older</button>
88
112
  </div></div></div>
89
113
  </main>
90
114
  </div>
91
115
  ${consoleShellScript}
116
+ <script>window.AUDIT_FILTERS = null/*AUDIT_FILTERS*/;</script>
92
117
  <script>
93
118
  (function () {
94
119
  var DOT = ' ' + String.fromCharCode(183) + ' ';
@@ -96,16 +121,19 @@ ${consoleShellScript}
96
121
  var state = {
97
122
  tab: params.get('tab') === 'cases' ? 'cases' : 'activity',
98
123
  agent: params.get('agent') || '', workflow: params.get('workflow') || '', by: params.get('by') || '',
99
- kind: params.get('kind') || '', status: params.get('status') || '',
124
+ kind: params.get('kind') || '', status: params.get('status') || '', flag: params.get('flag') || '',
100
125
  period: params.has('period') ? params.get('period') : '30', q: params.get('q') || '',
101
126
  };
102
- var filters = { agents: [], workflows: [], people: [] };
127
+ // The filters' choices come with the page (auditPageFor), so they show
128
+ // at once; a page served without them fetches them.
129
+ var embedded = window.AUDIT_FILTERS || null;
130
+ var filters = embedded || { agents: [], workflows: [], people: [] };
103
131
  var next = null;
104
132
  var list = document.getElementById('auList');
105
133
  var more = document.getElementById('auMore');
106
134
  var el = {
107
135
  agent: document.getElementById('auAgent'), workflow: document.getElementById('auWorkflow'), by: document.getElementById('auBy'),
108
- kind: document.getElementById('auKind'), status: document.getElementById('auStatus'), period: document.getElementById('auPeriod'),
136
+ kind: document.getElementById('auKind'), status: document.getElementById('auStatus'), flag: document.getElementById('auFlag'), period: document.getElementById('auPeriod'),
109
137
  q: document.getElementById('auQ'), exportLink: document.getElementById('auExport'),
110
138
  };
111
139
 
@@ -142,6 +170,7 @@ ${consoleShellScript}
142
170
  if (state.by) q.set('by', state.by);
143
171
  if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
144
172
  if (state.tab === 'cases' && state.status) q.set('status', state.status);
173
+ if (state.tab === 'cases' && state.flag) q.set('flag', state.flag);
145
174
  if (state.period) q.set('since', new Date(Date.now() - Number(state.period) * 86400000).toISOString());
146
175
  if (state.q) q.set('q', state.q);
147
176
  Object.keys(extra || {}).forEach(function (k) { q.set(k, extra[k]); });
@@ -154,6 +183,7 @@ ${consoleShellScript}
154
183
  ['agent', 'workflow', 'by', 'q'].forEach(function (k) { if (state[k]) q.set(k, state[k]); });
155
184
  if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
156
185
  if (state.tab === 'cases' && state.status) q.set('status', state.status);
186
+ if (state.tab === 'cases' && state.flag) q.set('flag', state.flag);
157
187
  if (state.period !== '30') q.set('period', state.period);
158
188
  history.replaceState(null, '', '/audit' + (q.toString() ? '?' + q.toString() : ''));
159
189
  }
@@ -162,7 +192,7 @@ ${consoleShellScript}
162
192
  // the agent, or the workspace setting.
163
193
  function eventLink(e) {
164
194
  var d = e.data || {};
165
- if (e.run_id) return { href: '/inbox?case=' + encodeURIComponent(e.run_id), text: 'Case' };
195
+ if (e.run_id) return { href: '/cases/' + encodeURIComponent(e.run_id) + '?back=' + encodeURIComponent(location.pathname + location.search), text: 'Case' };
166
196
  if (e.workflow_id) return { href: workflowHref(e.agent, e.workflow_id, /brief version/i.test(d.label || '') || /Edited the workflow/.test(d.label || '') ? 'brief' : 'changes'), text: 'Workflow' };
167
197
  if (e.agent) return { href: '/agents/config?agent=' + encodeURIComponent(e.agent), text: 'Agent' };
168
198
  var path = String(d.path || '');
@@ -199,8 +229,8 @@ ${consoleShellScript}
199
229
  return '<div class="au-row au-case"><span class="au-state ' + pill[0] + '">' + pill[1] + '</span>' +
200
230
  '<span class="au-what"><strong>' + esc(c.workflowTitle) + (c.inputs ? DOT + esc(c.inputs) : '') + '</strong>' +
201
231
  (c.outcome ? '<span class="au-detail">' + esc(c.outcome) + '</span>' : '') +
202
- '<span class="au-where">' + esc(when(c.startedAt)) + DOT + esc(agentLabel(c.agent)) + (c.briefVersion ? DOT + 'brief v' + c.briefVersion : '') + (c.people.length ? DOT + 'decided by ' + esc(c.people.join(', ')) : '') + '</span></span>' +
203
- '<a class="au-open" href="/inbox?case=' + encodeURIComponent(c.id) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
232
+ '<span class="au-where">' + esc(when(c.startedAt)) + DOT + esc(agentLabel(c.agent)) + (c.briefVersion ? DOT + 'brief v' + c.briefVersion : '') + (c.people.length ? DOT + 'decided by ' + esc(c.people.join(', ')) : '') + (c.evalCase ? DOT + '<span class="au-evalcase">eval case</span>' : '') + '</span></span>' +
233
+ '<a class="au-open" href="/cases/' + encodeURIComponent(c.id) + '?back=' + encodeURIComponent(location.pathname + location.search) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
204
234
  }
205
235
 
206
236
  function load(append) {
@@ -237,12 +267,39 @@ ${consoleShellScript}
237
267
  for (var i = 0; i < tabs.length; i++) tabs[i].setAttribute('aria-selected', String(tabs[i].getAttribute('data-tab') === state.tab));
238
268
  el.kind.hidden = state.tab !== 'activity';
239
269
  el.status.hidden = state.tab !== 'cases';
270
+ el.flag.hidden = state.tab !== 'cases';
240
271
  el.exportLink.hidden = state.tab !== 'activity';
272
+ verifyBtn.hidden = state.tab !== 'activity';
241
273
  el.exportLink.href = '/audit/events.csv?' + query();
242
274
  remember();
243
275
  }
244
276
 
245
- function changed() { sync(); load(false); }
277
+ // With a workflow chosen: its audit for the period, in sentences, and
278
+ // its report.
279
+ var summaryBox = document.getElementById('auSummary');
280
+ function loadSummary() {
281
+ var wf = state.workflow && filters.workflows.filter(function (w) { return w.id === state.workflow && (!state.agent || w.agent === state.agent); })[0];
282
+ if (!wf) { summaryBox.hidden = true; return; }
283
+ var q = new URLSearchParams();
284
+ q.set('since', state.period ? new Date(Date.now() - Number(state.period) * 86400000).toISOString() : '2000-01-01T00:00:00.000Z');
285
+ var base = '/agents/' + encodeURIComponent(wf.agent) + '/workflows/' + encodeURIComponent(wf.id) + '/audit';
286
+ summaryBox.hidden = false;
287
+ summaryBox.innerHTML = '<h2>' + esc(wf.title) + '</h2><p class="hint">Loading its audit' + String.fromCharCode(8230) + '</p>';
288
+ fetch(base + '?' + q.toString(), { headers: { accept: 'application/json' } })
289
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
290
+ .then(function (a) {
291
+ if (state.workflow !== wf.id) return;
292
+ var period = el.period.options[el.period.selectedIndex].text.toLowerCase();
293
+ summaryBox.innerHTML = '<h2>' + esc(wf.title) + ' <span class="hint">' + esc(period) + '</span></h2>' +
294
+ '<ul>' + a.summary.map(function (line) { return '<li>' + esc(line) + '</li>'; }).join('') + '</ul>' +
295
+ '<div class="au-summary-tools"><a class="primary" href="' + base + '/report?' + q.toString() + '">Open the report</a>' +
296
+ '<a href="' + base + '/report?' + q.toString() + '&format=json" download>Download JSON</a>' +
297
+ '<a href="' + workflowHref(wf.agent, wf.id, '') + '">Open the workflow</a></div>';
298
+ })
299
+ .catch(function (err) { summaryBox.innerHTML = '<p class="error">Could not load its audit: ' + esc(err.message) + '</p>'; });
300
+ }
301
+
302
+ function changed() { sync(); load(false); loadSummary(); }
246
303
 
247
304
  document.querySelector('.au-tabs').addEventListener('click', function (ev) {
248
305
  var b = ev.target.closest('button[data-tab]');
@@ -251,7 +308,7 @@ ${consoleShellScript}
251
308
  changed();
252
309
  });
253
310
  el.agent.addEventListener('change', function () { state.agent = el.agent.value; fillWorkflows(); changed(); });
254
- ['workflow', 'by', 'kind', 'status', 'period'].forEach(function (k) {
311
+ ['workflow', 'by', 'kind', 'status', 'flag', 'period'].forEach(function (k) {
255
312
  el[k].addEventListener('change', function () { state[k] = el[k].value; changed(); });
256
313
  });
257
314
  var typing;
@@ -261,20 +318,57 @@ ${consoleShellScript}
261
318
  });
262
319
  more.addEventListener('click', function () { load(true); });
263
320
 
321
+ // Checks every event's hash, in order.
322
+ var verifyBtn = document.getElementById('auVerify');
323
+ var check = document.getElementById('auCheck');
324
+ var PROBLEMS = {
325
+ 'changed': 'it was changed after it was recorded',
326
+ 'missing-before': 'an event before it was removed, or the order changed',
327
+ };
328
+ verifyBtn.addEventListener('click', function () {
329
+ verifyBtn.disabled = true;
330
+ check.hidden = false;
331
+ check.className = 'au-check';
332
+ check.textContent = 'Checking every event' + String.fromCharCode(8230);
333
+ fetch('/audit/verify', { headers: { accept: 'application/json' } })
334
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
335
+ .then(function (v) {
336
+ if (v.ok) {
337
+ check.innerHTML = 'Intact: all ' + v.events.toLocaleString() + ' events check out.' +
338
+ (v.last ? '<span class="hint">Latest event #' + v.last.id + ', ' + esc(when(v.last.at)) + DOT + 'hash ' + esc(v.last.hash) + '</span>' : '');
339
+ } else {
340
+ check.className = 'au-check bad';
341
+ check.innerHTML = 'Broken at event #' + v.broken.id + (v.broken.at ? ' (' + esc(when(v.broken.at)) + ')' : '') + ': ' + esc(PROBLEMS[v.broken.problem] || v.broken.problem) + '.' +
342
+ '<span class="hint">' + v.events.toLocaleString() + ' events before it check out.</span>';
343
+ }
344
+ })
345
+ .catch(function (err) { check.className = 'au-check bad'; check.textContent = 'Could not check: ' + err.message; })
346
+ .then(function () { verifyBtn.disabled = false; });
347
+ });
348
+
264
349
  el.q.value = state.q;
265
350
  el.kind.value = state.kind;
266
351
  el.status.value = state.status;
352
+ el.flag.value = state.flag;
267
353
  el.period.value = state.period;
268
- fetch('/audit/filters', { headers: { accept: 'application/json' } })
269
- .then(function (r) { return r.ok ? r.json() : filters; })
270
- .catch(function () { return filters; })
271
- .then(function (f) {
272
- filters = f;
273
- el.agent.innerHTML = '<option value="">All agents</option>' + f.agents.map(function (a) { return '<option value="' + esc(a.name) + '"' + (a.name === state.agent ? ' selected' : '') + '>' + esc(a.label) + '</option>'; }).join('');
274
- el.by.innerHTML = '<option value="">Anyone</option>' + f.people.map(function (p) { return '<option value="' + esc(p) + '"' + (p === state.by ? ' selected' : '') + '>' + esc(p) + '</option>'; }).join('');
275
- fillWorkflows();
276
- changed();
277
- });
354
+ function fillFilters(f) {
355
+ filters = f;
356
+ el.agent.innerHTML = '<option value="">All agents</option>' + f.agents.map(function (a) { return '<option value="' + esc(a.name) + '"' + (a.name === state.agent ? ' selected' : '') + '>' + esc(a.label) + '</option>'; }).join('');
357
+ el.by.innerHTML = '<option value="">Anyone</option>' + f.people.map(function (p) { return '<option value="' + esc(p) + '"' + (p === state.by ? ' selected' : '') + '>' + esc(p) + '</option>'; }).join('');
358
+ fillWorkflows();
359
+ }
360
+ if (embedded) {
361
+ fillFilters(embedded);
362
+ changed();
363
+ } else {
364
+ // The list doesn't wait for the choices; its rows are named again once
365
+ // they come.
366
+ changed();
367
+ fetch('/audit/filters', { headers: { accept: 'application/json' } })
368
+ .then(function (r) { return r.ok ? r.json() : null; })
369
+ .catch(function () { return null; })
370
+ .then(function (f) { if (f) { fillFilters(f); load(false); } });
371
+ }
278
372
  })();
279
373
  </script>
280
374
  </body>
@@ -390,7 +390,9 @@ export const consoleShellScript = `<script>
390
390
  : page === 'workflows' || page === 'workflows-overview' ? 'workflows'
391
391
  : page === 'config' ? 'settings'
392
392
  : page === 'inbox' ? 'inbox'
393
- : page === 'audit' ? 'audit' : '';
393
+ : page === 'audit' ? 'audit'
394
+ // A case, in the section it was opened from.
395
+ : page === 'case' ? ((params.get('back') || '').indexOf('/audit') === 0 ? 'audit' : (params.get('back') || '').indexOf('/agents') === 0 ? 'workflows' : 'inbox') : '';
394
396
  var railItems = document.querySelectorAll('[data-le-section]');
395
397
  for (var ri = 0; ri < railItems.length; ri++) {
396
398
  if (railItems[ri].getAttribute('data-le-section') === section0) railItems[ri].classList.add('is-current');
@@ -70,6 +70,8 @@ export const devUiCss = `
70
70
  cursor: pointer;
71
71
  font-weight: 500;
72
72
  }
73
+ select { cursor: pointer; }
74
+ select:disabled { cursor: default; }
73
75
  button:hover:not(:disabled) { background: var(--surface); }
74
76
  button[type="submit"], button.primary {
75
77
  background: var(--accent);
@@ -37,15 +37,32 @@ export interface InboxItem {
37
37
  finishedAt?: string;
38
38
  /** The latest person who decided something in it. */
39
39
  lastBy?: string;
40
+ /** When it began waiting on a person (its oldest open request). */
41
+ waitingSince?: string;
42
+ /** When anything last happened in it: finished, or decided. */
43
+ lastActivity: string;
44
+ /** What happened, in a few words: "Done automatically", "Approved by
45
+ * ana@…", "Failed". */
46
+ outcome: string;
40
47
  }
48
+ /** The Inbox's views: what's waiting on a person (however long), and
49
+ * everything from the last RECENT_DAYS days. */
50
+ export type InboxView = 'needs' | 'recent';
51
+ export declare const RECENT_DAYS = 7;
52
+ /** `view`: "needs" (waiting on a person, oldest first, however long),
53
+ * "recent" (the last RECENT_DAYS days, latest first), or "auto" (needs
54
+ * when anything waits, else recent). `open` is the older name for needs. */
41
55
  export declare function listInbox(deps: InboxDeps, filter?: {
56
+ view?: InboxView | 'auto';
42
57
  open?: boolean;
43
58
  q?: string;
44
59
  workflow?: string;
45
60
  limit?: number;
61
+ now?: number;
46
62
  }): Promise<{
47
63
  items: InboxItem[];
48
64
  open: number;
65
+ view: InboxView;
49
66
  workflows: {
50
67
  id: string;
51
68
  title: string;
@@ -1,3 +1,18 @@
1
+ export const RECENT_DAYS = 7;
2
+ // A case's outcome in words, from its status and the last decision.
3
+ function outcomeOf(run, waiting) {
4
+ if (waiting)
5
+ return 'Waiting';
6
+ if (run.status === 'error')
7
+ return 'Failed';
8
+ if (run.status === 'running')
9
+ return 'Running';
10
+ const last = [...(run.decisions ?? []).map((d) => ({ at: d.at, by: d.by, what: d.approved ? (d.edited ? 'Changed' : 'Approved') : 'Denied' })), ...(run.answers ?? []).map((a) => ({ at: a.at, by: a.by, what: 'Answered' }))]
11
+ .sort((a, b) => a.at.localeCompare(b.at)).pop();
12
+ if (!last)
13
+ return 'Done automatically';
14
+ return last.by ? `${last.what} by ${last.by}` : last.what;
15
+ }
1
16
  const OUTSIDE = 'p-';
2
17
  function short(text, max) {
3
18
  const flat = text.replace(/\s+/g, ' ').trim();
@@ -13,6 +28,9 @@ function titleOf(run, workflowTitle) {
13
28
  function questionOf(p) {
14
29
  return typeof p.args.question === 'string' ? p.args.question : p.reason;
15
30
  }
31
+ /** `view`: "needs" (waiting on a person, oldest first, however long),
32
+ * "recent" (the last RECENT_DAYS days, latest first), or "auto" (needs
33
+ * when anything waits, else recent). `open` is the older name for needs. */
16
34
  export async function listInbox(deps, filter = {}) {
17
35
  const [runs, pending] = await Promise.all([deps.runs(), deps.pending()]);
18
36
  const bySession = new Map();
@@ -22,34 +40,41 @@ export async function listInbox(deps, filter = {}) {
22
40
  const items = runs.map((run) => {
23
41
  const wfTitle = deps.workflowTitle(run.agent, run.workflow_id) ?? (run.workflow_id || 'One-off job');
24
42
  const waits = run.status === 'awaiting_approval' ? (bySession.get(run.session_id) ?? []) : [];
25
- const lastBy = [...(run.decisions ?? []), ...(run.answers ?? [])].sort((a, b) => a.at.localeCompare(b.at)).pop()?.by;
43
+ const decided = [...(run.decisions ?? []), ...(run.answers ?? [])].sort((a, b) => a.at.localeCompare(b.at));
44
+ const lastBy = decided.at(-1)?.by;
45
+ const since = waits.map((p) => p.createdAt).filter((t) => Boolean(t)).sort()[0];
46
+ const lastActivity = [run.started_at, run.finished_at, decided.at(-1)?.at].filter((t) => Boolean(t)).sort().at(-1);
26
47
  return {
27
48
  id: run.run_id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, status: run.status,
28
49
  waiting: [...new Set(waits.map((p) => p.kind))], startedAt: run.started_at, ...(run.finished_at ? { finishedAt: run.finished_at } : {}), ...(lastBy ? { lastBy } : {}),
50
+ ...(waits.length ? { waitingSince: since ?? run.started_at } : {}), lastActivity, outcome: outcomeOf(run, waits.length > 0),
29
51
  };
30
52
  });
31
53
  for (const p of pending) {
32
54
  if (runSessions.has(p.sessionId))
33
55
  continue;
56
+ const at = p.createdAt ?? new Date(0).toISOString();
34
57
  items.push({
35
58
  id: OUTSIDE + p.pendingId, title: short(p.kind === 'question' ? questionOf(p) : `Approve ${p.tool}`, 120), agent: p.agent, workflowId: '', workflowTitle: 'Chat',
36
- status: 'awaiting_approval', waiting: [p.kind], startedAt: p.createdAt ?? new Date(0).toISOString(),
59
+ status: 'awaiting_approval', waiting: [p.kind], startedAt: at, waitingSince: at, lastActivity: at, outcome: 'Waiting',
37
60
  });
38
61
  }
39
62
  const open = items.filter((i) => i.waiting.length).length;
63
+ const view = filter.open || filter.view === 'needs' ? 'needs' : filter.view === 'recent' ? 'recent' : open ? 'needs' : 'recent';
64
+ const recentSince = new Date((filter.now ?? Date.now()) - RECENT_DAYS * 24 * 60 * 60 * 1000).toISOString();
40
65
  const q = filter.q?.trim().toLowerCase();
41
66
  const runParams = new Map(runs.map((r) => [r.run_id, Object.values(r.params ?? {}).join(' ')]));
42
67
  const shown = items
43
- .filter((i) => !filter.open || i.waiting.length)
68
+ .filter((i) => (view === 'needs' ? i.waiting.length > 0 : !i.waiting.length && i.lastActivity >= recentSince))
44
69
  .filter((i) => !filter.workflow || i.workflowId === filter.workflow)
45
- .filter((i) => !q || `${i.title} ${i.agent} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''}`.toLowerCase().includes(q))
46
- // Waiting first, newest first within each.
47
- .sort((a, b) => (b.waiting.length ? 1 : 0) - (a.waiting.length ? 1 : 0) || b.startedAt.localeCompare(a.startedAt));
70
+ .filter((i) => !q || `${i.title} ${i.agent} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''} ${i.outcome}`.toLowerCase().includes(q))
71
+ // Waiting: the longest-waiting first. Recent: the latest first.
72
+ .sort((a, b) => (view === 'needs' ? (a.waitingSince ?? '').localeCompare(b.waitingSince ?? '') : b.lastActivity.localeCompare(a.lastActivity)));
48
73
  // Every workflow with a case, whatever the filter, for the workflow picker.
49
74
  const workflows = [...new Map(items.filter((i) => i.workflowId).map((i) => [i.workflowId, i.workflowTitle])).entries()]
50
75
  .map(([id, title]) => ({ id, title }))
51
76
  .sort((a, b) => a.title.localeCompare(b.title));
52
- return { items: shown.slice(0, filter.limit ?? 200), open, workflows };
77
+ return { items: shown.slice(0, filter.limit ?? 200), open, view, workflows };
53
78
  }
54
79
  /** What the agent did, in order: its words, the tools it used with what
55
80
  * came back, and the questions it asked with their answers. The run's