loopengine 0.5.0 → 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.
@@ -1,12 +1,14 @@
1
- // The console's Inbox, for acting: /inbox shows what needs a person
2
- // (Needs you, however long it has waited, the longest first) and every
3
- // case from the last 7 days (Recent: done automatically, decided by
4
- // someone, or failed); older cases are searched in Audit. A case is its
5
- // own page, /cases/<id> (?back= is where its back link goes): what it
6
- // was given, what the agent did, what it asks now (answer, approve,
7
- // approve as changed, deny), who decided what, and Save as eval case
8
- // (web/inbox-admin.ts behind /inbox/*). An approver or viewer sees only this page; a viewer can't
9
- // decide. Like the other console pages, its inline script avoids
1
+ // The console's Inbox, for acting: every workflow run as a conversation
2
+ // between the agent and the people it works for. The list (All, Needs
3
+ // attention, Completed, Failed, Archived) shows each as its title, its
4
+ // agent and workflow, where it stands, what it last said and when; one
5
+ // opens beside it as a thread: what started it, what the agent said and
6
+ // did, what it asked and the answers and decisions people gave, how it
7
+ // ended, and (when it waits) the question to answer or the approval to
8
+ // give, right there (web/inbox-admin.ts behind /inbox/*). A run's trace,
9
+ // its record to download and saving it as an eval case are on its
10
+ // workflow's Activity tab. An approver or viewer sees only this page; a
11
+ // viewer can't decide. Like the other console pages, its inline script avoids
10
12
  // backslashes and template placeholders, since it lives inside a template
11
13
  // literal.
12
14
  import { devUiCss } from './dev-ui-styles.js';
@@ -21,26 +23,70 @@ export const inboxPageHtml = `<!doctype html>
21
23
  <style>${devUiCss}
22
24
  .ib { max-width: 980px; display: grid; gap: 16px; }
23
25
  .ib-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
24
- .ib-filter { display: inline-flex; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
25
- .ib-filter button { border: 0; border-radius: 0; background: var(--bg); padding: 6px 12px; font-size: 13px; font-weight: 600; color: var(--ink-muted); }
26
- .ib-filter button[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-ink); }
27
26
  .ib-bar select, .ib-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); }
28
27
  .ib-bar input { flex: 1; min-width: 160px; }
29
- .ib-list { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--bg); }
30
- .ib-row { display: grid; grid-template-columns: 12px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 12px 16px; border-top: 1px solid var(--line); color: var(--ink); text-decoration: none; }
31
- .ib-row:first-child { border-top: 0; }
32
- .ib-row:hover { background: var(--surface); }
33
- .ib-row-title { font-weight: 600; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
34
- .ib-row-meta { font-size: 12.5px; color: var(--ink-muted); }
35
- .ib-row-side { display: flex; flex-direction: column; align-items: flex-end; gap: 2px; font-size: 12px; color: var(--ink-muted); white-space: nowrap; }
36
28
  .ib-state { font-size: 11.5px; font-weight: 700; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--ink-muted); }
37
29
  .ib-state.warn { background: var(--warn-soft); color: var(--warn); }
38
30
  .ib-state.good { background: var(--good-soft); color: var(--good); }
39
31
  .ib-state.bad { background: var(--bad-soft); color: var(--bad); }
40
32
  .ib-state.run { background: var(--accent-soft); color: var(--accent-ink); }
33
+ body[data-le-page="inbox"] .le-page { max-width: 1320px; }
34
+ .ib.is-inbox { max-width: none; }
35
+ .ib-tabs { display: flex; flex-wrap: wrap; gap: 2px; border-bottom: 1px solid var(--line); }
36
+ .ib-tabs button { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; height: auto; padding: 8px 12px; margin-bottom: -1px; font-size: 13.5px; font-weight: 600; color: var(--ink-muted); }
37
+ .ib-tabs button[aria-selected="true"] { color: var(--accent-ink); border-bottom-color: var(--accent); }
38
+ .ib-tabs .ib-count { margin-left: 6px; font-size: 11px; padding: 1px 7px; border-radius: 999px; background: var(--surface-2); color: var(--ink-muted); }
39
+ .ib-tabs button[data-view="needs"] .ib-count.on { background: var(--warn-soft); color: var(--warn); }
40
+ .ib-split { display: grid; grid-template-columns: minmax(280px, 380px) minmax(0, 1fr); gap: 16px; align-items: start; }
41
+ .ib-items { display: grid; gap: 8px; align-content: start; max-height: calc(100vh - 230px); overflow: auto; padding: 2px; }
42
+ .ib-item { display: grid; gap: 5px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--ink); text-decoration: none; }
43
+ .ib-item:hover { border-color: var(--ink-faint); }
44
+ .ib-item.is-selected { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
45
+ .ib-item.is-needs { border-left: 3px solid var(--warn); }
46
+ .ib-item-title { font-weight: 700; font-size: 14px; line-height: 1.3; overflow-wrap: anywhere; }
47
+ .ib-item-meta { font-size: 12.5px; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
48
+ .ib-item .ib-state { justify-self: start; }
49
+ .ib-item-summary { margin: 0; font-size: 13px; line-height: 1.45; color: var(--ink); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
50
+ .ib-item-time { font-size: 12px; color: var(--ink-faint); }
51
+ .ib-item-time.late { color: var(--warn); font-weight: 700; }
52
+ .ib-thread { border: 1px solid var(--line); border-radius: 12px; background: var(--bg); min-width: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); max-height: calc(100vh - 230px); }
53
+ .ib-thread-empty { padding: 48px 24px; text-align: center; color: var(--ink-muted); font-size: 13.5px; }
54
+ .ib-thread-head { display: grid; gap: 6px; padding: 14px 18px; border-bottom: 1px solid var(--line); }
55
+ .ib-thread-head h2 { margin: 0; font-size: 17px; letter-spacing: -0.01em; overflow-wrap: anywhere; }
56
+ .ib-thread-top { display: flex; align-items: flex-start; gap: 10px; }
57
+ .ib-thread-top h2 { flex: 1; min-width: 0; }
58
+ .ib-thread-tools { display: flex; gap: 8px; align-items: center; flex-shrink: 0; }
59
+ .ib-thread-tools a, .ib-thread-tools button { height: 30px; padding: 0 12px; border-radius: 8px; font-size: 12.5px; font-weight: 600; border: 1px solid var(--line); background: var(--bg); color: var(--ink); text-decoration: none; display: inline-flex; align-items: center; cursor: pointer; }
60
+ .ib-thread-tools .ib-thread-back { display: none; }
61
+ .ib-msgs { list-style: none; margin: 0; padding: 16px 18px 20px; display: grid; gap: 12px; overflow: auto; align-content: start; }
62
+ .ib-msg { display: grid; gap: 4px; max-width: 86%; min-width: 0; }
63
+ .ib-msg.person { justify-self: end; justify-items: end; }
64
+ .ib-msg.system { justify-self: center; justify-items: center; max-width: 100%; }
65
+ .ib-msg-who { font-size: 11.5px; color: var(--ink-muted); }
66
+ .ib-msg-who strong { color: var(--ink); font-weight: 600; }
67
+ .ib-bubble { padding: 10px 14px; border-radius: 14px; background: var(--surface); font-size: 14px; line-height: 1.5; min-width: 0; max-width: 100%; overflow-wrap: anywhere; box-sizing: border-box; }
68
+ .ib-msg.agent .ib-bubble { border-top-left-radius: 4px; }
69
+ .ib-msg.person .ib-bubble { background: var(--accent-soft); color: var(--ink); border-top-right-radius: 4px; }
70
+ .ib-msg.person.is-denied .ib-bubble { background: var(--bad-soft); }
71
+ .ib-msg.system .ib-bubble { background: none; border: 1px dashed var(--line); font-size: 12.5px; color: var(--ink-muted); padding: 8px 12px; }
72
+ .ib-msg.system .ib-kv { text-align: left; margin-top: 6px; color: var(--ink); }
73
+ .ib-msg.failed .ib-bubble { background: var(--bad-soft); color: var(--bad); }
74
+ .ib-msg.ask .ib-bubble { background: var(--bg); border: 1px solid var(--warn); box-shadow: 0 0 0 3px var(--warn-soft); width: 100%; display: grid; gap: 10px; }
75
+ .ib-msg.ask { max-width: 100%; width: 100%; }
76
+ .ib-msg.ask .ib-card { border: 0; padding: 0; box-shadow: none; background: none; }
77
+ .ib-act { justify-self: start; display: grid; gap: 4px; font-size: 12.5px; color: var(--ink-muted); max-width: 100%; min-width: 0; }
78
+ .ib-act summary { cursor: pointer; }
79
+ .ib-act summary code { font-size: 12px; }
80
+ .ib-act.failed summary { color: var(--bad); }
81
+ .ib-typing { font-size: 13px; color: var(--ink-muted); font-style: italic; }
82
+ @media (max-width: 860px) {
83
+ .ib-split { grid-template-columns: minmax(0, 1fr); }
84
+ .ib-split.has-thread .ib-items { display: none; }
85
+ .ib-split:not(.has-thread) .ib-thread { display: none; }
86
+ .ib-thread-tools .ib-thread-back { display: inline-flex; }
87
+ .ib-items, .ib-thread { max-height: none; }
88
+ }
41
89
  .ib-empty { padding: 28px 16px; text-align: center; color: var(--ink-muted); font-size: 13.5px; }
42
- .ib-back { font-size: 13px; color: var(--accent-ink); text-decoration: none; font-weight: 600; }
43
- .ib-case-head h2 { margin: 4px 0 6px; font-size: 20px; letter-spacing: -0.01em; }
44
90
  .ib-link { color: var(--accent-ink); font-weight: 600; text-decoration: none; }
45
91
  .ib-link:hover { text-decoration: underline; }
46
92
  .ib-chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: 12.5px; color: var(--ink-muted); }
@@ -50,21 +96,6 @@ export const inboxPageHtml = `<!doctype html>
50
96
  .ib-kv { display: grid; grid-template-columns: minmax(110px, max-content) 1fr; gap: 6px 14px; font-size: 13.5px; }
