pisha-server 0.0.11 → 0.0.13

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/ui/webhooks.js ADDED
@@ -0,0 +1,427 @@
1
+ import { $ } from './dom.js'
2
+ import { T, LOCALE, COLLATOR } from './i18n.js'
3
+ import { state, can } from './state.js'
4
+ import { api } from './api.js'
5
+ import { esc, ago } from './format.js'
6
+ import { setHtml } from './nav.js'
7
+ import { currentRoute } from './router.js'
8
+ import { dialog, confirmDialog, closeMenu } from './dialogs.js'
9
+ import { alertBox } from './mosaic.js'
10
+ import { postJson } from './machines.js'
11
+
12
+ // Webhooks: a team's door for other services (GitHub, GitLab…). Each team's
13
+ // page lists its own, and managers make and change them there; #/webhooks is
14
+ // the log of what came in through all of them (or one team's), and each
15
+ // entry opens with what came, as it came. See server/webhooks.
16
+
17
+ const STATUS_TAG = {
18
+ queued: 'info', delivered: 'info', processing: 'info', unreported: 'warn', done: 'ok', ignored: '', failed: 'err', filtered: '', ping: '', duplicate: '', undelivered: 'err', no_coordinator: 'err',
19
+ bad_signature: 'err', bad_json: 'warn', too_large: 'warn', disabled: 'warn', rate_limited: 'warn',
20
+ }
21
+ const STATUSES = Object.keys(STATUS_TAG)
22
+ const PRESETS = ['github', 'gitlab', 'stripe', 'standard', 'custom']
23
+ const VERIFY = ['hmac-sha256', 'token', 'stripe', 'standard']
24
+ // (Stripe and Standard Webhooks make the secret themselves: it is pasted.)
25
+ const FROM_SERVICE = ['stripe', 'standard']
26
+ const verifyOf = (preset, custom) => ({ github: 'hmac-sha256', gitlab: 'token', stripe: 'stripe', standard: 'standard' })[preset] ?? custom
27
+ const WHEN = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
28
+
29
+ let hooks = null // the company's webhooks, or null before they arrive
30
+ let loadingHooks = null
31
+ const log = { rows: [], next: null, key: '', seq: 0, loading: false, error: null }
32
+ const filter = { webhook: '', status: '' }
33
+ let filterTeam = null // (the team the filters were chosen for: another one starts without them)
34
+
35
+ const teamTitle = c => state.squadMeta.get(c)?.title || c
36
+ const urlOf = h => `${location.origin}${h.path}`
37
+ const statusTag = s => `<span class="tag ${STATUS_TAG[s] ?? ''}" data-whstatus="${esc(s)}">${esc(T.whStatus[s] ?? s)}</span>`
38
+ const eventOf = d => (d.event ? `${d.event}${d.action ? `.${d.action}` : ''}` : '—')
39
+
40
+ export function loadHooks(force = false) {
41
+ if (loadingHooks && !force) return loadingHooks
42
+ loadingHooks = api('/api/webhooks').then(list => { hooks = list; redraw() }).catch(() => { hooks ??= [] }).finally(() => { loadingHooks = null })
43
+ return loadingHooks
44
+ }
45
+ function redraw() {
46
+ const r = currentRoute()
47
+ if (r.view === 'team' && !$('team').hidden) void import('./team.js').then(m => m.refreshTeam())
48
+ if (r.view === 'webhooks' && !$('webhooks').hidden) drawScreen()
49
+ }
50
+
51
+ // --- the live stream -----------------------------------------------------------
52
+ export function webhooksArrived(list) {
53
+ hooks = Array.isArray(list) ? list : []
54
+ redraw()
55
+ }
56
+ export function deliveryArrived(d) {
57
+ if (!d?.id) return
58
+ const i = log.rows.findIndex(x => x.id === d.id)
59
+ if (i >= 0) log.rows[i] = d
60
+ else if (matches(d) && (!log.rows.length || d.id > log.rows[0].id)) log.rows.unshift(d)
61
+ else return
62
+ if (hooks) { const h = hooks.find(x => x.id === d.webhook_id); if (h && (!h.last_delivery || h.last_delivery.id <= d.id)) h.last_delivery = { id: d.id, received_at: d.received_at, status: d.status, event: d.event } }
63
+ redraw()
64
+ }
65
+ function matches(d) {
66
+ const team = currentRoute().team
67
+ if (team && d.coordinator !== team && hooks?.find(h => h.id === d.webhook_id)?.coordinator !== team) return false
68
+ if (filter.webhook && String(d.webhook_id) !== filter.webhook) return false
69
+ if (filter.status && d.status !== filter.status) return false
70
+ return true
71
+ }
72
+
73
+ // --- a team's page: its webhooks -----------------------------------------------
74
+ export function webhooksSection(coord) {
75
+ if (!hooks) { void loadHooks(); return card(coord, `<p class="tq-quiet">${esc(T.loading)}</p>`) }
76
+ const mine = hooks.filter(h => h.coordinator === coord).sort((a, b) => COLLATOR.compare(a.name, b.name))
77
+ const body = mine.length ? `<ul class="wh-list">${mine.map(row).join('')}</ul>` : `<p class="tq-quiet">${esc(T.whNone)}</p>`
78
+ return card(coord, body)
79
+ }
80
+ function card(coord, body) {
81
+ return `<section class="card tq-card" id="whSection">
82
+ <header class="tq-h"><h2>${esc(T.whTitle)}</h2><span class="wh-h-acts"><a class="btn quiet" href="#/webhooks/q/${encodeURIComponent(coord)}">${esc(T.whSeeLog)}</a>${can('manager') ? `<button type="button" class="btn" data-wh-new="${esc(coord)}">${esc(T.whNew)}</button>` : ''}</span></header>
83
+ ${body}
84
+ </section>`
85
+ }
86
+ function row(h) {
87
+ const last = h.last_delivery
88
+ const state_ = h.enabled ? `<span class="dot ok" aria-hidden="true"></span>${esc(T.whOn)}` : `<span class="dot warn" aria-hidden="true"></span>${esc(h.disabled_reason === 'no_coordinator' ? T.whOffNoCoord : T.whOff)}`
89
+ return `<li class="wh-row" data-wh="${h.id}">
90
+ <div class="wh-main"><b class="wh-name">${esc(h.name)}</b><span class="tag">${esc(T.whPreset[h.preset] ?? h.preset)}</span><span class="wh-state">${state_}</span></div>
91
+ <div class="wh-meta">${h.batch_seconds ? `<span class="tag">${esc(T.whBatchTag(h.batch_seconds))}</span>` : ''}${last ? `${statusTag(last.status)}<span>${esc(eventOf(last))}</span><span class="wh-when">${esc(ago(last.received_at))}</span>` : `<span>${esc(T.whNothingYet)}</span>`}${h.events ? `<span class="wh-events" title="${esc(h.events.join(', '))}">${esc(T.whOnlyEvents(h.events.length))}</span>` : ''}</div>
92
+ ${can('manager') ? `<button type="button" class="icon-btn wh-more" data-wh-menu="${h.id}" aria-label="${esc(T.whActions(h.name))}" title="${esc(T.whActions(h.name))}">⋯</button>` : ''}
93
+ </li>`
94
+ }
95
+
96
+ function openMenu(anchor, id) {
97
+ closeMenu()
98
+ const h = hooks?.find(x => x.id === id)
99
+ if (!h) return
100
+ const m = document.createElement('div')
101
+ m.className = 'menu'
102
+ m.innerHTML = `<button data-a="edit">${esc(T.whEdit)}</button>
103
+ <button data-a="test" ${h.enabled ? '' : 'disabled'}>${esc(T.whTest)}</button>
104
+ <button data-a="url">${esc(T.whShowUrl)}</button>
105
+ <button data-a="secret">${esc(T.whNewSecret)}</button>
106
+ <button data-a="toggle">${esc(h.enabled ? T.whTurnOff : T.whTurnOn)}</button>
107
+ <button data-a="delete" class="danger">${esc(T.delete)}</button>`
108
+ document.body.appendChild(m)
109
+ state.menuEl = m
110
+ const r = anchor.getBoundingClientRect()
111
+ m.style.top = `${Math.min(r.bottom + 4, innerHeight - m.offsetHeight - 8)}px`
112
+ m.style.left = `${Math.max(8, Math.min(r.right - m.offsetWidth, innerWidth - m.offsetWidth - 8))}px`
113
+ m.addEventListener('click', e => {
114
+ const b = e.target.closest('button')
115
+ if (!b || b.disabled) return
116
+ closeMenu()
117
+ hookAction(b.dataset.a, h)
118
+ })
119
+ }
120
+
121
+ async function hookAction(a, h) {
122
+ if (a === 'edit') return hookDialog({ hook: h })
123
+ if (a === 'url') return secretDialog({ ...h, url: urlOf(h) }, { secret: null })
124
+ if (a === 'test') {
125
+ try {
126
+ const d = await postJson('/api/webhooks/test', { id: h.id })
127
+ alertBox(T.whTestSent(d.id, T.whStatus[d.status] ?? d.status), T.whTest)
128
+ } catch (err) { alertBox(err.message) }
129
+ return
130
+ }
131
+ if (a === 'toggle') return postJson('/api/webhooks/update', { id: h.id, enabled: !h.enabled }).then(() => loadHooks(true)).catch(err => alertBox(err.message))
132
+ if (a === 'secret' && h.secret_from_service) return pasteSecretDialog(h)
133
+ if (a === 'secret') {
134
+ return confirmDialog({
135
+ title: T.whNewSecretTitle(h.name), text: esc(T.whNewSecretText), confirm: T.whNewSecret, danger: true,
136
+ run: async () => { const r = await postJson('/api/webhooks/secret', { id: h.id }); secretDialog({ ...h, url: urlOf(h) }, { secret: r.secret, renewed: true }) },
137
+ })
138
+ }
139
+ if (a === 'delete') {
140
+ return confirmDialog({
141
+ title: T.whDeleteTitle(h.name), text: esc(T.whDeleteText), confirm: T.delete, danger: true,
142
+ run: async () => { await postJson('/api/webhooks/delete', { id: h.id }); await loadHooks(true) },
143
+ })
144
+ }
145
+ }
146
+
147
+ // --- making and changing one ---------------------------------------------------
148
+ function hookDialog({ hook = null, coordinator = hook?.coordinator } = {}) {
149
+ const editing = !!hook
150
+ let preset = hook?.preset ?? 'github'
151
+ const v = k => esc(hook?.[k] ?? '')
152
+ const { el, close } = dialog(`<h3>${esc(editing ? T.whEditTitle(hook.name) : T.whNewTitle(teamTitle(coordinator)))}</h3>
153
+ <form class="wh-form" novalidate>
154
+ <label class="field"><span>${esc(T.whName)}</span><input name="name" maxlength="80" required value="${v('name')}" placeholder="${esc(T.whNamePh)}"></label>
155
+ ${editing ? '' : `<div class="field"><span>${esc(T.whService)}</span><span class="seg" role="group" aria-label="${esc(T.whService)}">${PRESETS.map(p => `<button type="button" data-preset="${p}" aria-pressed="${p === preset}" class="${p === preset ? 'on' : ''}">${esc(T.whPreset[p])}</button>`).join('')}</span></div>`}
156
+ <div class="wh-custom" ${preset === 'custom' ? '' : 'hidden'}>
157
+ <label class="field"><span>${esc(T.whVerify)}</span><select name="verify" ${editing ? 'disabled' : ''}>${VERIFY.map(x => `<option value="${x}"${(hook?.verify ?? 'hmac-sha256') === x ? ' selected' : ''}>${esc(T.whVerifyName[x])}</option>`).join('')}</select></label>
158
+ <div class="row2">
159
+ <label class="field"><span>${esc(T.whSigHeader)}</span><input name="signature_header" value="${v('signature_header')}" placeholder="X-Signature"></label>
160
+ <label class="field"><span>${esc(T.whEventHeader)}</span><input name="event_header" value="${v('event_header')}" placeholder="X-Event"></label>
161
+ </div>
162
+ <label class="field"><span>${esc(T.whDeliveryHeader)}</span><input name="delivery_header" value="${v('delivery_header')}" placeholder="X-Delivery-Id"></label>
163
+ </div>
164
+ <label class="field"><span>${esc(T.whEvents)}</span><input name="events" value="${esc(hook?.events?.join(', ') ?? '')}" placeholder="push, pull_request.opened, issues"><small class="dim-note">${esc(T.whEventsHint)}</small></label>
165
+ <label class="field"><span>${esc(T.whPrompt)}</span><textarea name="prompt" rows="4" maxlength="4000" placeholder="${esc(T.whPromptPh)}">${v('prompt')}</textarea><small class="dim-note">${esc(T.whPromptHint)}</small></label>
166
+ <div class="field wh-by-event"><span>${esc(T.whByEvent)}</span><small class="dim-note">${esc(T.whByEventHint)}</small>
167
+ <div class="wh-pe-list" data-pe-list>${Object.entries(hook?.prompts ?? {}).map(([e, t]) => peRow(e, t)).join('')}</div>
168
+ <button type="button" class="btn quiet wh-pe-add" data-pe-add>${esc(T.whByEventAdd)}</button></div>
169
+ <label class="field wh-batch"><span>${esc(T.whBatch)}</span><input type="number" name="batch_seconds" min="0" max="300" step="1" inputmode="numeric" value="${esc(hook?.batch_seconds ?? 0)}"><small class="dim-note">${esc(T.whBatchHint)}</small></label>
170
+ ${editing ? '' : `<label class="field"><span data-secret-label>${esc(T.whOwnSecret)}</span><input name="secret" autocomplete="off" spellcheck="false" placeholder="${esc(T.whOwnSecretPh)}"><small class="dim-note" data-secret-hint hidden>${esc(T.whServiceSecretHint)}</small></label>`}
171
+ <div class="err"></div>
172
+ <div class="actions wh-actions"><button type="button" class="btn" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(editing ? T.save : T.whCreate)}</button></div>
173
+ </form>`, { wide: true })
174
+ const form = el.querySelector('form')
175
+ form.querySelector('[name=name]').focus()
176
+ // (The secret: one's own or made here, or the one the service made.)
177
+ const secretKind = () => {
178
+ if (editing) return
179
+ const fromService = FROM_SERVICE.includes(verifyOf(preset, form.querySelector('[name=verify]').value))
180
+ el.querySelector('[data-secret-label]').textContent = fromService ? T.whServiceSecret : T.whOwnSecret
181
+ form.querySelector('[name=secret]').placeholder = fromService ? 'whsec_…' : T.whOwnSecretPh
182
+ el.querySelector('[data-secret-hint]').hidden = !fromService
183
+ }
184
+ el.querySelectorAll('[data-preset]').forEach(b => b.addEventListener('click', () => {
185
+ preset = b.dataset.preset
186
+ el.querySelectorAll('[data-preset]').forEach(x => { x.classList.toggle('on', x === b); x.setAttribute('aria-pressed', String(x === b)) })
187
+ el.querySelector('.wh-custom').hidden = preset !== 'custom'
188
+ secretKind()
189
+ }))
190
+ form.querySelector('[name=verify]').addEventListener('change', secretKind)
191
+ el.querySelector('[data-pe-add]').addEventListener('click', () => {
192
+ el.querySelector('[data-pe-list]').insertAdjacentHTML('beforeend', peRow('', ''))
193
+ el.querySelector('[data-pe-list] .wh-pe-row:last-child [name=pe-event]').focus()
194
+ })
195
+ el.querySelector('[data-pe-list]').addEventListener('click', e => { e.target.closest('[data-pe-del]')?.closest('.wh-pe-row')?.remove() })
196
+ form.addEventListener('submit', async e => {
197
+ e.preventDefault()
198
+ const f = Object.fromEntries(new FormData(form))
199
+ const events = String(f.events ?? '').split(/[\s,]+/).filter(Boolean)
200
+ const prompts = {}
201
+ for (const r of el.querySelectorAll('.wh-pe-row')) {
202
+ const ev = r.querySelector('[name=pe-event]').value.trim(), text = r.querySelector('[name=pe-text]').value.trim()
203
+ if (ev || text) prompts[ev] = text
204
+ }
205
+ const body = { name: f.name, events: events.length ? events : null, prompt: f.prompt ?? '', prompts: Object.keys(prompts).length ? prompts : null, batch_seconds: Number(f.batch_seconds || 0) }
206
+ if (preset === 'custom') Object.assign(body, { ...(editing ? {} : { verify: f.verify }), signature_header: f.signature_header, event_header: f.event_header, delivery_header: f.delivery_header })
207
+ const btn = form.querySelector('[type=submit]')
208
+ btn.disabled = true
209
+ try {
210
+ if (editing) {
211
+ await postJson('/api/webhooks/update', { id: hook.id, ...body })
212
+ close()
213
+ } else {
214
+ const made = await postJson('/api/webhooks/create', { ...body, coordinator, preset, ...(f.secret ? { secret: f.secret } : {}) })
215
+ close()
216
+ secretDialog(made, { secret: made.secret, made: true })
217
+ }
218
+ await loadHooks(true)
219
+ } catch (err) {
220
+ el.querySelector('.err').textContent = err.message
221
+ btn.disabled = false
222
+ }
223
+ })
224
+ }
225
+
226
+ // What to do with one event: its name and the words for it.
227
+ const peRow = (event, text) => `<div class="wh-pe-row">
228
+ <input name="pe-event" value="${esc(event)}" placeholder="pull_request.opened" aria-label="${esc(T.whEvent)}" spellcheck="false">
229
+ <textarea name="pe-text" rows="2" maxlength="4000" aria-label="${esc(T.whPrompt)}" placeholder="${esc(T.whPromptPh)}">${esc(text)}</textarea>
230
+ <button type="button" class="btn quiet" data-pe-del aria-label="${esc(T.whRemove)}" title="${esc(T.whRemove)}">✕</button>
231
+ </div>`
232
+
233
+ // A new secret the service made: pasted here (one generated here would never match).
234
+ function pasteSecretDialog(h) {
235
+ const { el, close } = dialog(`<h3>${esc(T.whNewSecretTitle(h.name))}</h3>
236
+ <form class="wh-form" novalidate>
237
+ <p class="dim-note">${esc(T.whPasteSecretText)}</p>
238
+ <label class="field"><span>${esc(T.whServiceSecret)}</span><input name="secret" autocomplete="off" spellcheck="false" placeholder="whsec_…" required></label>
239
+ <div class="err"></div>
240
+ <div class="actions wh-actions"><button type="button" class="btn" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(T.save)}</button></div>
241
+ </form>`)
242
+ const form = el.querySelector('form')
243
+ form.querySelector('[name=secret]').focus()
244
+ form.addEventListener('submit', async e => {
245
+ e.preventDefault()
246
+ try { await postJson('/api/webhooks/secret', { id: h.id, secret: form.querySelector('[name=secret]').value.trim() }); close() } catch (err) { el.querySelector('.err').textContent = err.message }
247
+ })
248
+ }
249
+
250
+ // Where to send it and with what secret: shown once, when made or renewed.
251
+ function secretDialog(h, { secret, made = false, renewed = false }) {
252
+ const copyRow = (text, id) => `<div class="cmdrow"><pre class="cmd" id="${id}">${esc(text)}</pre><button type="button" class="btn" data-copy-from="${id}">${esc(T.copy)}</button></div>`
253
+ const steps = T.whSteps[h.preset] ?? T.whSteps.custom
254
+ const { el } = dialog(`<h3>${esc(made ? T.whMadeTitle(h.name) : renewed ? T.whRenewedTitle(h.name) : T.whUrlTitle(h.name))}</h3>
255
+ <div class="wh-secret">
256
+ <p class="wh-label">${esc(T.whUrl)}</p>${copyRow(h.url ?? urlOf(h), 'whUrl')}
257
+ ${h.secret_from_service ? `<p class="dim-note">${esc(T.whSecretFromService)}</p>` : secret ? `<p class="wh-label">${esc(h.verify === 'token' ? T.whToken : T.whSecret)}</p>${copyRow(secret, 'whSecretVal')}<p class="wh-note">${esc(T.whSecretOnce)}</p>` : `<p class="wh-note">${esc(T.whSecretHidden)}</p>`}
258
+ <ol class="wh-steps">${steps.map(s => `<li>${esc(s)}</li>`).join('')}</ol>
259
+ <p class="dim-note">${esc(T.whPublicNote)}</p>
260
+ </div>
261
+ <div class="actions wh-actions"><button type="button" class="btn primary" data-cancel>${esc(T.close)}</button></div>`, { wide: true })
262
+ el.addEventListener('click', async e => {
263
+ const b = e.target.closest('[data-copy-from]')
264
+ if (!b) return
265
+ try { await navigator.clipboard.writeText(el.querySelector(`#${b.dataset.copyFrom}`).textContent); b.textContent = T.copied } catch {}
266
+ })
267
+ }
268
+
269
+ // --- the log -------------------------------------------------------------------
270
+ export function webhooksHead() {
271
+ const team = currentRoute().team
272
+ return { title: esc(team ? T.whLogOf(teamTitle(team)) : T.whTitle) }
273
+ }
274
+
275
+ export function renderWebhooks() {
276
+ if (!hooks) void loadHooks()
277
+ const team = currentRoute().team ?? ''
278
+ if (team !== filterTeam) { filterTeam = team; filter.webhook = '' }
279
+ const key = `${currentRoute().team ?? ''}|${filter.webhook}|${filter.status}`
280
+ if (key !== log.key) { log.key = key; log.rows = []; log.next = null; log.error = null; void loadLog() }
281
+ drawScreen()
282
+ }
283
+
284
+ async function loadLog(more = false) {
285
+ const seq = ++log.seq
286
+ log.loading = true
287
+ const q = new URLSearchParams({ limit: '100' })
288
+ const team = currentRoute().team
289
+ if (team) q.set('coordinator', team)
290
+ if (filter.webhook) q.set('webhook', filter.webhook)
291
+ if (filter.status) q.set('status', filter.status)
292
+ if (more && log.next) q.set('before', String(log.next))
293
+ try {
294
+ const r = await api(`/api/webhooks/deliveries?${q}`)
295
+ if (seq !== log.seq) return
296
+ log.rows = more ? [...log.rows, ...r.deliveries] : r.deliveries
297
+ log.next = r.next_before
298
+ log.error = null
299
+ } catch (err) { if (seq === log.seq) log.error = err.message }
300
+ if (seq === log.seq) log.loading = false
301
+ if (currentRoute().view === 'webhooks') drawScreen()
302
+ }
303
+
304
+ function drawScreen() {
305
+ const team = currentRoute().team
306
+ const list = (hooks ?? []).filter(h => !team || h.coordinator === team)
307
+ const sel = (k, opts, all) => `<label class="u-filter"><span class="sr-only">${esc(all)}</span><select data-whfilter="${k}"><option value="">${esc(all)}</option>${opts.map(([v, l]) => `<option value="${esc(v)}"${filter[k] === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`
308
+ const filters = `<div class="u-filters">
309
+ ${sel('webhook', list.map(h => [String(h.id), team ? h.name : `${h.name} · ${teamTitle(h.coordinator)}`]), T.whAllWebhooks)}
310
+ ${sel('status', STATUSES.map(s => [s, T.whStatus[s]]), T.whAllStatuses)}
311
+ ${team ? `<a class="btn quiet" href="#/q/${encodeURIComponent(team)}">${esc(T.whBackToTeam)}</a>` : ''}
312
+ </div>`
313
+ let body
314
+ if (log.error) body = `<p class="err">${esc(log.error)}</p>`
315
+ else if (!log.rows.length) body = log.loading ? `<p class="dim-note">${esc(T.loading)}</p>` : `<div class="empty"><b>${esc(T.whLogEmpty)}</b><span>${esc(hooks && !list.length ? T.whLogNoHooks : T.whLogEmptyHint)}</span></div>`
316
+ else {
317
+ body = `<div class="card wh-table-card"><div class="mc-scroll"><table class="wh-table">
318
+ <thead><tr><th scope="col">${esc(T.whWhen)}</th><th scope="col">${esc(T.whWebhook)}</th><th scope="col">${esc(T.whEvent)}</th><th scope="col">${esc(T.whState)}</th><th scope="col">${esc(T.whResult)}</th></tr></thead>
319
+ <tbody>${log.rows.map(d => `<tr data-whd="${d.id}" tabindex="0">
320
+ <td class="wh-when-c"><span title="${esc(new Date(d.received_at).toISOString())}">${esc(WHEN.format(d.received_at))}</span><small>#${d.id}</small></td>
321
+ <td>${esc(d.webhook_name ?? '')}${team ? '' : `<small>${esc(teamTitle(d.coordinator ?? hooks?.find(h => h.id === d.webhook_id)?.coordinator ?? ''))}</small>`}</td>
322
+ <td class="wh-ev">${esc(eventOf(d))}</td>
323
+ <td>${statusTag(d.status)}</td>
324
+ <td class="wh-res">${esc(resultLine(d))}</td>
325
+ </tr>`).join('')}</tbody></table></div></div>
326
+ ${log.next ? `<div class="wh-more-row"><button type="button" class="btn" data-whmore ${log.loading ? 'disabled' : ''}>${esc(T.whMore)}</button></div>` : ''}`
327
+ }
328
+ setHtml($('webhooks'), `<div class="u-wrap">${filters}${body}</div>`)
329
+ $('topSub').textContent = log.rows.length ? T.whShown(log.rows.length) : ''
330
+ }
331
+ // Why it ended as it did, in the dashboard's language. (The server's own words
332
+ // only where they are an error it met: the dashboard has none for it.)
333
+ function reasonText(d) {
334
+ if (Object.hasOwn(T.whWhy, d.status)) return T.whWhy[d.status]
335
+ const again = /^delivered again from #(\d+)$/.exec(d.reason ?? '')
336
+ if (again) return T.whWhyAgain(again[1])
337
+ if (d.event === 'pisha_test') return T.whWhyTest
338
+ return d.reason ?? ''
339
+ }
340
+ const waiting = d => d.waiting_for?.length ? T.whWaitingFor(d.waiting_for.join(', ')) : ''
341
+ const resultLine = d => d.summary || waiting(d) || (['processing', 'unreported'].includes(d.status) ? T.whWhy[d.status] : d.status === 'delivered' ? [T.whDeliveredTo(d.coordinator ?? ''), d.reason ? reasonText(d) : ''].filter(Boolean).join(' · ') : reasonText(d))
342
+
343
+ // One entry, whole: what came, as it came.
344
+ async function deliveryDialog(id) {
345
+ let d
346
+ try { d = await api(`/api/webhooks/delivery?id=${id}`) } catch (err) { return alertBox(err.message) }
347
+ let pretty = d.body
348
+ try { if (d.body != null) pretty = JSON.stringify(JSON.parse(d.body), null, 2) } catch {}
349
+ const fact = (k, v) => (v == null || v === '' ? '' : `<dt>${esc(k)}</dt><dd>${v}</dd>`)
350
+ const coord = d.coordinator
351
+ const headers = Object.entries(d.headers ?? {})
352
+ const { el, close } = dialog(`<h3 class="wh-d-h">${esc(T.whDeliveryTitle(d.id))} ${statusTag(d.status)}</h3>
353
+ <div class="wh-detail">
354
+ <dl class="wh-facts">
355
+ ${fact(T.whWebhook, esc(d.webhook_name ?? ''))}
356
+ ${fact(T.whWhen, esc(WHEN.format(d.received_at)))}
357
+ ${fact(T.whEvent, `<code>${esc(eventOf(d))}</code>`)}
358
+ ${fact(T.whDeliveryKey, d.delivery_key ? `<code>${esc(d.delivery_key)}</code>` : '')}
359
+ ${fact(T.whFrom, d.ip ? `<code>${esc(d.ip)}</code>` : '')}
360
+ ${fact(T.whSize, esc(T.whBytes(d.size)))}
361
+ ${fact(T.whReason, reasonText(d) ? esc(reasonText(d)) : '')}
362
+ ${fact(T.whTo, coord ? `<a href="#/s/${encodeURIComponent(coord)}/chat" data-cancel>${esc(coord)}</a>${d.message_id ? ` <small>(${esc(T.whMessage(d.message_id))})</small>` : ''}` : '')}
363
+ </dl>
364
+ ${turnHtml(d)}
365
+ ${headers.length ? `<details class="wh-headers"><summary>${esc(T.whHeaders(headers.length))}</summary><table class="wh-kv">${headers.map(([k, v]) => `<tr><th scope="row">${esc(k)}</th><td><code>${esc(v)}</code></td></tr>`).join('')}</table></details>` : ''}
366
+ <p class="wh-label">${esc(T.whBody)}</p>
367
+ ${d.body == null ? `<p class="dim-note">${esc(T.whNoBody)}</p>` : `<pre class="cmd wh-body">${esc(pretty)}</pre>`}
368
+ </div>
369
+ <div class="err"></div>
370
+ <div class="actions wh-actions">${d.body != null && can('manager') ? `<button type="button" class="btn" data-redeliver>${esc(T.whRedeliver)}</button>` : ''}<button type="button" class="btn primary" data-cancel>${esc(T.close)}</button></div>`, { wide: true })
371
+ el.querySelector('[data-redeliver]')?.addEventListener('click', async e => {
372
+ e.currentTarget.disabled = true
373
+ try { const r = await postJson('/api/webhooks/redeliver', { id: d.id }); close(); alertBox(T.whRedelivered(r.id), T.whRedeliver) } catch (err) { el.querySelector('.err').textContent = err.message; e.currentTarget.disabled = false }
374
+ })
375
+ }
376
+
377
+ // What its coordinator did with it: what it said came of it, its turn on it
378
+ // (how long, the tools it used, the messages it sent, its last words) and
379
+ // what that cost.
380
+ const FULL = new Intl.NumberFormat(LOCALE)
381
+ function turnHtml(d) {
382
+ if (!d.message_id) return ''
383
+ const t = d.trace, k = d.tokens
384
+ const took = d.turn_started_at && d.turn_ended_at ? T.whTook(Math.max(1, Math.round((d.turn_ended_at - d.turn_started_at) / 1000))) : d.turn_started_at ? T.whStillOn : ''
385
+ const report = d.outcome
386
+ ? `<p class="wh-report"><span class="tag ${STATUS_TAG[d.outcome]}">${esc(T.whStatus[d.outcome])}</span>${d.summary ? ` ${esc(d.summary)}` : ''}<small>${esc(ago(d.reported_at))}</small></p>`
387
+ : `<p class="dim-note">${esc(waiting(d) || (d.turn_started_at ? T.whNoReport : T.whNotYet))}</p>`
388
+ const tools = t?.tools?.length ? `<details class="wh-trace-part"><summary>${esc(T.whTools(t.tools_total ?? t.tools.length))}</summary><ol class="wh-tools">${t.tools.map(x => `<li class="${x.ok ? '' : 'bad'}"><code>${esc(x.tool)}</code> <span>${esc(x.summary)}</span></li>`).join('')}</ol></details>` : ''
389
+ const REPORT_TAG = { done: 'ok', blocked: 'err', failed: 'err', question: 'warn' }
390
+ const reportOf = m => (m.report
391
+ ? `<div class="wh-wreport"><span class="tag ${REPORT_TAG[m.report.state] ?? ''}">${esc(T.reportWord?.[m.report.state] ?? m.report.state)}</span> ${esc(m.report.text)}</div>`
392
+ : m.task ? `<div class="wh-wreport dim-note">${esc(T.whNoWorkerReport)}</div>` : '')
393
+ const tasks = (t?.messages ?? []).filter(m => m.task).length
394
+ const msgs = t?.messages?.length ? `<details class="wh-trace-part"${tasks ? ' open' : ''}><summary>${esc(T.whSent(t.messages.length))}</summary><ul class="wh-msgs">${t.messages.map(m => `<li><b>${esc(T.whSentTo(m.to))}</b> ${esc(m.text)}${reportOf(m)}</li>`).join('')}</ul></details>` : ''
395
+ const said = t?.text ? `<details class="wh-trace-part"><summary>${esc(T.whLastWords)}</summary><p class="wh-said">${esc(t.text)}</p></details>` : ''
396
+ const all = x => x.input + x.cache_read + x.cache_write + x.output
397
+ const w = d.worker_tokens
398
+ const cost = [k ? `<span>${esc(T.whTokens(FULL.format(all(k)), k.calls))}</span>` : '', w ? `<span>${esc(T.whWorkerTokens(FULL.format(all(w)), w.calls))}</span>` : ''].join('')
399
+ const together = d.together?.length ? `<p class="dim-note">${esc(T.whTogether(d.together.map(n => `#${n}`).join(', ')))}</p>` : ''
400
+ return `<section class="wh-turn"><p class="wh-label">${esc(T.whWhatItDid)}</p>${report}${together}
401
+ ${took || cost ? `<p class="wh-turn-meta">${took ? `<span>${esc(took)}</span>` : ''}${cost}</p>` : ''}
402
+ ${tools}${msgs}${said}
403
+ ${d.turn_ended_at && !t?.tools?.length && !t?.text ? `<p class="dim-note">${esc(T.whNoTrace)}</p>` : ''}</section>`
404
+ }
405
+
406
+ // --- clicks ----------------------------------------------------------------------
407
+ document.addEventListener('click', e => {
408
+ const n = e.target.closest('[data-wh-new]')
409
+ if (n) return hookDialog({ coordinator: n.dataset.whNew })
410
+ const m = e.target.closest('[data-wh-menu]')
411
+ if (m) return openMenu(m, Number(m.dataset.whMenu))
412
+ if (currentRoute().view !== 'webhooks') return
413
+ if (e.target.closest('[data-whmore]')) return void loadLog(true)
414
+ const r = e.target.closest('[data-whd]')
415
+ if (r && $('webhooks').contains(r)) return void deliveryDialog(Number(r.dataset.whd))
416
+ })
417
+ document.addEventListener('keydown', e => {
418
+ if (e.key !== 'Enter' || currentRoute().view !== 'webhooks') return
419
+ const r = e.target.closest?.('[data-whd]')
420
+ if (r) void deliveryDialog(Number(r.dataset.whd))
421
+ })
422
+ document.addEventListener('change', e => {
423
+ const f = e.target.closest?.('[data-whfilter]')
424
+ if (!f || currentRoute().view !== 'webhooks') return
425
+ filter[f.dataset.whfilter] = f.value
426
+ renderWebhooks()
427
+ })
package/usage/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createUsage, CAUSES } from './usage.js'
package/usage/usage.js ADDED
@@ -0,0 +1,128 @@
1
+ import { now, bad } from '../platform/index.js'
2
+
3
+ // What the agents spend, in tokens: each session's plugin reports its model
4
+ // calls (observation events of kind "tokens", see plugins/pisha/observe.js),
5
+ // and they are kept added up by the hour, with what each one was spent on:
6
+ // the session, its team and role then, its agent and model, what started the
7
+ // turn (the user, its coordinator, a linked team, the board…) and the board
8
+ // task it was about. Only counts, never what was said.
9
+ export const CAUSES = ['user', 'inbox', 'coordinator', 'worker', 'link', 'board', 'webhook', 'system', 'other', 'self']
10
+ const KINDS = ['input', 'cache_read', 'cache_write', 'output']
11
+ const HOUR = 3600_000
12
+ const DAY = 24 * HOUR
13
+
14
+ export function createUsage(platform, { sessions, boards }) {
15
+ const { db, bus, quota, log } = platform
16
+ db.exec(`
17
+ CREATE TABLE IF NOT EXISTS token_usage (
18
+ hour INTEGER NOT NULL, session TEXT NOT NULL, team TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '',
19
+ agent TEXT NOT NULL DEFAULT 'claude', model TEXT NOT NULL DEFAULT '', cause TEXT NOT NULL DEFAULT 'self',
20
+ task TEXT NOT NULL DEFAULT '', sub INTEGER NOT NULL DEFAULT 0,
21
+ input INTEGER NOT NULL DEFAULT 0, cache_read INTEGER NOT NULL DEFAULT 0, cache_write INTEGER NOT NULL DEFAULT 0,
22
+ output INTEGER NOT NULL DEFAULT 0, calls INTEGER NOT NULL DEFAULT 0,
23
+ PRIMARY KEY (hour, session, team, role, agent, model, cause, task, sub)
24
+ );
25
+ CREATE INDEX IF NOT EXISTS token_usage_hour ON token_usage(hour);
26
+ `)
27
+ const keptMs = () => quota('usage_days', 400) * DAY
28
+
29
+ // Who a session is now: its role, team (a coordinator's own name, a
30
+ // worker's coordinator) and agent. (Until it first logs in, what it was opened as.)
31
+ function whoIs(name) {
32
+ const r = db.prepare('SELECT role, coordinator, agent, opened_role, opened_coordinator, host_id FROM identities WHERE name = ?').get(name)
33
+ if (!r) return { role: '', team: '', agent: 'claude' }
34
+ const role = r.role ?? (r.host_id ? r.opened_role : null) ?? ''
35
+ const team = role === 'coordinator' ? name : role === 'worker' ? (r.role ? r.coordinator : r.opened_coordinator) ?? '' : ''
36
+ return { role, team, agent: r.agent ?? 'claude' }
37
+ }
38
+
39
+ // What started a turn, from the message it began with: its sender as seen
40
+ // from this session (its coordinator, one of its workers, a linked team).
41
+ function causeOf(name, ev) {
42
+ if (ev.cause === 'user' || ev.cause === 'inbox' || ev.cause === 'self') return ev.cause
43
+ if (ev.cause === 'board') return 'board'
44
+ if (ev.cause === 'notice') return 'system'
45
+ if (ev.cause !== 'message' || !Number.isSafeInteger(ev.msg)) return 'other'
46
+ const m = db.prepare('SELECT from_name, target, system FROM messages WHERE id = ?').get(ev.msg)
47
+ if (!m) return 'other'
48
+ if (m.from_name === boards.BOARD_SENDER) return 'board'
49
+ if (m.from_name === 'pisha:webhook') return 'webhook' // (messaging's WEBHOOK_SENDER: this module doesn't see messaging)
50
+ if (m.system) return 'system'
51
+ const me = whoIs(name), them = whoIs(m.from_name)
52
+ if (me.role === 'worker' && me.team === m.from_name) return 'coordinator'
53
+ if (them.role === 'worker' && them.team === name) return 'worker'
54
+ if (me.role === 'coordinator' && them.role === 'coordinator' && sessions.linked(name, m.from_name)) return 'link'
55
+ return 'other'
56
+ }
57
+
58
+ const add = db.prepare(`INSERT INTO token_usage (hour, session, team, role, agent, model, cause, task, sub, input, cache_read, cache_write, output, calls)
59
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
60
+ ON CONFLICT(hour, session, team, role, agent, model, cause, task, sub) DO UPDATE SET
61
+ input = input + excluded.input, cache_read = cache_read + excluded.cache_read, cache_write = cache_write + excluded.cache_write,
62
+ output = output + excluded.output, calls = calls + excluded.calls`)
63
+
64
+ // A batch of model calls from one session (already checked by observation).
65
+ function record(name, list) {
66
+ const who = whoIs(name)
67
+ for (const ev of list) {
68
+ const counts = KINDS.map(k => ev[k] ?? 0)
69
+ if (!counts.some(n => n > 0)) continue
70
+ const task = typeof ev.task === 'string' ? boards.taskIn(ev.task) ?? '' : ''
71
+ try {
72
+ add.run(Math.floor(ev.ts / HOUR) * HOUR, name, who.team, who.role, who.agent, ev.model ?? '', causeOf(name, ev), task, ev.sub ? 1 : 0, ...counts, ev.calls || 1)
73
+ } catch (err) { log(`token usage of "${name}" not kept: ${err.message}`) }
74
+ }
75
+ }
76
+ bus.on('tokens', record)
77
+
78
+ function cleanupUsage() {
79
+ db.prepare('DELETE FROM token_usage WHERE hour < ?').run(now() - keptMs())
80
+ }
81
+
82
+ // --- the dashboard's read ------------------------------------------------------
83
+
84
+ const sum = (a, r) => { for (const k of [...KINDS, 'calls']) a[k] = (a[k] ?? 0) + r[k]; return a }
85
+ const zero = () => ({ input: 0, cache_read: 0, cache_write: 0, output: 0, calls: 0 })
86
+ const DIMENSIONS = ['team', 'session', 'cause', 'task', 'model', 'agent', 'role']
87
+
88
+ // From/to in ms (to excluded), by hour or by day in the viewer's time zone
89
+ // (tz: minutes east of UTC), filtered by team, session, agent or model.
90
+ // Totals, the series, and the totals by each dimension.
91
+ function usage(q) {
92
+ const to = Number(q.get('to')) || now()
93
+ const from = Number(q.get('from')) || to - 7 * DAY
94
+ if (!(from < to) || to - from > 400 * DAY) throw bad('from must be before to, at most 400 days apart')
95
+ const bucket = q.get('bucket') === 'hour' ? 'hour' : 'day'
96
+ const tz = Math.max(-840, Math.min(840, Number(q.get('tz')) || 0)) * 60_000
97
+ const where = ['hour >= ?', 'hour < ?'], args = [Math.floor(from / HOUR) * HOUR, to]
98
+ for (const k of ['team', 'session', 'agent', 'model', 'cause']) {
99
+ const v = q.get(k)
100
+ if (v != null && v !== '') { where.push(`${k} = ?`); args.push(String(v).slice(0, 200)) }
101
+ }
102
+ const rows = db.prepare(`SELECT * FROM token_usage WHERE ${where.join(' AND ')}`).all(...args)
103
+ const totals = zero(), series = new Map(), by = Object.fromEntries(DIMENSIONS.map(d => [d, new Map()]))
104
+ for (const r of rows) {
105
+ sum(totals, r)
106
+ const t = bucket === 'hour' ? r.hour : Math.floor((r.hour + tz) / DAY) * DAY - tz
107
+ sum(series.get(t) ?? series.set(t, zero()).get(t), r)
108
+ for (const d of DIMENSIONS) {
109
+ const key = d === 'session' ? `${r.session}\u0000${r.team}\u0000${r.role}\u0000${r.agent}` : String(r[d] ?? '')
110
+ const m = by[d]
111
+ sum(m.get(key) ?? m.set(key, zero()).get(key), r)
112
+ }
113
+ }
114
+ const total = r => r.input + r.cache_read + r.cache_write + r.output
115
+ const list = (d, m) => [...m].map(([key, v]) => {
116
+ if (d !== 'session') return { [d]: key, ...v }
117
+ const [session, team, role, agent] = key.split('\u0000')
118
+ return { session, team, role, agent, ...v }
119
+ }).sort((a, b) => total(b) - total(a))
120
+ return {
121
+ from, to, bucket, totals,
122
+ series: [...series].sort((a, b) => a[0] - b[0]).map(([t, v]) => ({ t, ...v })),
123
+ by: Object.fromEntries(DIMENSIONS.map(d => [d, list(d, by[d])])),
124
+ }
125
+ }
126
+
127
+ return { usageReads: { usage }, cleanupUsage, record }
128
+ }
@@ -0,0 +1 @@
1
+ export { createWebhooks, signatureOk, stripeSignatureOk, standardSignatureOk, PRESETS, STATUSES } from './webhooks.js'