agenttrace-journal 0.0.0-stage → 0.1.0

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.
package/viewer/app.js ADDED
@@ -0,0 +1,481 @@
1
+ import { readActivity, formatDuration, formatNumber, formatCost } from './trace-data.js';
2
+
3
+ const idPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[47][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
4
+ const byId = (id) => document.getElementById(id);
5
+ const shell = byId('viewer');
6
+ const search = byId('run-search');
7
+ const list = byId('runs');
8
+ const more = byId('more-runs');
9
+ const detail = byId('run-detail');
10
+ const loading = byId('initial-loading').querySelector('main').cloneNode(true);
11
+ loading.id = 'loading-trace';
12
+ loading.hidden = true;
13
+ detail.before(loading);
14
+ const events = byId('events');
15
+ const filters = [...document.querySelectorAll('[data-filter]')];
16
+ const metrics = [...detail.querySelectorAll('.mt .v')];
17
+ const overview = detail.querySelector('[data-name="Overview"]');
18
+ const errorPanel = byId('trace-error');
19
+ const time = new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
20
+ const timeWithSeconds = new Intl.DateTimeFormat(undefined, {
21
+ hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
22
+ });
23
+ const calendar = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
24
+ const labels = { model: 'Model', tool: 'Tool', command: 'Command', file: 'File',
25
+ verification: 'Verification', decision: 'Decision', capture: 'Capture' };
26
+
27
+ let query = '';
28
+ let directory = '.agenttrace';
29
+ let total = 0;
30
+ let next = null;
31
+ let firstPage = [];
32
+ const older = new Map();
33
+ let selected = null;
34
+ let trace = null;
35
+ let activity = null;
36
+ let traceKey = null;
37
+ let filter = 'all';
38
+ const expansion = new Map();
39
+ let loadError = '';
40
+ let traceError = '';
41
+ let listRequest;
42
+ let detailRequest;
43
+ let searchTimer;
44
+ let listKey;
45
+ let noticeMessage = '';
46
+
47
+ function element(tag, className, text) {
48
+ const node = document.createElement(tag);
49
+ if (className) node.className = className;
50
+ if (text !== undefined) node.textContent = text;
51
+ return node;
52
+ }
53
+
54
+ function icon(name) {
55
+ return byId('icon-' + name).content.firstElementChild.cloneNode(true);
56
+ }
57
+
58
+ function timestamp(value, precise = false) {
59
+ const date = new Date(value);
60
+ if (!Number.isFinite(date.valueOf())) return 'Unknown time';
61
+ const today = new Date();
62
+ const yesterday = new Date();
63
+ yesterday.setDate(today.getDate() - 1);
64
+ const day = date.toDateString();
65
+ const label = day === today.toDateString() ? 'Today'
66
+ : day === yesterday.toDateString() ? 'Yesterday' : calendar.format(date);
67
+ return label + (precise ? ', ' + timeWithSeconds.format(date) : ' ' + time.format(date));
68
+ }
69
+
70
+ function statusInto(node, status, caption, live = false) {
71
+ node.classList.toggle('bad', status === 'failed');
72
+ const label = caption ?? { passed: 'Completed', failed: 'Failed', open: 'Unfinished' }[status];
73
+ const symbol = icon(status === 'open' ? live ? 'live' : 'pending' : status);
74
+ if (live) {
75
+ symbol.setAttribute('height', '16');
76
+ symbol.setAttribute('width', '16');
77
+ }
78
+ node.replaceChildren(symbol, ...(label ? [label] : []));
79
+ if (!label) {
80
+ node.title = status === 'passed' ? 'Passed' : status;
81
+ symbol.removeAttribute('aria-hidden');
82
+ symbol.setAttribute('role', 'img');
83
+ symbol.setAttribute('aria-label', node.title);
84
+ }
85
+ }
86
+
87
+ function runSummaries() {
88
+ return [...new Map([...older.values(), ...firstPage].map((item) => [item.id, item])).values()]
89
+ .sort((a, b) => b.startedAt.localeCompare(a.startedAt) || b.id.localeCompare(a.id));
90
+ }
91
+
92
+ function renderRuns() {
93
+ const items = runSummaries();
94
+ const key = JSON.stringify([items, selected, query, total, directory]);
95
+ if (listKey !== key) {
96
+ listKey = key;
97
+ const active = list.contains(document.activeElement) ? document.activeElement.hash : null;
98
+ const fragment = document.createDocumentFragment();
99
+ let focus;
100
+ for (const run of items) {
101
+ const isSelected = run.id === selected;
102
+ const link = element('a', isSelected ? 'run sel' : 'run');
103
+ link.href = '#' + run.id;
104
+ if (link.hash === active) focus = link;
105
+ if (isSelected) link.setAttribute('aria-current', 'true');
106
+ const summary = element('div', 'run-summary');
107
+ const timeNode = element('time', 'tm', timestamp(run.startedAt));
108
+ timeNode.dateTime = run.startedAt;
109
+ summary.append(element('div', 'nm', run.name), timeNode);
110
+ const badge = element('span', 'stt');
111
+ statusInto(badge, run.status);
112
+ link.append(summary, badge);
113
+ fragment.append(link);
114
+ }
115
+ list.replaceChildren(fragment);
116
+ focus?.focus({ preventScroll: true });
117
+ }
118
+ const directoryName = directory.replace(/[\\/]+$/, '').split(/[\\/]/).at(-1) || directory;
119
+ const count = formatNumber(total);
120
+ byId('run-source').textContent = directoryName + '/ · ' + (total ? count + (total === 1 ? ' run' : ' runs') : 'empty');
121
+ byId('run-source').title = directory;
122
+ byId('run-count').textContent = query ? formatNumber(items.length) + (next ? '+' : '') + ' of ' + count : count;
123
+ const noMatches = !items.length && !loadError && Boolean(query);
124
+ byId('unmatched-runs').hidden = !noMatches;
125
+ byId('no-runs-match').textContent = 'No runs match “' + query + '”';
126
+ byId('empty-runs').hidden = Boolean(items.length || query || loadError);
127
+ list.hidden = noMatches || !byId('empty-runs').hidden;
128
+ byId('clear-search').hidden = !search.value;
129
+ search.disabled = total === 0 && !query && !loadError;
130
+ more.hidden = !next;
131
+ }
132
+
133
+ function renderNotice() {
134
+ const notices = [loadError, noticeMessage];
135
+ if (trace?.totals?.droppedEvents) notices.push(formatNumber(trace.totals.droppedEvents) + ' events exceeded the capture limit.');
136
+ if (trace?.totals?.pendingOperations) {
137
+ const pending = trace.totals.pendingOperations;
138
+ notices.push(formatNumber(pending) + (pending === 1 ? ' operation was' : ' operations were') + ' still running when the run ended.');
139
+ }
140
+ if (trace?.malformedLines) notices.push(formatNumber(trace.malformedLines) + ' malformed lines were skipped.');
141
+ if (trace?.error) notices.push(trace.error);
142
+ const notice = byId('viewer-notice');
143
+ notice.textContent = notices.filter(Boolean).join(' ');
144
+ notice.hidden = !notice.textContent;
145
+ }
146
+
147
+ function renderPanels() {
148
+ const matchesSelection = !query || runSummaries().some((item) => item.id === selected);
149
+ const showTrace = Boolean(selected && matchesSelection);
150
+ const showTraceError = showTrace && Boolean(traceError);
151
+ const showListError = !showTrace && Boolean(loadError);
152
+ detail.hidden = !showTrace || (!trace && !showTraceError);
153
+ loading.hidden = !showTrace || Boolean(trace || showTraceError);
154
+ byId('first-run').hidden = showTrace || Boolean(total || query || loadError);
155
+ byId('select-run').hidden = showTrace || showListError || !byId('first-run').hidden;
156
+ byId('unavailable').hidden = !showListError;
157
+ if (showTraceError || showListError) {
158
+ (showTraceError ? detail : byId('unavailable')).append(errorPanel);
159
+ errorPanel.hidden = false;
160
+ byId('error-title').textContent = showTraceError ? 'Trace unavailable' : 'Could not read runs';
161
+ byId('error-description').textContent = showTraceError ? traceError : loadError;
162
+ byId('error-path').textContent = showTraceError ? directory.replace(/[\\/]$/, '') + '/' + selected + '.ndjson' : directory;
163
+ } else errorPanel.hidden = true;
164
+ for (const section of [byId('claim-evidence'), detail.querySelector('.mt'), byId('activity')]) {
165
+ section.hidden = showTraceError || !trace || (section.id === 'claim-evidence' && !activity?.evidence);
166
+ }
167
+ overview.hidden = !showTrace;
168
+ renderNotice();
169
+ }
170
+
171
+ function renderOverview() {
172
+ const item = trace ?? runSummaries().find((run) => run.id === selected);
173
+ const available = Boolean(trace && !traceError);
174
+ byId('run-title').textContent = item?.name ?? 'Trace ' + selected;
175
+ const timestampNode = byId('run-time');
176
+ timestampNode.hidden = !item;
177
+ timestampNode.nextElementSibling.hidden = !item;
178
+ if (item) {
179
+ timestampNode.textContent = timestamp(item.startedAt, true);
180
+ timestampNode.dateTime = item.startedAt;
181
+ }
182
+ byId('trace-id').textContent = selected;
183
+ const runStatus = byId('run-status');
184
+ runStatus.hidden = !item;
185
+ if (item) {
186
+ const totals = item.totals;
187
+ const caption = totals?.failedChecks ? 'Failed · ' + totals.failedChecks + ' failed verification'
188
+ + (totals.failedChecks === 1 ? '' : 's')
189
+ : totals?.failedOperations ? (item.status === 'failed' ? 'Failed' : 'Completed')
190
+ + ' · ' + totals.failedOperations + (totals.failedOperations === 1 ? ' failed operation' : ' failed operations') : undefined;
191
+ statusInto(runStatus, item.status, caption, true);
192
+ }
193
+ const exportLink = byId('export-trace');
194
+ exportLink.classList.toggle('dis', !available);
195
+ exportLink.setAttribute('aria-disabled', String(!available));
196
+ if (available) {
197
+ exportLink.href = '/api/traces/' + trace.id;
198
+ exportLink.download = 'agenttrace-' + trace.id + '.json';
199
+ } else {
200
+ exportLink.removeAttribute('href');
201
+ exportLink.removeAttribute('download');
202
+ }
203
+ updateLiveLabel();
204
+ if (!available) return;
205
+
206
+ const { totals, counts, evidence, last } = activity;
207
+ const values = [
208
+ formatDuration(trace.durationMs ?? last?.offsetMs),
209
+ formatNumber(totals.inputTokens), formatNumber(totals.outputTokens),
210
+ formatCost(totals.pricedRequests ? totals.costUsd : undefined),
211
+ formatNumber(totals.unpricedRequests), formatNumber(counts.all),
212
+ ];
213
+ metrics.forEach((node, index) => { node.textContent = values[index]; });
214
+ if (evidence) {
215
+ const { claim, failedCheck, file } = evidence;
216
+ byId('artifact-title').textContent = file ? 'File ' + file.event.change : 'File evidence';
217
+ byId('artifact-path').textContent = file?.event.path ?? 'No tracked file change';
218
+ byId('check-title').textContent = 'Verification failed';
219
+ byId('check-error').textContent = failedCheck.details.find(([label]) => label === 'Error')?.[1] ?? failedCheck.title;
220
+ byId('claim-message').textContent = '“' + claim.event.message + '”';
221
+ }
222
+ }
223
+
224
+ function updateLiveLabel() {
225
+ const live = byId('live-info');
226
+ live.hidden = trace?.status !== 'open' || Boolean(traceError);
227
+ if (!live.hidden) {
228
+ const seconds = Math.max(0, Math.floor((Date.now() - Date.parse(activity.last?.at ?? trace.startedAt)) / 1000));
229
+ live.textContent = 'Updating live, last event ' + (seconds < 60 ? seconds + 's ago' : timestamp(activity.last?.at ?? trace.startedAt));
230
+ }
231
+ }
232
+
233
+ function renderActivity() {
234
+ if (!activity) return;
235
+ const { rows, counts, evidence } = activity;
236
+ for (const chip of filters) {
237
+ const name = chip.dataset.filter;
238
+ chip.querySelector('.ct').textContent = formatNumber(counts[name]);
239
+ chip.classList.toggle('on', filter === name);
240
+ chip.setAttribute('aria-pressed', String(filter === name));
241
+ }
242
+ const visible = filter === 'all' ? rows : rows.filter((row) => row.category === filter);
243
+ byId('event-columns').hidden = !visible.length;
244
+ byId('activity-scroll').hidden = !visible.length && filter !== 'all';
245
+ byId('unmatched-events').hidden = Boolean(visible.length || filter === 'all');
246
+ byId('filter-title').textContent = 'No ' + labels[filter] + ' events in this run';
247
+ byId('filter-description').textContent = 'This run recorded ' + formatNumber(counts.all)
248
+ + (counts.all === 1 ? ' event.' : ' events.');
249
+ const waiting = byId('waiting');
250
+ waiting.hidden = filter !== 'all' || (trace.status !== 'open' && visible.length > 0);
251
+ waiting.textContent = trace.status === 'open' ? 'Waiting for the next event…' : 'This run did not record any activity.';
252
+
253
+ const activeKey = events.contains(document.activeElement) ? document.activeElement.dataset.key : null;
254
+ const fragment = document.createDocumentFragment();
255
+ let focus;
256
+ for (const row of visible) {
257
+ const { key, category, parent, title, event, status, statusText, duration, details } = row;
258
+ const button = element('button', 'ev');
259
+ button.type = 'button';
260
+ button.dataset.key = key;
261
+ if (activeKey === key) focus = button;
262
+ button.classList.toggle('nested', Boolean(parent));
263
+ button.classList.toggle('bad', status === 'failed');
264
+ const categoryNode = element('span', 'ty');
265
+ categoryNode.append(icon(category), labels[category]);
266
+ const name = element('span', 'nmx' + (['model', 'decision', 'capture'].includes(category) ? '' : ' mono'));
267
+ if (parent) name.append(element('span', 'parent', 'in ' + parent + ' · '));
268
+ name.append(title ?? '');
269
+ name.title = name.textContent;
270
+ const badge = element('span', 'stt');
271
+ if (status) statusInto(badge, status, category === 'tool' && status === 'passed' ? '' : statusText);
272
+ const chevron = icon('expand');
273
+ button.append(
274
+ element('span', 'off', Number.isFinite(event.offsetMs) ? '+' + (event.offsetMs / 1000).toFixed(1) + 's' : '—'),
275
+ chevron, categoryNode, name, badge, element('span', 'du', formatDuration(duration)),
276
+ );
277
+ const panel = element('div', parent ? 'dt nested' : 'dt');
278
+ panel.id = 'event-' + key;
279
+ button.setAttribute('aria-controls', panel.id);
280
+ const inner = element('div');
281
+ const fields = element('dl', 'dbox');
282
+ for (const [label, value] of details) fields.append(element('dt', 'l', label), element('dd', 'v', value ?? '—'));
283
+ inner.append(fields);
284
+ panel.append(inner);
285
+ function setExpanded(open) {
286
+ button.setAttribute('aria-expanded', String(open));
287
+ chevron.classList.toggle('o', open);
288
+ panel.classList.toggle('open', open);
289
+ panel.setAttribute('aria-hidden', String(!open));
290
+ }
291
+ setExpanded(expansion.get(key) ?? Boolean(evidence && (row === evidence.file || row === evidence.failedCheck)));
292
+ button.addEventListener('click', () => {
293
+ const open = button.getAttribute('aria-expanded') !== 'true';
294
+ expansion.set(key, open);
295
+ setExpanded(open);
296
+ });
297
+ fragment.append(button, panel);
298
+ }
299
+ events.replaceChildren(fragment);
300
+ focus?.focus({ preventScroll: true });
301
+ }
302
+
303
+ async function request(path, controller) {
304
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]);
305
+ const response = await fetch(path, { signal });
306
+ if (!response.ok) {
307
+ const { error } = await response.json();
308
+ throw new Error(error ?? 'Request failed');
309
+ }
310
+ return response.json();
311
+ }
312
+
313
+ async function loadTrace() {
314
+ if (!selected || detailRequest) return;
315
+ const id = selected;
316
+ const controller = new AbortController();
317
+ detailRequest = controller;
318
+ try {
319
+ const current = await request('/api/traces/' + id, controller);
320
+ if (detailRequest !== controller) return;
321
+ const key = [current.id, current.updatedAt, current.events.length, current.status].join('/');
322
+ if (traceKey !== key || traceError) {
323
+ trace = current;
324
+ traceKey = key;
325
+ traceError = '';
326
+ activity = readActivity(current);
327
+ if (older.has(id)) {
328
+ const { events: _events, ...summary } = current;
329
+ older.set(id, summary);
330
+ renderRuns();
331
+ }
332
+ renderOverview();
333
+ renderActivity();
334
+ renderPanels();
335
+ } else updateLiveLabel();
336
+ } catch (error) {
337
+ if (detailRequest !== controller) return;
338
+ traceError = error.message;
339
+ renderOverview();
340
+ renderPanels();
341
+ } finally {
342
+ if (detailRequest === controller) detailRequest = undefined;
343
+ }
344
+ }
345
+
346
+ function selectRun(id) {
347
+ if (id === selected) return;
348
+ detailRequest?.abort();
349
+ detailRequest = undefined;
350
+ selected = id;
351
+ trace = null;
352
+ activity = null;
353
+ traceKey = null;
354
+ traceError = '';
355
+ noticeMessage = '';
356
+ filter = 'all';
357
+ expansion.clear();
358
+ byId('activity-scroll').scrollTop = 0;
359
+ renderRuns();
360
+ renderPanels();
361
+ void loadTrace();
362
+ }
363
+
364
+ function chooseRun() {
365
+ const hash = location.hash.slice(1);
366
+ const latest = query ? null : firstPage[0]?.id ?? null;
367
+ selectRun(idPattern.test(hash) ? hash : latest);
368
+ }
369
+
370
+ async function loadRuns(after = null) {
371
+ if (listRequest) return;
372
+ const controller = new AbortController();
373
+ listRequest = controller;
374
+ more.disabled = true;
375
+ try {
376
+ const params = new URLSearchParams();
377
+ if (query) params.set('q', query);
378
+ if (after) params.set('after', after);
379
+ const page = await request('/api/traces?' + params, controller);
380
+ if (listRequest !== controller) return;
381
+ if (after) {
382
+ for (const run of page.traces) older.set(run.id, run);
383
+ next = page.next;
384
+ } else {
385
+ const lastId = page.traces.at(-1)?.id;
386
+ for (const run of firstPage) {
387
+ // A newly recorded run can push a previously visible row onto page two.
388
+ if (older.size && lastId && run.id < lastId) older.set(run.id, run);
389
+ }
390
+ firstPage = page.traces;
391
+ if (!older.size) next = page.next;
392
+ }
393
+ directory = page.directory;
394
+ total = page.total;
395
+ loadError = '';
396
+ if (!selected) chooseRun();
397
+ const summary = firstPage.find((run) => run.id === selected);
398
+ if (summary && trace && (summary.updatedAt !== trace.updatedAt || summary.status !== trace.status)) void loadTrace();
399
+ } catch (error) {
400
+ if (listRequest !== controller) return;
401
+ loadError = error.message;
402
+ } finally {
403
+ if (listRequest === controller) {
404
+ listRequest = undefined;
405
+ more.disabled = false;
406
+ shell.hidden = false;
407
+ byId('initial-loading').hidden = true;
408
+ renderRuns();
409
+ renderPanels();
410
+ }
411
+ }
412
+ }
413
+
414
+ function updateSearch() {
415
+ clearTimeout(searchTimer);
416
+ searchTimer = undefined;
417
+ byId('clear-search').hidden = !search.value;
418
+ const value = search.value.trim();
419
+ if (value === query) return;
420
+ listRequest?.abort();
421
+ listRequest = undefined;
422
+ searchTimer = setTimeout(() => {
423
+ searchTimer = undefined;
424
+ query = value;
425
+ next = null;
426
+ firstPage = [];
427
+ older.clear();
428
+ list.scrollTop = 0;
429
+ void loadRuns();
430
+ }, value ? 180 : 0);
431
+ }
432
+
433
+ function clearSearch() {
434
+ search.value = '';
435
+ search.focus();
436
+ updateSearch();
437
+ }
438
+
439
+ async function copy(button, value) {
440
+ try {
441
+ await navigator.clipboard.writeText(value);
442
+ const label = button.title || button.getAttribute('aria-label') || button.textContent.trim();
443
+ button.title = 'Copied';
444
+ noticeMessage = label === 'Copy path' ? '' : 'Trace ID copied.';
445
+ } catch {
446
+ noticeMessage = 'Clipboard access unavailable.';
447
+ button.title = noticeMessage;
448
+ }
449
+ renderNotice();
450
+ }
451
+
452
+ search.addEventListener('input', updateSearch);
453
+ byId('clear-search').addEventListener('click', clearSearch);
454
+ byId('clear-results').addEventListener('click', clearSearch);
455
+ more.addEventListener('click', () => { if (next) void loadRuns(next); });
456
+ for (const button of filters) button.addEventListener('click', () => {
457
+ filter = button.dataset.filter;
458
+ renderActivity();
459
+ });
460
+ byId('show-all').addEventListener('click', () => {
461
+ filter = 'all';
462
+ renderActivity();
463
+ filters[0].focus();
464
+ });
465
+ byId('copy-id').addEventListener('click', ({ currentTarget }) => void copy(currentTarget, selected));
466
+ byId('copy-path').addEventListener('click', ({ currentTarget }) => void copy(currentTarget, byId('error-path').textContent));
467
+ byId('retry').addEventListener('click', () => {
468
+ if (traceError && selected) void loadTrace();
469
+ else void loadRuns();
470
+ });
471
+ window.addEventListener('hashchange', chooseRun);
472
+
473
+ function refresh() {
474
+ if (document.hidden) return;
475
+ if (!searchTimer) void loadRuns();
476
+ if (selected && (!trace || trace.status === 'open' || traceError)) void loadTrace();
477
+ }
478
+ if (idPattern.test(location.hash.slice(1))) chooseRun();
479
+ void loadRuns();
480
+ setInterval(refresh, 2500);
481
+ document.addEventListener('visibilitychange', refresh);