51
97
  .ib-kv dt { color: var(--ink-muted); font-family: var(--font-mono); font-size: 12.5px; padding-top: 1px; }
52
98
  .ib-kv dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
53
- .ib-trace-sum { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0; font-size: 13px; padding: 10px 12px; background: var(--surface); border-radius: 10px; }
54
- .ib-trace-sum dt { color: var(--ink-muted); }
55
- .ib-trace-sum dd { margin: 0; overflow-wrap: anywhere; }
56
- .ib-trace-span.event { background: var(--surface); }
57
- .ib-trace-list { list-style: none; margin: 10px 0 0; padding: 0; display: grid; gap: 8px; }
58
- .ib-trace-span { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; display: grid; gap: 6px; }
59
- .ib-trace-span.err { border-color: var(--bad); }
60
- .ib-trace-head { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; }
61
- .ib-trace-kind { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--accent-ink); }
62
- .ib-trace-span.tool .ib-trace-kind { color: var(--ink-muted); }
63
- .ib-trace-meta { font-size: 12.5px; color: var(--ink-muted); }
64
- .ib-trace-span details > summary { cursor: pointer; font-size: 13px; color: var(--ink-muted); }
65
- .ib-trace-span details .ib-pre { margin-top: 6px; }
66
- .ib-trace-tools { display: flex; flex-wrap: wrap; gap: 4px; }
67
- .ib-trace-tools code { font-size: 12px; background: var(--surface); padding: 1px 6px; border-radius: 6px; }
68
99
  .ib-pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; background: var(--surface); padding: 10px 12px; border-radius: 8px; max-height: 360px; overflow: auto; }
69
100
  .ib-question { margin: 0; font-size: 14.5px; }
70
101
  .ib-card textarea { width: 100%; box-sizing: border-box; min-height: 80px; font: inherit; font-size: 14px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); color: var(--ink); resize: vertical; }
@@ -74,29 +105,6 @@ export const inboxPageHtml = `<!doctype html>
74
105
  .ib-btn.plain { background: none; border-color: var(--line); color: var(--ink); font-weight: 500; }
75
106
  .ib-btn.bad { background: var(--bad-soft); border-color: var(--bad); color: var(--bad); }
76
107
  .ib-btn.opt { background: var(--accent-soft); color: var(--accent-ink); border-color: transparent; font-weight: 500; }
77
- .ib-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
78
- .ib-step { display: grid; gap: 4px; padding-left: 14px; border-left: 2px solid var(--line); font-size: 13.5px; }
79
- .ib-step.q { border-left-color: var(--warn); }
80
- .ib-step-k { font-size: 12px; font-weight: 700; color: var(--ink-muted); }
81
- .ib-step-meta { font-weight: 400; color: var(--ink-faint); margin-left: 8px; }
82
- .ib-totals { margin: -4px 0 10px; font-size: 12.5px; color: var(--ink-muted); }
83
- .ib-export { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
84
- .ib-export a.ib-btn { text-decoration: none; display: inline-flex; align-items: center; }
85
- @media print {
86
- .le-sidebar, .ib-back, .ib-export, .ib-actions, .le-head, .le-menu-btn { display: none !important; }
87
- .le-app { display: block !important; }
88
- .ib-card { break-inside: avoid; }
89
- details { display: block; }
90
- }
91
- .ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
92
- .ib-who { font-size: 13px; display: grid; gap: 4px; }
93
- .ib-late { color: var(--warn); font-weight: 700; }
94
- .ib-older { margin: 0; font-size: 12.5px; }
95
- .ib-suggest { display: grid; gap: 8px; border-top: 1px solid var(--line); padding-top: 10px; }
96
- .ib-suggest[hidden] { display: none; }
97
- .ib-suggest h4 { margin: 0; font-size: 13px; }
98
- .ib-suggest-row { display: flex; gap: 10px; align-items: flex-start; justify-content: space-between; font-size: 13px; }
99
- .ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
100
108
  .ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
101
109
  .ib-change del { color: var(--bad); }
102
110
  .ib-change ins { color: var(--good); text-decoration: none; }
@@ -118,7 +126,7 @@ export const inboxPageHtml = `<!doctype html>
118
126
  .ib-md table { border-collapse: collapse; font-size: 13px; }
119
127
  .ib-md th, .ib-md td { border: 1px solid var(--line); padding: 4px 8px; text-align: left; }
120
128
  .error { font-size: 13px; color: var(--bad); margin: 0; }
121
- @media (max-width: 640px) { .ib-row { grid-template-columns: 12px minmax(0, 1fr); } .ib-row-side { grid-column: 2; align-items: flex-start; flex-direction: row; gap: 8px; } .ib-kv { grid-template-columns: 1fr; } }
129
+ @media (max-width: 640px) { .ib-kv { grid-template-columns: 1fr; } }
122
130
  </style>
123
131
  </head>
124
132
  <body data-le-page="inbox">
@@ -128,7 +136,7 @@ ${consoleSidebarHtml}
128
136
  <div class="le-head plain">
129
137
  <div class="le-head-row">
130
138
  <div class="le-title"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">&#9776;</button>
131
- <div><h1>Inbox</h1><p>Questions and approvals from your agents' runs, and the history of each case: what it was given, what the agent did and who decided what.</p></div>
139
+ <div><h1>Inbox</h1><p>Your conversations with your agents' workflow runs: what each asks you, what it did, and how it ended.</p></div>
132
140
  </div>
133
141
  </div>
134
142
  </div>
@@ -143,14 +151,14 @@ ${renderMarkdownScript}
143
151
  var ELLIPSIS = String.fromCharCode(8230);
144
152
  var DOT = ' ' + String.fromCharCode(183) + ' ';
145
153
  var params = new URLSearchParams(location.search);
