loopengine 0.4.5 → 0.4.7

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.
@@ -59,6 +59,15 @@ export const auditPageHtml = `<!doctype html>
59
59
  .au-state.bad { background: var(--bad-soft); color: var(--bad); }
60
60
  .au-state.warn { background: var(--warn-soft); color: var(--warn); }
61
61
  .au-state.run { background: var(--accent-soft); color: var(--accent-ink); }
62
+ .au-evalcase { color: var(--accent-ink); font-weight: 600; }
63
+ .chg { display: grid; gap: 6px; margin-top: 4px; font-size: 12.5px; flex-basis: 100%; }
64
+ .chg-field del { color: var(--bad); }
65
+ .chg-field ins { color: var(--good); text-decoration: none; }
66
+ .chg-lines { display: grid; gap: 1px; margin-top: 3px; font-family: var(--font-mono); font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
67
+ .chg-del { background: var(--bad-soft); color: var(--bad); padding: 1px 6px; }
68
+ .chg-ins { background: var(--good-soft); color: var(--good); padding: 1px 6px; }
69
+ .chg-note { color: var(--ink-muted); font-family: inherit; font-weight: 400; }
70
+ .chg details summary { cursor: pointer; color: var(--accent-ink); font-family: var(--font-sans, inherit); font-size: 12px; margin-top: 2px; }
62
71
  .au-empty { padding: 28px 16px; text-align: center; color: var(--ink-muted); font-size: 13.5px; }
63
72
  .au-more { justify-self: center; }
64
73
  .error { font-size: 13px; color: var(--bad); margin: 0; }
@@ -91,6 +100,9 @@ ${consoleSidebarHtml}
91
100
  <select id="auKind" aria-label="Kind">
92
101
  <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>
93
102
  </select>
103
+ <select id="auFlag" aria-label="Worth a look" hidden>
104
+ <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>
105
+ </select>
94
106
  <select id="auStatus" aria-label="Status" hidden>
95
107
  <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>
96
108
  </select>
@@ -117,7 +129,7 @@ ${consoleShellScript}
117
129
  var state = {
118
130
  tab: params.get('tab') === 'cases' ? 'cases' : 'activity',
119
131
  agent: params.get('agent') || '', workflow: params.get('workflow') || '', by: params.get('by') || '',
120
- kind: params.get('kind') || '', status: params.get('status') || '',
132
+ kind: params.get('kind') || '', status: params.get('status') || '', flag: params.get('flag') || '',
121
133
  period: params.has('period') ? params.get('period') : '30', q: params.get('q') || '',
122
134
  };
123
135
  // The filters' choices come with the page (auditPageFor), so they show
@@ -129,7 +141,7 @@ ${consoleShellScript}
129
141
  var more = document.getElementById('auMore');
130
142
  var el = {
131
143
  agent: document.getElementById('auAgent'), workflow: document.getElementById('auWorkflow'), by: document.getElementById('auBy'),
132
- kind: document.getElementById('auKind'), status: document.getElementById('auStatus'), period: document.getElementById('auPeriod'),
144
+ kind: document.getElementById('auKind'), status: document.getElementById('auStatus'), flag: document.getElementById('auFlag'), period: document.getElementById('auPeriod'),
133
145
  q: document.getElementById('auQ'), exportLink: document.getElementById('auExport'),
134
146
  };
135
147
 
@@ -166,6 +178,7 @@ ${consoleShellScript}
166
178
  if (state.by) q.set('by', state.by);
167
179
  if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
168
180
  if (state.tab === 'cases' && state.status) q.set('status', state.status);
181
+ if (state.tab === 'cases' && state.flag) q.set('flag', state.flag);
169
182
  if (state.period) q.set('since', new Date(Date.now() - Number(state.period) * 86400000).toISOString());
170
183
  if (state.q) q.set('q', state.q);
171
184
  Object.keys(extra || {}).forEach(function (k) { q.set(k, extra[k]); });
@@ -178,6 +191,7 @@ ${consoleShellScript}
178
191
  ['agent', 'workflow', 'by', 'q'].forEach(function (k) { if (state[k]) q.set(k, state[k]); });
179
192
  if (state.tab === 'activity' && state.kind) q.set('kind', state.kind);
180
193
  if (state.tab === 'cases' && state.status) q.set('status', state.status);
194
+ if (state.tab === 'cases' && state.flag) q.set('flag', state.flag);
181
195
  if (state.period !== '30') q.set('period', state.period);
182
196
  history.replaceState(null, '', '/audit' + (q.toString() ? '?' + q.toString() : ''));
183
197
  }
@@ -186,7 +200,7 @@ ${consoleShellScript}
186
200
  // the agent, or the workspace setting.
187
201
  function eventLink(e) {
188
202
  var d = e.data || {};
189
- if (e.run_id) return { href: '/inbox?case=' + encodeURIComponent(e.run_id), text: 'Case' };
203
+ if (e.run_id) return { href: '/cases/' + encodeURIComponent(e.run_id) + '?back=' + encodeURIComponent(location.pathname + location.search), text: 'Case' };
190
204
  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' };
191
205
  if (e.agent) return { href: '/agents/config?agent=' + encodeURIComponent(e.agent), text: 'Agent' };
192
206
  var path = String(d.path || '');
@@ -205,6 +219,27 @@ ${consoleShellScript}
205
219
  return { what: 'Feedback' + (v ? ': ' + v : ''), detail: d.note || '' };
206
220
  }
207
221
 
222
+ // A change's details: each setting from and to, and for long texts the
223
+ // lines added (+) and removed (−), a few shown and the rest folded.
224
+ function changeDetailsHtml(d) {
225
+ var list = d.changes || [];
226
+ if (!list.length && !d.brief) return '';
227
+ var MINUS = String.fromCharCode(8722);
228
+ var lineHtml = function (sign, cls, l) { return '<div class="' + cls + '">' + sign + ' ' + esc(l) + '</div>'; };
229
+ var rows = list.map(function (c) {
230
+ if (c.added || c.removed) {
231
+ var lines = (c.removed || []).map(function (l) { return lineHtml(MINUS, 'chg-del', l); }).concat((c.added || []).map(function (l) { return lineHtml('+', 'chg-ins', l); }));
232
+ var head = '<strong>' + esc(c.field) + '</strong>' + (c.field === 'instructions' && d.brief ? ' <span class="chg-note">brief v' + d.brief.from + ' ' + String.fromCharCode(8594) + ' v' + d.brief.to + '</span>' : '');
233
+ var shown = lines.slice(0, 6).join('');
234
+ var more = lines.length > 6 ? '<details><summary>' + (lines.length - 6) + ' more line' + (lines.length - 6 === 1 ? '' : 's') + '</summary>' + lines.slice(6).join('') + '</details>' : '';
235
+ return '<div class="chg-field">' + head + '<div class="chg-lines">' + (shown || '<div class="chg-note">Only spacing changed.</div>') + more + '</div></div>';
236
+ }
237
+ return '<div class="chg-field"><strong>' + esc(c.field) + '</strong>: <del>' + esc(c.from) + '</del> ' + String.fromCharCode(8594) + ' <ins>' + esc(c.to) + '</ins></div>';
238
+ }).join('');
239
+ if (!rows && d.brief) rows = '<div class="chg-field">brief v' + d.brief.from + ' ' + String.fromCharCode(8594) + ' v' + d.brief.to + '</div>';
240
+ return '<div class="chg">' + rows + '</div>';
241
+ }
242
+
208
243
  function eventRow(e) {
209
244
  var words = eventWords(e);
210
245
  var link = eventLink(e);
@@ -213,7 +248,7 @@ ${consoleShellScript}
213
248
  var where = agentLabel(e.agent) + (e.workflow_id ? DOT + workflowTitle(e.agent, e.workflow_id) : '');
214
249
  return '<div class="au-row"><span class="au-when">' + esc(when(e.at)) + '</span>' +
215
250
  '<span class="au-kind ' + esc(e.kind) + denied + '">' + kind + '</span>' +
216
- '<span class="au-what"><strong>' + esc(words.what) + '</strong>' + (words.detail ? '<span class="au-detail">' + esc(words.detail) + '</span>' : '') +
251
+ '<span class="au-what"><strong>' + esc(words.what) + '</strong>' + (words.detail ? '<span class="au-detail">' + esc(words.detail) + '</span>' : '') + (e.kind === 'change' ? changeDetailsHtml(e.data || {}) : '') +
217
252
  '<span class="au-where">' + (e.by ? esc(e.by) + DOT : '') + esc(where) + '</span></span>' +
218
253
  '<a class="au-open" href="' + esc(link.href) + '">' + esc(link.text) + ' ' + String.fromCharCode(8594) + '</a></div>';
219
254
  }
@@ -223,8 +258,8 @@ ${consoleShellScript}
223
258
  return '<div class="au-row au-case"><span class="au-state ' + pill[0] + '">' + pill[1] + '</span>' +
224
259
  '<span class="au-what"><strong>' + esc(c.workflowTitle) + (c.inputs ? DOT + esc(c.inputs) : '') + '</strong>' +
225
260
  (c.outcome ? '<span class="au-detail">' + esc(c.outcome) + '</span>' : '') +
226
- '<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>' +
227
- '<a class="au-open" href="/inbox?case=' + encodeURIComponent(c.id) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
261
+ '<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>' +
262
+ '<a class="au-open" href="/cases/' + encodeURIComponent(c.id) + '?back=' + encodeURIComponent(location.pathname + location.search) + '">Open ' + String.fromCharCode(8594) + '</a></div>';
228
263
  }
229
264
 
230
265
  function load(append) {
@@ -261,6 +296,7 @@ ${consoleShellScript}
261
296
  for (var i = 0; i < tabs.length; i++) tabs[i].setAttribute('aria-selected', String(tabs[i].getAttribute('data-tab') === state.tab));
262
297
  el.kind.hidden = state.tab !== 'activity';
263
298
  el.status.hidden = state.tab !== 'cases';
299
+ el.flag.hidden = state.tab !== 'cases';
264
300
  el.exportLink.hidden = state.tab !== 'activity';
265
301
  verifyBtn.hidden = state.tab !== 'activity';
266
302
  el.exportLink.href = '/audit/events.csv?' + query();
@@ -301,7 +337,7 @@ ${consoleShellScript}
301
337
  changed();
302
338
  });
303
339
  el.agent.addEventListener('change', function () { state.agent = el.agent.value; fillWorkflows(); changed(); });
304
- ['workflow', 'by', 'kind', 'status', 'period'].forEach(function (k) {
340
+ ['workflow', 'by', 'kind', 'status', 'flag', 'period'].forEach(function (k) {
305
341
  el[k].addEventListener('change', function () { state[k] = el[k].value; changed(); });
306
342
  });
307
343
  var typing;
@@ -311,14 +347,12 @@ ${consoleShellScript}
311
347
  });
312
348
  more.addEventListener('click', function () { load(true); });
313
349
 
314
- // Checks every event's hash, in order, and the anchors sent away.
350
+ // Checks every event's hash, in order.
315
351
  var verifyBtn = document.getElementById('auVerify');
316
352
  var check = document.getElementById('auCheck');
317
353
  var PROBLEMS = {
318
354
  'changed': 'it was changed after it was recorded',
319
355
  'missing-before': 'an event before it was removed, or the order changed',
320
- 'missing-after-anchor': 'events up to an anchored point are missing',
321
- 'anchor-differs': 'it no longer matches the hash anchored for it',
322
356
  };
323
357
  verifyBtn.addEventListener('click', function () {
324
358
  verifyBtn.disabled = true;
@@ -328,15 +362,13 @@ ${consoleShellScript}
328
362
  fetch('/audit/verify', { headers: { accept: 'application/json' } })
329
363
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
330
364
  .then(function (v) {
331
- var anchors = v.anchors ? v.anchors + ' anchor' + (v.anchors === 1 ? '' : 's') + ' kept at ' + v.anchoredAt + ' match' + (v.anchors === 1 ? 'es' : '') : 'no anchors yet (one is sent each day)';
332
- var note = v.anchorsNote ? '<span class="hint">Anchors checked are this workspace' + String.fromCharCode(8217) + 's own: ' + esc(v.anchorsNote) + '.</span>' : '';
333
365
  if (v.ok) {
334
- check.innerHTML = 'Intact: all ' + v.events.toLocaleString() + ' events check out, and ' + anchors + '.' +
335
- (v.last ? '<span class="hint">Latest event #' + v.last.id + ', ' + esc(when(v.last.at)) + DOT + 'hash ' + esc(v.last.hash.slice(0, 16)) + String.fromCharCode(8230) + '</span>' : '') + note;
366
+ check.innerHTML = 'Intact: all ' + v.events.toLocaleString() + ' events check out.' +
367
+ (v.last ? '<span class="hint">Latest event #' + v.last.id + ', ' + esc(when(v.last.at)) + DOT + 'hash ' + esc(v.last.hash) + '</span>' : '');
336
368
  } else {
337
369
  check.className = 'au-check bad';
338
370
  check.innerHTML = 'Broken at event #' + v.broken.id + (v.broken.at ? ' (' + esc(when(v.broken.at)) + ')' : '') + ': ' + esc(PROBLEMS[v.broken.problem] || v.broken.problem) + '.' +
339
- '<span class="hint">' + v.events.toLocaleString() + ' events before it check out.</span>' + note;
371
+ '<span class="hint">' + v.events.toLocaleString() + ' events before it check out.</span>';
340
372
  }
341
373
  })
342
374
  .catch(function (err) { check.className = 'au-check bad'; check.textContent = 'Could not check: ' + err.message; })
@@ -346,6 +378,7 @@ ${consoleShellScript}
346
378
  el.q.value = state.q;
347
379
  el.kind.value = state.kind;
348
380
  el.status.value = state.status;
381
+ el.flag.value = state.flag;
349
382
  el.period.value = state.period;
350
383
  function fillFilters(f) {
351
384
  filters = f;
@@ -10,3 +10,16 @@ export declare function changeOf(method: string, path: string): Change | undefin
10
10
  /** A body as kept in the log: secret-looking fields blanked, long text
11
11
  * cut. Secrets' bodies are dropped whole. */
12
12
  export declare function keptBody(path: string, body: unknown): unknown;
13
+ /** One setting a change touched: short values from and to, or for a
14
+ * long text (instructions, policies) the lines added and removed. */
15
+ export interface FieldChange {
16
+ field: string;
17
+ from?: string;
18
+ to?: string;
19
+ added?: string[];
20
+ removed?: string[];
21
+ }
22
+ export declare function describeChanges(before: Record<string, unknown>, after: Record<string, unknown>): FieldChange[];
23
+ /** The changes in a line: "instructions: 2 lines added, 1 removed; title:
24
+ * Refunds → Refund check". */
25
+ export declare function changesSummary(changes: FieldChange[]): string;
@@ -85,3 +85,70 @@ function redact(value, depth) {
85
85
  }
86
86
  return value;
87
87
  }
88
+ const showValue = (v) => {
89
+ if (v === undefined || v === null || v === '')
90
+ return '(none)';
91
+ const text = typeof v === 'string' ? v : JSON.stringify(v);
92
+ return text.length > 200 ? text.slice(0, 199) + '…' : text;
93
+ };
94
+ // Lines in `after` and not `before`, and the reverse, in order (the same
95
+ // longest-common-subsequence diff the workflow audit uses).
96
+ function lineChanges(before, after) {
97
+ const a = before.split('\n');
98
+ const b = after.split('\n');
99
+ if (a.length * b.length > 4_000_000) {
100
+ const inA = new Set(a);
101
+ const inB = new Set(b);
102
+ return { added: b.filter((l) => !inA.has(l) && l.trim()), removed: a.filter((l) => !inB.has(l) && l.trim()) };
103
+ }
104
+ const t = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
105
+ for (let i = a.length - 1; i >= 0; i--)
106
+ for (let j = b.length - 1; j >= 0; j--)
107
+ t[i][j] = a[i] === b[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]);
108
+ const added = [];
109
+ const removed = [];
110
+ let i = 0;
111
+ let j = 0;
112
+ while (i < a.length && j < b.length) {
113
+ if (a[i] === b[j]) {
114
+ i++;
115
+ j++;
116
+ }
117
+ else if (t[i + 1][j] >= t[i][j + 1])
118
+ removed.push(a[i++]);
119
+ else
120
+ added.push(b[j++]);
121
+ }
122
+ removed.push(...a.slice(i));
123
+ added.push(...b.slice(j));
124
+ return { added: added.filter((l) => l.trim()).map((l) => l.slice(0, 300)), removed: removed.filter((l) => l.trim()).map((l) => l.slice(0, 300)) };
125
+ }
126
+ /** What differs between two snapshots of the same settings, field by
127
+ * field. A text of several lines, or a long one, is told as lines added
128
+ * and removed; anything else as its value before and after. */
129
+ // Always told as lines, however short: what an agent reads.
130
+ const TEXT_FIELDS = new Set(['instructions', 'shared policies', 'checklist']);
131
+ export function describeChanges(before, after) {
132
+ const out = [];
133
+ for (const field of [...new Set([...Object.keys(before), ...Object.keys(after)])]) {
134
+ const b = before[field];
135
+ const a = after[field];
136
+ if (JSON.stringify(b) === JSON.stringify(a))
137
+ continue;
138
+ const long = (v) => typeof v === 'string' && (TEXT_FIELDS.has(field) || v.includes('\n') || v.length > 200);
139
+ if (long(b) || long(a)) {
140
+ const { added, removed } = lineChanges(typeof b === 'string' ? b : '', typeof a === 'string' ? a : '');
141
+ out.push({ field, added: added.slice(0, 40), removed: removed.slice(0, 40) });
142
+ }
143
+ else
144
+ out.push({ field, from: showValue(b), to: showValue(a) });
145
+ }
146
+ return out;
147
+ }
148
+ /** The changes in a line: "instructions: 2 lines added, 1 removed; title:
149
+ * Refunds → Refund check". */
150
+ export function changesSummary(changes) {
151
+ return changes.map((c) => (c.added || c.removed
152
+ ? `${c.field}: ${c.added?.length ?? 0} line${c.added?.length === 1 ? '' : 's'} added, ${c.removed?.length ?? 0} removed`
153
+ : `${c.field}: ${c.from} → ${c.to}`)).join('; ');
154
+ }
@@ -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');
@@ -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