146
- // Needs you (waiting on a person, however long) or Recent (the last 7
147
- // days); none asked: needs you when anything waits.
148
- var state = { view: params.get('open') === '1' ? 'needs' : params.get('view') || '', q: params.get('q') || '', workflow: params.get('workflow') || '' };
149
- // A case's own page is /cases/<id>; ?back= is where its back link goes.
150
- var caseMatch = location.pathname.match(/^[/]cases[/]([^/]+)$/);
151
- var caseId = caseMatch ? decodeURIComponent(caseMatch[1]) : '';
152
- var back = params.get('back');
153
- if (!back || back.charAt(0) !== '/' || back.charAt(1) === '/') back = '/inbox';
154
+ // All, Needs attention, Completed, Failed or Archived; none asked:
155
+ // Needs attention when anything waits, else All. Recent (the older view)
156
+ // is All now. ?item= is the conversation open beside the list.
157
+ var VIEWS = [['all', 'All'], ['needs', 'Needs attention'], ['completed', 'Completed'], ['failed', 'Failed'], ['archived', 'Archived']];
158
+ var asked = params.get('open') === '1' ? 'needs' : params.get('view') === 'recent' ? 'all' : params.get('view') || '';
159
+ var state = { view: VIEWS.some(function (v) { return v[0] === asked; }) ? asked : '', q: params.get('q') || '', workflow: params.get('workflow') || '', item: params.get('item') || '' };
160
+ var listed = null;
161
+ var openThread = null;
154
162
  var fullAccess = !document.querySelector('.le-app.le-inbox-only');
155
163
  var role = 'owner';
156
164
  var workflows = {};
@@ -160,13 +168,19 @@ ${renderMarkdownScript}
160
168
  return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
161
169
  });
162
170
  }
171
+ // 1 hour ago, Yesterday, 3 days ago, then the date.
163
172
  function ago(iso) {
164
173
  if (!iso) return '';
165
- var s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
166
- if (s < 60) return 'just now';
167
- if (s < 3600) return Math.floor(s / 60) + ' min ago';
168
- if (s < 86400) return Math.floor(s / 3600) + ' h ago';
169
- return new Date(iso).toLocaleDateString();
174
+ var d = new Date(iso);
175
+ var s = Math.max(0, (Date.now() - d.getTime()) / 1000);
176
+ if (s < 60) return 'Just now';
177
+ if (s < 3600) { var m = Math.floor(s / 60); return m + (m === 1 ? ' minute ago' : ' minutes ago'); }
178
+ var today = new Date(); today.setHours(0, 0, 0, 0);
179
+ if (d >= today) { var h = Math.floor(s / 3600); return h + (h === 1 ? ' hour ago' : ' hours ago'); }
180
+ var days = Math.round((today - new Date(d.getFullYear(), d.getMonth(), d.getDate())) / 86400000);
181
+ if (days === 1) return 'Yesterday';
182
+ if (days < 7) return days + ' days ago';
183
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: d.getFullYear() === today.getFullYear() ? undefined : 'numeric' });
170
184
  }
171
185
  function when(iso) { return iso ? new Date(iso).toLocaleString() : ''; }
172
186
  function canDecide() { return role !== 'viewer'; }
@@ -178,25 +192,16 @@ ${renderMarkdownScript}
178
192
  if (h < 48) return 'Waiting ' + h + ' h';
179
193
  return 'Waiting ' + Math.floor(h / 24) + ' days';
180
194
  }
181
- // What happened in a recent case.
182
- function outcomeHtml(item) {
183
- var o = item.outcome || '';
184
- var cls = o === 'Failed' ? 'bad' : o === 'Running' ? 'run' : /^Denied/.test(o) ? 'bad' : /^Changed/.test(o) ? 'warn' : 'good';
185
- return '<span class="ib-state ' + cls + '">' + esc(o) + '</span>';
186
- }
187
- // A case's page, coming back here.
188
- function caseHref(id) {
189
- return '/cases/' + encodeURIComponent(id) + '?back=' + encodeURIComponent(pageUrl());
190
- }
191
- function backLabel() {
192
- return back.indexOf('/audit') === 0 ? 'Audit' : back.indexOf('/agents') === 0 ? 'Workflow' : 'Inbox';
195
+ // The run on its workflow's Activity tab, with its trace open.
196
+ function traceHref(c) {
197
+ return '/agents/config?agent=' + encodeURIComponent(c.agent) + '&tab=workflows&workflow=' + encodeURIComponent(c.workflowId) + '&wtab=activity&run=' + encodeURIComponent(c.id);
193
198
  }
194
199
 
195
200
  function stateHtml(item) {
196
- if (item.waiting && item.waiting.length) return '<span class="ib-state warn">' + (item.waiting.indexOf('approval') !== -1 ? 'Needs approval' : 'Question') + '</span>';
201
+ if (item.waiting && item.waiting.length) return '<span class="ib-state warn">' + (item.waiting.indexOf('approval') !== -1 ? 'Approval needed' : 'Question for you') + '</span>';
197
202
  if (item.status === 'running') return '<span class="ib-state run">Running</span>';
198
203
  if (item.status === 'error') return '<span class="ib-state bad">Failed</span>';
199
- if (item.status === 'done') return '<span class="ib-state good">Done</span>';
204
+ if (item.status === 'done') return '<span class="ib-state good">Completed</span>';
200
205
  return '<span class="ib-state">' + esc(item.status) + '</span>';
201
206
  }
202
207
 
@@ -212,57 +217,228 @@ ${renderMarkdownScript}
212
217
  if (state.view) q.set('view', state.view);
213
218
  if (state.q) q.set('q', state.q);
214
219
  if (state.workflow) q.set('workflow', state.workflow);
220
+ if (state.item) q.set('item', state.item);
215
221
  var s = q.toString();
216
222
  return '/inbox' + (s ? '?' + s : '');
217
223
  }
218
224
 
219
- function renderList(data) {
220
- var items = data.items || [];
221
- (data.workflows || []).forEach(function (w) { workflows[w.id] = w.title; });
222
- var options = Object.keys(workflows).sort(function (a, b) { return workflows[a].localeCompare(workflows[b]); }).map(function (id) { return '<option value="' + esc(id) + '"' + (id === state.workflow ? ' selected' : '') + '>' + esc(workflows[id]) + '</option>'; }).join('');
223
- state.view = data.view || state.view || 'recent';
224
- var needs = state.view === 'needs';
225
- var rows = items.map(function (i) {
226
- var waited = i.waitingSince ? Date.now() - new Date(i.waitingSince).getTime() : 0;
227
- var side = needs
228
- ? stateHtml(i) + '<span class="' + (waited > 3 * 86400000 ? 'ib-late' : '') + '">' + esc(waitedFor(waited)) + '</span>'
229
- : outcomeHtml(i) + '<span>' + esc(ago(i.lastActivity)) + '</span>';
230
- return '<a class="ib-row" href="' + caseHref(i.id) + '">' +
231
- '<span class="le-dot' + (i.waiting.length ? ' warn' : i.status === 'running' ? '' : ' idle') + '" aria-hidden="true"></span>' +
232
- '<span style="min-width:0"><div class="ib-row-title">' + esc(i.title) + '</div>' +
233
- '<div class="ib-row-meta">' + esc(i.workflowTitle) + DOT + esc(i.agent) + DOT + 'started ' + esc(ago(i.startedAt)) + '</div></span>' +
234
- '<span class="ib-row-side">' + side + '</span></a>';
235
- }).join('');
225
+ // A conversation in the list: its title, its agent and workflow, where
226
+ // it stands, what it last said, and when.
227
+ function itemHtml(i) {
228
+ var waited = i.waitingSince ? Date.now() - new Date(i.waitingSince).getTime() : 0;
229
+ var late = waited > 3 * 86400000;
230
+ return '<a class="ib-item' + (i.id === state.item ? ' is-selected' : '') + (i.state === 'needs' ? ' is-needs' : '') + '" href="/inbox?item=' + encodeURIComponent(i.id) + '" data-item="' + esc(i.id) + '">' +
231
+ '<span class="ib-item-title">' + esc(i.title) + '</span>' +
232
+ '<span class="ib-item-meta">' + esc(i.agentLabel || i.agent) + DOT + esc(i.workflowTitle) + '</span>' +
233
+ stateHtml(i) +
234
+ (i.summary ? '<p class="ib-item-summary">' + esc(i.summary) + '</p>' : '') +
235
+ '<span class="ib-item-time' + (late ? ' late' : '') + '" title="' + esc(when(i.lastActivity)) + '">' + esc(i.state === 'needs' ? (late ? waitedFor(waited) : ago(i.waitingSince || i.lastActivity)) : ago(i.lastActivity)) + '</span>' +
236
+ '</a>';
237
+ }
238
+
239
+ var EMPTY = {
240
+ all: 'Nothing here yet. Every workflow run shows here as a conversation: what it asks you, what it did and how it ended.',
241
+ needs: 'Nothing needs you right now. Questions and approvals from your agents land here, however long ago they were asked.',
242
+ completed: 'No completed runs.',
243
+ failed: 'Nothing failed.',
244
+ archived: 'Nothing archived. Archive a finished conversation to clear it from All.',
245
+ };
246
+
247
+ // The page around the list: the tabs, the filters, the list and the
248
+ // open conversation. Drawn once; the list and tabs redraw in place.
249
+ function renderInbox() {
250
+ page.classList.add('is-inbox');
236
251
  page.innerHTML =
252
+ '<div class="ib-tabs" role="tablist" aria-label="Show"></div>' +
237
253
  '<div class="ib-bar">' +
238
- '<span class="ib-filter" role="group" aria-label="Show"><button type="button" data-view="needs" aria-pressed="' + needs + '">Needs you (' + (data.open || 0) + ')</button><button type="button" data-view="recent" aria-pressed="' + !needs + '">Recent</button></span>' +
239
- '<select id="ibWorkflow" aria-label="Workflow"><option value="">All workflows</option>' + options + '</select>' +
240
- '<input id="ibSearch" type="search" placeholder="Search cases, inputs or people" value="' + esc(state.q) + '" aria-label="Search">' +
254
+ '<select id="ibWorkflow" aria-label="Workflow"><option value="">All workflows</option></select>' +
255
+ '<input id="ibSearch" type="search" placeholder="Search conversations, inputs or people" value="' + esc(state.q) + '" aria-label="Search">' +
241
256
  '</div>' +
242
- (items.length ? '<div class="ib-list">' + rows + '</div>'
243
- : '<div class="ib-list"><p class="ib-empty">' + (needs ? 'Nothing needs you right now. Questions and approvals from your agents land here, however long ago they were asked.' : 'Nothing in the last 7 days. Every run shows here for a week: done automatically, decided by someone, or failed.') + '</p></div>') +
244
- (needs ? '' : '<p class="hint ib-older">Showing the last 7 days.' + (fullAccess ? ' Older cases: <a class="ib-link" href="/audit?tab=cases">search all cases in Audit</a>.' : '') + '</p>');
245
- var buttons = page.querySelectorAll('[data-view]');
246
- for (var b = 0; b < buttons.length; b++) buttons[b].addEventListener('click', function (ev) { state.view = ev.currentTarget.getAttribute('data-view'); refreshList(); });
257
+ '<div class="ib-split"><div class="ib-items" role="list"><p class="hint">Loading' + ELLIPSIS + '</p></div>' +
258
+ '<section class="ib-thread" aria-live="polite"><div class="ib-thread-empty">Pick a conversation to see it here.</div></section></div>';
259
+ page.querySelector('.ib-tabs').addEventListener('click', function (ev) {
260
+ var b = ev.target.closest('[data-view]');
261
+ if (!b) return;
262
+ state.view = b.getAttribute('data-view');
263
+ refreshList();
264
+ });
247
265
  page.querySelector('#ibWorkflow').addEventListener('change', function (ev) { state.workflow = ev.currentTarget.value; refreshList(); });
248
266
  var search = page.querySelector('#ibSearch');
249
267
  var timer = null;
250
268
  search.addEventListener('input', function () {
251
269
  clearTimeout(timer);
252
- timer = setTimeout(function () { state.q = search.value.trim(); refreshList(true); }, 300);
270
+ timer = setTimeout(function () { state.q = search.value.trim(); refreshList(); }, 300);
271
+ });
272
+ page.querySelector('.ib-items').addEventListener('click', function (ev) {
273
+ var a = ev.target.closest('[data-item]');
274
+ if (!a || ev.metaKey || ev.ctrlKey || ev.shiftKey) return;
275
+ ev.preventDefault();
276
+ selectItem(a.getAttribute('data-item'));
253
277
  });
254
278
  }
255
279
 
256
- function refreshList(keepFocus) {
280
+ function renderList(data) {
281
+ listed = data;
282
+ var items = data.items || [];
283
+ (data.workflows || []).forEach(function (w) { workflows[w.id] = w.title; });
284
+ state.view = data.view || state.view || 'all';
285
+ var counts = data.counts || {};
286
+ page.querySelector('.ib-tabs').innerHTML = VIEWS.map(function (v) {
287
+ var n = counts[v[0]];
288
+ return '<button type="button" role="tab" data-view="' + v[0] + '" aria-selected="' + (state.view === v[0]) + '">' + v[1] +
289
+ (n ? '<span class="ib-count' + (v[0] === 'needs' ? ' on' : '') + '">' + n + '</span>' : '') + '</button>';
290
+ }).join('');
291
+ var select = page.querySelector('#ibWorkflow');
292
+ select.innerHTML = '<option value="">All workflows</option>' + Object.keys(workflows).sort(function (a, b) { return workflows[a].localeCompare(workflows[b]); })
293
+ .map(function (id) { return '<option value="' + esc(id) + '"' + (id === state.workflow ? ' selected' : '') + '>' + esc(workflows[id]) + '</option>'; }).join('');
294
+ var box = page.querySelector('.ib-items');
295
+ var top = box.scrollTop;
296
+ box.innerHTML = items.length ? items.map(itemHtml).join('') : '<p class="ib-empty">' + esc(EMPTY[state.view] || EMPTY.all) + '</p>';
297
+ box.scrollTop = top;
298
+ // Wide enough for both: the first conversation opens beside the list.
299
+ if (!state.item && items.length && window.matchMedia('(min-width: 861px)').matches) selectItem(items[0].id, true);
300
+ // The open one changed (a decision, a new step): shown again, unless
301
+ // someone is typing in it.
302
+ var current = items.filter(function (i) { return i.id === state.item; })[0];
303
+ if (current && openThread && openThread.lastActivity !== current.lastActivity && !threadInUse()) loadThread(state.item);
304
+ }
305
+
306
+ function refreshList() {
257
307
  history.replaceState(null, '', pageUrl());
258
308
  return fetch(listUrl(), { headers: { accept: 'application/json' } })
259
309
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
260
- .then(function (data) {
261
- var had = keepFocus && document.activeElement && document.activeElement.id === 'ibSearch';
262
- renderList(data);
263
- if (had) { var s = page.querySelector('#ibSearch'); s.focus(); s.setSelectionRange(s.value.length, s.value.length); }
310
+ .then(renderList)
311
+ .catch(function (err) { var box = page.querySelector('.ib-items'); if (box) box.innerHTML = '<p class="error">Could not load the Inbox: ' + esc(err.message) + '</p>'; });
312
+ }
313
+
314
+ function selectItem(id, quiet) {
315
+ state.item = id;
316
+ history.replaceState(null, '', pageUrl());
317
+ var cards = page.querySelectorAll('.ib-item');
318
+ for (var i = 0; i < cards.length; i++) cards[i].classList.toggle('is-selected', cards[i].getAttribute('data-item') === id);
319
+ page.querySelector('.ib-split').classList.toggle('has-thread', !quiet);
320
+ loadThread(id);
321
+ }
322
+
323
+ // Something being written in the open conversation: an answer, a
324
+ // reason, changed arguments.
325
+ function threadInUse() {
326
+ var boxes = page.querySelectorAll('.ib-thread textarea');
327
+ for (var i = 0; i < boxes.length; i++) if ((boxes[i].value && !boxes[i].hidden && boxes[i].className.indexOf('ib-args') === -1) || boxes[i] === document.activeElement) return true;
328
+ return false;
329
+ }
330
+
331
+ function loadThread(id) {
332
+ var box = page.querySelector('.ib-thread');
333
+ if (!openThread || openThread.id !== id) box.innerHTML = '<div class="ib-thread-empty">Loading' + ELLIPSIS + '</div>';
334
+ return fetch('/inbox/cases/' + encodeURIComponent(id), { headers: { accept: 'application/json' } })
335
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
336
+ .then(function (c) {
337
+ if (state.item !== id) return;
338
+ var item = listed && (listed.items || []).filter(function (i) { return i.id === id; })[0];
339
+ openThread = { id: id, lastActivity: item ? item.lastActivity : null };
340
+ renderThread(c);
264
341
  })
265
- .catch(function (err) { page.innerHTML = '<p class="error">Could not load the Inbox: ' + esc(err.message) + '</p>'; });
342
+ .catch(function (err) { if (state.item === id) box.innerHTML = '<div class="ib-thread-empty"><p class="error">Could not open it: ' + esc(err.message) + '</p></div>'; });
343
+ }
344
+
345
+ var SOURCES = { webhook: 'a webhook', schedule: 'a schedule', console: 'Run now', api: 'an app', assignment: 'an assignment', chain: 'another workflow' };
346
+
347
+ function msgHtml(kind, who, at, body, extra) {
348
+ return '<li class="ib-msg ' + kind + (extra ? ' ' + extra : '') + '">' +
349
+ (who || at ? '<span class="ib-msg-who">' + (who ? '<strong>' + esc(who) + '</strong>' : '') + (who && at ? DOT : '') + (at ? '<span title="' + esc(when(at)) + '">' + esc(ago(at)) + '</span>' : '') + '</span>' : '') +
350
+ '<div class="ib-bubble">' + body + '</div></li>';
351
+ }
352
+ function activityHtml(s) {
353
+ return '<li class="ib-act' + (s.failed ? ' failed' : '') + '"><details><summary>' + (s.failed ? 'Tried ' : 'Used ') + '<code>' + esc(s.tool) + '</code>' + (s.failed ? ' (failed)' : '') + '</summary>' +
354
+ '<pre class="ib-pre">' + esc(JSON.stringify(s.args, null, 2)) + '</pre>' + (s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
355
+ }
356
+
357
+ // The conversation, in order: what started it, then the agent's words,
358
+ // the tools it used, what it asked and what people answered or decided,
359
+ // then what it waits on now (answer or decide right there) or how it
360
+ // ended.
361
+ function threadMessagesHtml(c) {
362
+ var run = c.run;
363
+ var agent = c.agentLabel || c.agent;
364
+ var out = [];
365
+ if (run) {
366
+ var params = run.params && Object.keys(run.params).length ? kvHtml(run.params) : '';
367
+ out.push(msgHtml('system', '', run.started_at, 'Started by ' + esc(SOURCES[run.source] || run.source || 'a person') + (params ? params : '')));
368
+ }
369
+ var decisions = ((run && run.decisions) || []).slice().sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
370
+ var answers = ((run && run.answers) || []).slice().sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
371
+ var waitingTools = c.pending.filter(function (p) { return p.kind === 'approval'; }).map(function (p) { return p.tool; });
372
+ var lastText = '';
373
+ c.steps.forEach(function (s) {
374
+ lastText = s.kind === 'text' ? s.text.trim() : '';
375
+ if (s.kind === 'text') { out.push(msgHtml('agent', agent, '', '<div class="ib-md">' + renderMarkdownPreview(s.text) + '</div>')); return; }
376
+ if (s.kind === 'question') {
377
+ if (s.answer == null) return;
378
+ var a = answers.shift();
379
+ out.push(msgHtml('agent', agent, '', '<div class="ib-md">' + renderMarkdownPreview(s.question) + '</div>'));
380
+ out.push(msgHtml('person', a && a.by ? a.by : 'Answer', a && a.at, '<div style="white-space:pre-wrap">' + esc(s.answer) + '</div>'));
381
+ return;
382
+ }
383
+ var di = -1;
384
+ for (var k = 0; k < decisions.length; k++) if (decisions[k].tool === s.tool) { di = k; break; }
385
+ if (di >= 0) {
386
+ var d = decisions.splice(di, 1)[0];
387
+ out.push(msgHtml('agent', agent, '', 'Wants to run <code>' + esc(s.tool) + '</code>' + '<details><summary class="hint">With these values</summary>' + kvHtml(d.edited && d.before ? d.before : s.args) + '</details>'));
388
+ var change = d.edited ? changeOf(d.before, d.after) : '';
389
+ out.push(msgHtml('person', d.by || 'Decision', d.at, '<strong>' + (d.approved ? (d.edited ? 'Approved with changes' : 'Approved') : 'Denied') + '</strong>' +
390
+ (d.reason ? '<div>' + String.fromCharCode(8220) + esc(d.reason) + String.fromCharCode(8221) + '</div>' : '') + (change ? '<div class="ib-change">' + change + '</div>' : ''), d.approved ? '' : 'is-denied'));
391
+ if (d.approved) out.push(activityHtml(s));
392
+ return;
393
+ }
394
+ // Waiting on a decision: asked below, with its buttons.
395
+ if (s.result == null && waitingTools.indexOf(s.tool) !== -1) return;
396
+ out.push(activityHtml(s));
397
+ });
398
+ c.pending.forEach(function (p) { out.push('<li class="ib-msg agent ask"><span class="ib-msg-who"><strong>' + esc(agent) + '</strong>' + (p.createdAt ? DOT + esc(ago(p.createdAt)) : '') + '</span><div class="ib-bubble">' + pendingHtml(p) + '</div></li>'); });
399
+ if (run && !c.pending.length) {
400
+ if (run.status === 'running') out.push('<li class="ib-msg agent"><span class="ib-typing">' + esc(agent) + ' is working' + ELLIPSIS + '</span></li>');
401
+ if (run.status === 'error') out.push(msgHtml('agent', agent, run.finished_at, '<strong>Failed.</strong> ' + esc(run.error || 'It stopped with an error.') +
402
+ (run.output_errors && run.output_errors.length ? '<ul class="ib-schema-errors">' + run.output_errors.map(function (e) { return '<li>' + esc(e) + '</li>'; }).join('') + '</ul>' : ''), 'failed'));
403
+ // Its result, unless that's what it just said.
404
+ if (run.status === 'done' && !(run.output === undefined && lastText && lastText === String(run.result || '').trim())) out.push(msgHtml('agent', agent, run.finished_at, run.output !== undefined
405
+ ? '<pre class="ib-pre">' + esc(JSON.stringify(run.output, null, 2)) + '</pre>'
406
+ : '<div class="ib-md">' + renderMarkdownPreview(run.result || 'Done.') + '</div>'));
407
+ }
408
+ return out.join('');
409
+ }
410
+
411
+ function renderThread(c) {
412
+ var box = page.querySelector('.ib-thread');
413
+ var run = c.run;
414
+ var status = stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: run ? run.status : 'awaiting_approval' });
415
+ var canArchive = canDecide() && !c.pending.length && run && run.status !== 'running';
416
+ var msgs = box.querySelector('.ib-msgs');
417
+ var keepScroll = openThread && msgs && msgs.getAttribute('data-id') === c.id ? msgs.scrollTop : null;
418
+ box.innerHTML =
419
+ '<header class="ib-thread-head"><div class="ib-thread-top"><div class="ib-thread-tools"><button type="button" class="ib-thread-back">' + String.fromCharCode(8592) + ' Inbox</button></div><h2>' + esc(c.title) + '</h2>' +
420
+ '<div class="ib-thread-tools">' + (canArchive ? '<button type="button" data-act="archive">' + (c.archived ? 'Unarchive' : 'Archive') + '</button>' : '') +
421
+ (fullAccess && run && c.workflowId ? '<a href="' + esc(traceHref(c)) + '">View trace</a>' : '') + '</div></div>' +
422
+ '<div class="ib-chips">' + status + (c.archived ? '<span class="ib-state">Archived</span>' : '') + '<span>' + caseLinks(c) + '</span></div></header>' +
423
+ '<ol class="ib-msgs" data-id="' + esc(c.id) + '">' + threadMessagesHtml(c) + '</ol>';
424
+ msgs = box.querySelector('.ib-msgs');
425
+ // The latest at the bottom, in view; a redraw keeps where it was.
426
+ msgs.scrollTop = keepScroll != null ? keepScroll : msgs.scrollHeight;
427
+ box.querySelector('.ib-thread-back').addEventListener('click', function () {
428
+ state.item = '';
429
+ openThread = null;
430
+ history.replaceState(null, '', pageUrl());
431
+ page.querySelector('.ib-split').classList.remove('has-thread');
432
+ });
433
+ var archive = box.querySelector('[data-act="archive"]');
434
+ if (archive) archive.addEventListener('click', function () {
435
+ archive.disabled = true;
436
+ fetch('/inbox/cases/' + encodeURIComponent(c.id) + '/archive', { method: c.archived ? 'DELETE' : 'POST' })
437
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'That did not work'); }); })
438
+ .then(function () { openThread = null; loadThread(c.id); refreshList(); })
439
+ .catch(function (err) { archive.disabled = false; archive.textContent = err.message; });
440
+ });
441
+ wireCase(c);
266
442
  }
267
443
 
268
444
  function valueHtml(v) {
@@ -300,34 +476,6 @@ ${renderMarkdownScript}
300
476
  '</div>';
301
477
  }
302
478
 
303
- // How long something took, in words: 850 ms, 4.2 s, 3 min, 2 h 5 min.
304
- function duration(ms) {
305
- if (ms < 1000) return Math.round(ms) + ' ms';
306
- if (ms < 60000) return (ms / 1000).toFixed(1) + ' s';
307
- var min = Math.round(ms / 60000);
308
- return min < 60 ? min + ' min' : Math.floor(min / 60) + ' h' + (min % 60 ? ' ' + (min % 60) + ' min' : '');
309
- }
310
- function count(n) { return Number(n).toLocaleString(); }
311
- // Dollars: cents to the cent, smaller amounts to a tenth of a cent.
312
- function dollars(n) { return '$' + (n >= 0.1 ? n.toFixed(2) : n >= 0.001 ? n.toFixed(3) : n > 0 ? '<0.001' : '0'); }
313
-
314
- // A step's model call (tokens, time) and the wait after it.
315
- function stepMeta(s) {
316
- var parts = [];
317
- if (s.call) parts.push('model ' + (s.call.durationMs != null ? duration(s.call.durationMs) + ', ' : '') + count(s.call.inputTokens) + ' in ' + String.fromCharCode(183) + ' ' + count(s.call.outputTokens) + ' out tokens' + (s.call.costUsd != null ? ', ' + dollars(s.call.costUsd) : ''));
318
- if (s.waitMs != null) parts.push((s.kind === 'question' ? 'answered after ' : 'took ') + duration(s.waitMs));
319
- return parts.length ? '<span class="ib-step-meta">' + esc(parts.join(DOT)) + '</span>' : '';
320
- }
321
-
322
- function stepHtml(s) {
323
- if (s.kind === 'text') return '<li class="ib-step"><span class="ib-step-k">Agent' + stepMeta(s) + '</span><div class="ib-md">' + renderMarkdownPreview(s.text) + '</div></li>';
324
- if (s.kind === 'question') return '<li class="ib-step q"><span class="ib-step-k">Asked' + stepMeta(s) + '</span><div class="ib-md">' + renderMarkdownPreview(s.question) + '</div>' +
325
- (s.answer != null ? '<span class="ib-step-k">Answer</span><div style="white-space:pre-wrap">' + esc(s.answer) + '</div>' : '<span class="hint">Waiting for an answer</span>') + '</li>';
326
- return '<li class="ib-step"><span class="ib-step-k">Used ' + esc(s.tool) + (s.failed ? ' (failed)' : '') + stepMeta(s) + '</span>' +
327
- '<details><summary>What it sent' + (s.result != null ? ' and got back' : '') + '</summary><pre class="ib-pre">' + esc(JSON.stringify(s.args, null, 2)) + '</pre>' +
328
- (s.result != null ? '<pre class="ib-pre" style="margin-top:6px">' + esc(s.result) + '</pre>' : '') + '</details></li>';
329
- }
330
-
331
479
  // What a person changed before approving: each field whose value
332
480
  // differs, from what the agent asked for to what ran.
333
481
  function changeOf(before, after) {
@@ -339,256 +487,13 @@ ${renderMarkdownScript}
339
487
  }).join('');
340
488
  }
341
489
 
342
- function decidedHtml(run) {
343
- var rows = [];
344
- (run.decisions || []).forEach(function (d) { rows.push({ at: d.at, text: (d.approved ? (d.edited ? 'Approved as changed' : 'Approved') : 'Denied') + ' ' + d.tool, by: d.by, reason: d.reason, change: d.edited ? changeOf(d.before, d.after) : '' }); });
345
- (run.answers || []).forEach(function (a) { rows.push({ at: a.at, text: 'Answered: ' + a.answer, by: a.by }); });
346
- rows.sort(function (a, b) { return String(a.at).localeCompare(String(b.at)); });
347
- if (!rows.length) return '';
348
- return '<div class="ib-card"><h3>Decisions</h3><div class="ib-who">' + rows.map(function (r) {
349
- return '<div>' + esc(r.text) + ' <span class="hint">' + (r.by ? 'by ' + esc(r.by) + DOT : '') + esc(when(r.at)) + '</span>' +
350
- (r.reason ? '<div class="ib-reason">' + String.fromCharCode(8220) + esc(r.reason) + String.fromCharCode(8221) + '</div>' : '') +
351
- (r.change ? '<div class="ib-change">' + r.change + '</div>' : '') + '</div>';
352
- }).join('') + '</div></div>';
353
- }
354
-
355
490
  // The case's workflow and agent, each opening its page. An approver or
356
491
  // viewer can open only the Inbox, so for them they're plain text.
357
492
  function caseLinks(c) {
358
- if (document.querySelector('.le-app.le-inbox-only')) return esc(c.workflowTitle) + DOT + esc(c.agent);
493
+ if (document.querySelector('.le-app.le-inbox-only')) return esc(c.agentLabel || c.agent) + DOT + esc(c.workflowTitle);
359
494
  var agentUrl = '/agents/config?agent=' + encodeURIComponent(c.agent);
360
495
  var wf = c.workflowId ? '<a class="ib-link" href="' + agentUrl + '&tab=workflows&workflow=' + encodeURIComponent(c.workflowId) + '">' + esc(c.workflowTitle) + '</a>' : esc(c.workflowTitle);
361
- return wf + DOT + '<a class="ib-link" href="' + agentUrl + '">' + esc(c.agent) + '</a>';
362
- }
363
-
364
- function totalsHtml(c) {
365
- var t = c.totals;
366
- if (!t) return '';
367
- return '<p class="ib-totals">' + esc([
368
- t.calls + (t.calls === 1 ? ' model call' : ' model calls'),
369
- count(t.inputTokens) + ' tokens in, ' + count(t.outputTokens) + ' out',
370
- 'model time ' + duration(t.modelMs),
371
- t.costUsd != null ? 'cost ' + dollars(t.costUsd) : '',
372
- t.elapsedMs != null ? 'start to finish ' + duration(t.elapsedMs) : '',
373
- ].filter(Boolean).join(DOT)) + '</p>';
374
- }
375
-
376
- // Keep the case: its whole record as a file, or printed (to paper or
377
- // a PDF, from the browser's print dialog).
378
- function exportHtml(c) {
379
- return '<div class="ib-export"><a class="ib-btn plain" href="/inbox/cases/' + encodeURIComponent(c.id) + '/export" download>Download record</a>' +
380
- '<button type="button" class="ib-btn plain" data-act="print">Print or save as PDF</button></div>';
381
- }
382
-
383
- function renderCase(c) {
384
- var run = c.run;
385
- var status = run ? stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: run.status }) : stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: 'awaiting_approval' });
386
- page.innerHTML =
387
- '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a>' +
388
- '<div class="ib-case-head"><h2>' + esc(c.title) + '</h2><div class="ib-chips">' + status + '<span>' + caseLinks(c) + (run ? DOT + 'started ' + esc(when(run.started_at)) + (run.source ? ' by ' + esc(run.source === 'webhook' ? 'a webhook' : run.source === 'schedule' ? 'a schedule' : run.source === 'console' ? 'Run now' : run.source === 'api' ? 'an app' : run.source) : '') : '') + '</span></div></div>' +
389
- c.pending.map(pendingHtml).join('') +
390
- (run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
391
- (c.steps.length ? '<div class="ib-card"><h3>What the agent did</h3>' + totalsHtml(c) + '<ol class="ib-steps">' + c.steps.map(stepHtml).join('') + '</ol></div>' : '') +
392
- (run ? decidedHtml(run) : '') +
393
- // With an output schema, the result is its JSON, shown once.
394
- (run && run.output !== undefined ? '<div class="ib-card"><h3>Result <span class="hint">(JSON, matches its output schema' + (run.output_retries ? ', after ' + run.output_retries + (run.output_retries === 1 ? ' retry' : ' retries') : '') + ')</span></h3><pre class="ib-pre">' + esc(JSON.stringify(run.output, null, 2)) + '</pre></div>'
395
- : run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
396
- (run && run.status === 'error' && run.output_errors && run.output_errors.length ? '<div class="ib-card"><h3>Didn' + String.fromCharCode(8217) + 't match its output schema</h3><ul class="ib-schema-errors">' + run.output_errors.map(function (e) { return '<li>' + esc(e) + '</li>'; }).join('') + '</ul></div>' : '') +
397
- (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '') +
398
- traceHtml(c) +
399
- exportHtml(c) +
400
- evalCaseHtml(c);
401
- var print = page.querySelector('[data-act="print"]');
402
- if (print) print.addEventListener('click', function () { window.print(); });
403
- wireEvalCase(c);
404
- wireTrace(c);
405
- wireCase(c);
406
- }
407
-
408
- // The run's trace (owners, admins and editors): the prompt it ran with,
409
- // each model call (what was new in its input, and its output) and each
410
- // tool call (input, output, time), word for word. Loaded when opened.
411
- function traceHtml(c) {
412
- if (!fullAccess || !c.run) return '';
413
- return '<div class="ib-card ib-trace"><h3>Trace</h3>' +
414
- '<p class="hint" style="margin:0">Every step word for word: the prompt the agent ran with, what each model call was given and answered, and what each tool was sent and returned.</p>' +
415
- '<div class="ib-actions"><button type="button" class="ib-btn plain" data-act="trace">Show trace</button><span class="hint ib-trace-status" role="status"></span></div>' +
416
- '<ol class="ib-trace-list" hidden></ol></div>';
417
- }
418
- var NL = String.fromCharCode(10);
419
- // A traced value as text: a cut one says how much was left out.
420
- function traceText(v) {
421
- if (v == null) return '';
422
- if (typeof v === 'object' && !Array.isArray(v) && v.truncated) return String(v.start) + NL + NL + '(cut: ' + count(v.chars) + ' characters in all)';
423
- if (typeof v === 'string') return v;
424
- if (Array.isArray(v)) return v.map(blockText).join(NL + NL);
425
- return JSON.stringify(v, null, 2);
426
- }
427
- function blockText(b) {
428
- if (b && typeof b === 'object' && 'role' in b) return b.role.toUpperCase() + NL + traceText(b.content);
429
- if (!b || typeof b !== 'object') return String(b);
430
- if (b.type === 'text') return b.text;
431
- if (b.type === 'tool_use') return 'Calls ' + b.name + ' ' + JSON.stringify(b.input, null, 2);
432
- if (b.type === 'tool_result') return 'Result for ' + b.tool_use_id + (b.is_error ? ' (error)' : '') + ':' + NL + traceText(b.content);
433
- return JSON.stringify(b, null, 2);
434
- }
435
- function tracePart(label, v, open) {
436
- var text = traceText(v);
437
- if (!text) return '';
438
- return '<details' + (open ? ' open' : '') + '><summary>' + esc(label) + '</summary><pre class="ib-pre">' + esc(text) + '</pre></details>';
439
- }
440
- // The trace's own fields at the top: which run of which version, the
441
- // model, how long, what it cost, and the feedback on it.
442
- function traceSummaryHtml(t) {
443
- var rows = [
444
- ['Execution id', t.execution_id],
445
- ['Workflow', t.workflow_id + (t.workflow_version_id ? ' (' + t.workflow_version_id + ')' : '')],
446
- ['Model', t.model ? (t.model.provider ? t.model.provider + ' ' : '') + t.model.model : ''],
447
- ['Status', t.status],
448
- ['Duration', t.duration_ms != null ? duration(t.duration_ms) : ''],
449
- ['Cost', (t.cost.usd != null ? dollars(t.cost.usd) + DOT : '') + t.cost.model_calls + (t.cost.model_calls === 1 ? ' model call' : ' model calls') + DOT + count(t.cost.input_tokens) + ' in ' + String.fromCharCode(183) + ' ' + count(t.cost.output_tokens) + ' out tokens'],
450
- ['Tool calls', String(t.tool_calls.length)],
451
- ['Feedback', t.feedback ? [t.feedback.verdict, t.feedback.edit ? t.feedback.edit + ' edits' : '', t.feedback.note].filter(Boolean).join(DOT) || 'reported' : 'none yet'],
452
- ['Error', t.error || ''],
453
- ].filter(function (r) { return r[1]; });
454
- return '<dl class="ib-trace-sum">' + rows.map(function (r) { return '<dt>' + esc(r[0]) + '</dt><dd>' + esc(r[1]) + '</dd>'; }).join('') + '</dl>';
455
- }
456
- function traceStepHtml(st, i, steps) {
457
- var meta = [];
458
- if (st.duration_ms != null) meta.push(duration(st.duration_ms));
459
- var head = function (kind, name) {
460
- return '<div class="ib-trace-head"><span class="ib-trace-kind">' + kind + '</span>' + (name ? '<strong>' + esc(name) + '</strong>' : '') +
461
- '<span class="ib-trace-meta">' + esc(meta.join(DOT)) + '</span></div>';
462
- };
463
- var err = st.error ? '<p class="error" style="margin:0">' + esc(st.error) + '</p>' : '';
464
- if (st.type === 'prompt') {
465
- return '<li class="ib-trace-span prompt">' + head(st.resumed ? 'Prompt (resumed)' : 'Prompt', '') +
466
- (st.tools.length ? '<div class="ib-trace-tools">' + st.tools.map(function (t) { return '<code>' + esc(t) + '</code>'; }).join('') + '</div>' : '') +
467
- (st.prior_messages ? '<span class="ib-trace-meta">After ' + st.prior_messages + ' earlier messages in this conversation</span>' : '') +
468
- tracePart('System prompt', st.system, false) +
469
- tracePart(st.resumed ? 'Resumed with' : 'Input', st.input, true) + '</li>';
470
- }
471
- if (st.type === 'model_call') {
472
- if (st.input_tokens != null) meta.push(count(st.input_tokens) + ' in ' + String.fromCharCode(183) + ' ' + count(st.output_tokens) + ' out tokens');
473
- if (st.messages_sent != null) meta.push(st.messages_sent + (st.messages_sent === 1 ? ' message' : ' messages') + ' sent');
474
- if (st.stop_reason) meta.push('stopped: ' + st.stop_reason);
475
- var fresh = Array.isArray(st.input) && st.input.length ? st.input : null;
476
- var afterPrompt = i > 0 && steps[i - 1].type === 'prompt';
477
- return '<li class="ib-trace-span llm' + (st.error ? ' err' : '') + '">' + head('Model call', st.model) + err +
478
- (fresh ? tracePart('New input', fresh, false) : '<span class="ib-trace-meta">' + (afterPrompt ? 'Given the prompt above' : 'No new input since the step before') + '</span>') +
479
- tracePart('Output', st.output, true) + '</li>';
480
- }
481
- if (st.type === 'tool_call') {
482
- if (st.status) meta.push(st.status);
483
- return '<li class="ib-trace-span tool' + (st.error ? ' err' : '') + '">' + head('Tool call', st.name) + err +
484
- tracePart('Input', st.input, false) + tracePart('Output', st.output, false) + '</li>';
485
- }
486
- var who = st.by ? ' by ' + st.by : '';
487
- if (st.type === 'decision') {
488
- return '<li class="ib-trace-span event">' + head('Decision', (st.approved ? (st.changed ? 'Approved as changed: ' : 'Approved: ') : 'Denied: ') + st.tool) +
489
- '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' + (st.reason ? '<div>' + esc(st.reason) + '</div>' : '') + '</li>';
490
- }
491
- if (st.type === 'answer') {
492
- return '<li class="ib-trace-span event">' + head('Answer', '') + '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' +
493
- tracePart('Question', st.question, false) + '<div>' + esc(st.answer) + '</div></li>';
494
- }
495
- return '<li class="ib-trace-span event">' + head('Feedback', [st.verdict, st.edit ? st.edit + ' edits' : ''].filter(Boolean).join(', ')) +
496
- '<span class="ib-trace-meta">' + esc(when(st.at) + who) + '</span>' + (st.note ? '<div>' + esc(st.note) + '</div>' : '') + '</li>';
497
- }
498
- function wireTrace(c) {
499
- var btn = page.querySelector('[data-act="trace"]');
500
- if (!btn) return;
501
- var list = page.querySelector('.ib-trace-list');
502
- var status = page.querySelector('.ib-trace-status');
503
- var loaded = false;
504
- btn.addEventListener('click', function () {
505
- if (loaded) {
506
- list.hidden = !list.hidden;
507
- btn.textContent = list.hidden ? 'Show trace' : 'Hide trace';
508
- return;
509
- }
510
- btn.disabled = true;
511
- status.textContent = 'Loading' + ELLIPSIS;
512
- fetch('/inbox/cases/' + encodeURIComponent(c.id) + '/trace', { headers: { accept: 'application/json' } })
513
- .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not load the trace'); return b; }); })
514
- .then(function (t) {
515
- loaded = true;
516
- btn.disabled = false;
517
- var steps = t.step_events || [];
518
- var traced = steps.some(function (x) { return x.type === 'prompt' || x.type === 'model_call'; });
519
- status.textContent = traced ? '' : 'No step-by-step trace for this run: it ran before traces were kept.';
520
- list.innerHTML = '<li>' + traceSummaryHtml(t) + '</li>' + steps.map(traceStepHtml).join('') +
521
- (t.final_output ? '<li class="ib-trace-span">' + '<div class="ib-trace-head"><span class="ib-trace-kind">Final output</span></div>' + tracePart('Output', t.final_output, true) + '</li>' : '') +
522
- '<li><a class="ib-link" href="/agents/' + encodeURIComponent(t.agent) + '/runs/' + encodeURIComponent(t.execution_id) + '/trace" download="trace-' + esc(t.execution_id.slice(0, 8)) + '.json">Download trace as JSON</a></li>';
523
- list.hidden = false;
524
- btn.textContent = 'Hide trace';
525
- })
526
- .catch(function (err) { btn.disabled = false; status.textContent = err.message; });
527
- });
528
- }
529
-
530
- // Save this run as one of its workflow's eval cases (owners, admins and
531
- // editors): a test it must keep passing. Then the success criteria it
532
- // suggests, from what people corrected in it, to add or not.
533
- function evalCaseHtml(c) {
534
- var run = c.run;
535
- if (!fullAccess || !run || !run.workflow_id || run.status !== 'done') return '';
536
- return '<div class="ib-card ib-eval"><h3>Eval case</h3>' +
537
- '<p class="hint" style="margin:0">Save this run as a test its workflow must keep passing after every change to its brief. Runs where a person denied or changed something, or that went wrong, make the best tests.</p>' +
538
- '<div class="ib-actions"><button type="button" class="ib-btn plain" data-act="save-case">Save as eval case</button><span class="hint ib-eval-result" role="status"></span></div>' +
539
- '<div class="ib-suggest" hidden></div></div>';
540
- }
541
- function evalBase(c) {
542
- return '/agents/' + encodeURIComponent(c.agent) + '/workflows/' + encodeURIComponent(c.workflowId) + '/evals';
543
- }
544
- function wireEvalCase(c) {
545
- var btn = page.querySelector('[data-act="save-case"]');
546
- if (!btn) return;
547
- var result = page.querySelector('.ib-eval-result');
548
- var suggest = page.querySelector('.ib-suggest');
549
- // Already a case: say so.
550
- fetch(evalBase(c), { headers: { accept: 'application/json' } })
551
- .then(function (r) { return r.ok ? r.json() : null; })
552
- .then(function (ev) {
553
- if (ev && (ev.cases || []).some(function (k) { return k.fromRun === c.id; })) { btn.disabled = true; btn.textContent = 'Saved as an eval case'; }
554
- }).catch(function () {});
555
- btn.addEventListener('click', function () {
556
- btn.disabled = true;
557
- result.textContent = 'Saving' + ELLIPSIS;
558
- fetch(evalBase(c) + '/cases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: c.id }) })
559
- .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not save'); return b; }); })
560
- .then(function (b) {
561
- btn.textContent = 'Saved as an eval case';
562
- result.innerHTML = 'Saved. <a class="ib-link" href="/agents/config?agent=' + encodeURIComponent(c.agent) + '&tab=workflows&workflow=' + encodeURIComponent(c.workflowId) + '&wtab=evaluation">See its eval cases</a>';
563
- showSuggestions(c, b.suggestions || [], b.criteria || []);
564
- })
565
- .catch(function (err) { btn.disabled = false; result.textContent = err.message; });
566
- });
567
- }
568
- function showSuggestions(c, suggestions, criteria) {
569
- var box = page.querySelector('.ib-suggest');
570
- var have = criteria.map(function (k) { return k.text; });
571
- var fresh = suggestions.filter(function (s) { return have.indexOf(s.text) === -1; });
572
- if (!fresh.length) return;
573
- box.hidden = false;
574
- box.innerHTML = '<h4>Add to its success criteria?</h4><p class="hint" style="margin:0">From what people corrected in this run. Each becomes a criterion every eval case is judged on.</p>' +
575
- fresh.map(function (s, i) { return '<div class="ib-suggest-row"><span>' + esc(s.text) + '</span><button type="button" class="ib-btn plain" data-suggest="' + i + '">Add</button></div>'; }).join('');
576
- box.addEventListener('click', function (ev) {
577
- var b = ev.target.closest('[data-suggest]');
578
- if (!b) return;
579
- b.disabled = true;
580
- var s = fresh[Number(b.getAttribute('data-suggest'))];
581
- fetch(evalBase(c), { headers: { accept: 'application/json' } })
582
- .then(function (r) { return r.json(); })
583
- .then(function (ev2) {
584
- var list = (ev2.criteria || []).map(function (k) { return { text: k.text, kind: k.kind, value: k.value }; });
585
- list.push({ text: s.text, kind: s.kind });
586
- return fetch(evalBase(c) + '/criteria', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ criteria: list }) });
587
- })
588
- .then(function (r) { return r.json().then(function (body) { if (!r.ok) throw new Error(body.error || 'Could not add it'); }); })
589
- .then(function () { b.textContent = 'Added'; })
590
- .catch(function (err) { b.disabled = false; b.textContent = err.message; });
591
- });
496
+ return '<a class="ib-link" href="' + agentUrl + '">' + esc(c.agentLabel || c.agent) + '</a>' + DOT + wf;
592
497
  }
593
498
 
594
499
  function send(card, path, body) {
@@ -602,7 +507,7 @@ ${renderMarkdownScript}
602
507
  if (!r.ok) throw new Error(r.body.error || 'That did not work');
603
508
  result.textContent = 'Done. The agent is carrying on' + ELLIPSIS;
604
509
  if (window.leShell && window.leShell.reloadInboxCount) window.leShell.reloadInboxCount();
605
- setTimeout(openCase, 1200);
510
+ setTimeout(function () { openThread = null; if (state.item) loadThread(state.item); refreshList(); }, 1200);
606
511
  })
607
512
  .catch(function (err) {
608
513
  result.textContent = err.message;
@@ -656,26 +561,12 @@ ${renderMarkdownScript}
656
561
  }
657
562
  }
658
563
 
659
- function openCase() {
660
- return fetch('/inbox/cases/' + encodeURIComponent(caseId), { headers: { accept: 'application/json' } })
661
- .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
662
- .then(function (c) { document.title = c.title + ' ' + String.fromCharCode(183) + ' Case'; renderCase(c); })
663
- .catch(function (err) { page.innerHTML = '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a><p class="error">Could not open this case: ' + esc(err.message) + '</p>'; });
664
- }
665
-
666
564
  function start() {
667
- // A case's page is about that case, wherever it was opened from.
668
- if (caseId) {
669
- var head = document.querySelector('.le-head h1');
670
- var lede = document.querySelector('.le-head p');
671
- if (head) head.textContent = 'Case';
672
- if (lede) lede.textContent = 'One run in full: what it was given, what the agent did step by step, who decided what, and what came of it.';
673
- }
674
- if (caseId) openCase();
675
- else refreshList();
565
+ renderInbox();
566
+ refreshList().then(function () { if (state.item && (!openThread || openThread.id !== state.item)) selectItem(state.item); });
676
567
  // The list keeps itself current while it's open.
677
568
  setInterval(function () {
678
- if (document.hidden || caseId) return;
569
+ if (document.hidden) return;
679
570
  if (document.activeElement && document.activeElement.id === 'ibSearch') return;
680
571
  refreshList();
681
572
  }, 15000);