Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

signals-ui.ts

284 lines · 14.2 KB · TypeScript
/**
 * Server-rendered Signal pages: Sources (CRUD) and Inbox (list + explain).
 * Pure (no kody:runtime). Every action is a plain form POST that redirects
 * back with a result. Pages work without JavaScript.
 */
import { esc, icon, renderShell } from './ui.ts'
import type { SourceRecord } from '../signals/sources/types.ts'
import type { SignalRecord } from '../signals/records/types.ts'
import type { RoutingConfig } from '../signals/routing/types.ts'

const TZ = 'America/Denver'
const BAD_FLASH = /^(error|invalid|unknown|could not|failed)/i

function fmtTime(iso: string | null | undefined): string {
	const t = iso ? Date.parse(iso) : Number.NaN
	if (!Number.isFinite(t)) return 'never'
	return new Intl.DateTimeFormat('en-US', { timeZone: TZ, month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }).format(new Date(t))
}

function ago(now: number, iso: string | null | undefined): string {
	const t = iso ? Date.parse(iso) : Number.NaN
	if (!Number.isFinite(t)) return 'never'
	const ms = now - t
	if (ms < 60_000) return 'just now'
	if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ago`
	if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h ago`
	return `${Math.floor(ms / 86_400_000)}d ago`
}

function when(now: number, iso: string | null | undefined): string {
	return iso ? `<time datetime="${esc(iso)}" title="${esc(fmtTime(iso))}">${esc(ago(now, iso))}</time>` : 'never'
}

function flashHtml(flash?: string): string {
	return flash ? `<div class="flash${BAD_FLASH.test(flash) ? ' bad' : ''}" role="status">${esc(flash)}</div>` : ''
}

function postForm(bp: string, fields: Record<string, string>, label: string, opts: { cls?: string; confirm?: string; disabled?: boolean } = {}): string {
	const hidden = Object.entries(fields)
		.map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}"/>`)
		.join('')
	return `<form class="inline" method="post" action="${bp}/signals"${opts.confirm ? ` data-confirm="${esc(opts.confirm)}"` : ''}>${hidden}<button type="submit" class="${opts.cls ?? 'btn small'}"${opts.disabled ? ' disabled' : ''}>${esc(label)}</button></form>`
}

const STATUS_LABEL: Record<string, [string, string]> = {
	received: ['Received', 'st-intake'],
	routed: ['Routed', 'st-triaged'],
	dispatched: ['Dispatched', 'st-shipped'],
	failed: ['Failed', 'lvl-bad'],
	rejected: ['Rejected', 'st-dropped'],
}

function statusChip(status: string): string {
	const [label, cls] = STATUS_LABEL[status] ?? [status, 'off']
	return `<span class="chip ${cls}">${esc(label)}</span>`
}

const KIND_LABEL: Record<string, string> = {
	'generic-webhook': 'Generic webhook',
	'github-issues': 'GitHub issues',
	'github-ci': 'GitHub CI',
	sentry: 'Sentry',
	discord: 'Discord',
	friction: 'Friction',
	email: 'Email',
	x: 'X',
	manual: 'Manual',
}

function sourceRow(bp: string, s: SourceRecord): string {
	const inboundUrl = `${bp}/signals/in/${esc(s.id)}`
	return `<li class="frow"><div class="frow-main"><a class="row-title" href="${bp}/signals/sources/${esc(s.id)}">${esc(s.name)}</a>
<div class="row-meta"><span>${esc(KIND_LABEL[s.kind] ?? s.kind)}</span><span>Scope: ${s.projectScope.length ? esc(s.projectScope.join(', ')) : 'all projects'}</span><span>Created ${esc(fmtTime(s.createdAt))}</span></div>
<code class="small muted">${esc(inboundUrl)}</code>
</div><span class="chip ${s.enabled ? 'on' : 'off'}">${s.enabled ? 'Active' : 'Disabled'}</span></li>`
}

export type SourcesPageOptions = {
	basePath: string
	sources: SourceRecord[]
	flash?: string
}

export function renderSourcesPage(opts: SourcesPageOptions): string {
	const bp = esc(opts.basePath)
	const list = opts.sources.length
		? `<ul class="list flist">${opts.sources.map((s) => sourceRow(bp, s)).join('')}</ul>`
		: `<div class="card empty"><div class="bubble">${icon('inbox')}</div><p>No signal sources yet. Create one to start receiving signals.</p></div>`
	const main = `
<header class="page-head"><div><h1>Signal sources</h1><p>Manage inbound signal feeds. Each source gets an endpoint, a signing key, and routing rules.</p></div></header>
${flashHtml(opts.flash)}
<section class="card stack" aria-labelledby="new-h">
 <div class="card-head"><h2 id="new-h">Create a source</h2></div>
 <form method="post" action="${bp}/signals" class="form-grid">
  <input type="hidden" name="action" value="create-source"/>
  <label class="field"><span>ID</span><input name="id" required pattern="[a-z][a-z0-9_-]{1,62}" placeholder="my-sentry" autocomplete="off"/><small class="muted">Lowercase slug, used in the inbound URL</small></label>
  <label class="field"><span>Name</span><input name="name" required placeholder="My Sentry alerts" autocomplete="off"/></label>
  <label class="field"><span>Kind</span><select name="kind">${Object.entries(KIND_LABEL).map(([k, v]) => `<option value="${esc(k)}">${esc(v)}</option>`).join('')}</select></label>
  <label class="field"><span>Project scope</span><input name="projectScope" placeholder="kody, epicweb" autocomplete="off"/><small class="muted">Comma-separated project ids (empty = all projects)</small></label>
  <label class="field"><span>Note</span><input name="note" placeholder="What this source sends" autocomplete="off"/></label>
  <div class="row-btns"><button type="submit" class="btn primary">Create source</button></div>
 </form>
</section>
<section aria-labelledby="src-h" class="stack"><h2 id="src-h">Sources</h2>${list}</section>`
	return renderShell({ basePath: opts.basePath, view: 'signals' as never, title: 'Signal sources', main })
}

export type SourceDetailOptions = {
	basePath: string
	source: SourceRecord
	recordCount: number
	routingConfig: RoutingConfig
	flash?: string
}

export function renderSourceDetail(opts: SourceDetailOptions): string {
	const bp = esc(opts.basePath)
	const s = opts.source
	const rc = opts.routingConfig
	const inboundUrl = `${bp}/signals/in/${esc(s.id)}`
	const criteriaRows = Object.entries(rc.criteria)
		.map(([key, m]) => `<li><div><b>${esc(key)}</b><span class="d">${esc(m.label)} &#8594; ${esc(m.destination)}</span></div></li>`)
		.join('')
	const main = `
<header class="page-head">
 <div>
  <nav class="breadcrumb"><a href="${bp}/signals/sources">Sources</a> / ${esc(s.name)}</nav>
  <h1>${esc(s.name)}</h1>
  <p>${esc(s.note || 'No description')}</p>
 </div>
</header>
${flashHtml(opts.flash)}
<div class="grid2">
 <section class="card" aria-labelledby="info-h"><div class="card-head"><h2 id="info-h">Source details</h2></div>
  <ul class="kv">
   <li><div><b>ID</b></div><code>${esc(s.id)}</code></li>
   <li><div><b>Kind</b></div><span>${esc(KIND_LABEL[s.kind] ?? s.kind)}</span></li>
   <li><div><b>Inbound URL</b></div><code class="small">${esc(inboundUrl)}</code></li>
   <li><div><b>Signing header</b></div><code>${esc(s.signingHeader)}</code></li>
   <li><div><b>Project scope</b></div><span>${s.projectScope.length ? esc(s.projectScope.join(', ')) : 'All projects'}</span></li>
   <li><div><b>Signals received</b></div><span>${opts.recordCount}</span></li>
   <li><div><b>Status</b></div><span class="chip ${s.enabled ? 'on' : 'off'}">${s.enabled ? 'Active' : 'Disabled'}</span></li>
  </ul>
  <div class="row-btns" style="margin-top:12px">
   ${postForm(bp, { action: s.enabled ? 'disable-source' : 'enable-source', id: s.id }, s.enabled ? 'Disable' : 'Enable')}
   ${postForm(bp, { action: 'delete-source', id: s.id, confirmId: s.id }, 'Delete', { cls: 'btn small danger', confirm: `Delete source "${s.name}"? This cannot be undone.` })}
  </div>
 </section>
 <section class="card" aria-labelledby="route-h"><div class="card-head"><h2 id="route-h">Routing rules</h2></div>
  <p class="small muted" style="margin-bottom:8px">Confidence threshold: ${rc.confidenceThreshold.toFixed(2)}</p>
  <ul class="kv">${criteriaRows || '<li class="muted">No criteria configured</li>'}</ul>
 </section>
</div>`
	return renderShell({ basePath: opts.basePath, view: 'signals' as never, title: s.name, main })
}

function signalRow(bp: string, r: SignalRecord, now: number): string {
	return `<li class="frow"><div class="frow-main"><a class="row-title" href="${bp}/signals/inbox/${esc(r.id)}">${esc(r.title ?? 'Signal')}</a>
<div class="row-meta"><span>${esc(r.sourceId)}</span>${r.projectId ? `<span>${esc(r.projectId)}</span>` : ''}<span>${when(now, r.receivedAt)}</span>${r.routingDecision ? `<span>&#8594; ${esc(r.routingDecision.destination)}</span>` : ''}</div>
</div><div class="chip-row">${r.verified ? '' : '<span class="chip lvl-bad">Unverified</span>'}${statusChip(r.status)}</div></li>`
}

export type InboxPageOptions = {
	basePath: string
	records: SignalRecord[]
	sourceFilter: string
	statusFilter: string
	projectFilter: string
	total: number
	flash?: string
}

export function renderInboxPage(opts: InboxPageOptions): string {
	const bp = esc(opts.basePath)
	const now = Date.now()
	const list = opts.records.length
		? `<ul class="list flist">${opts.records.map((r) => signalRow(bp, r, now)).join('')}</ul>`
		: `<div class="card empty"><div class="bubble">${icon('inbox')}</div><p>No signals yet. Configure a source and send a test payload.</p></div>`

	const statusTabs = ['', 'received', 'routed', 'dispatched', 'failed', 'rejected']
		.map((s) => {
			const label = s || 'All'
			const params = new URLSearchParams()
			if (s) params.set('status', s)
			if (opts.sourceFilter) params.set('source', opts.sourceFilter)
			if (opts.projectFilter) params.set('project', opts.projectFilter)
			const qs = params.toString()
			const active = s === opts.statusFilter
			return `<a href="${bp}/signals/inbox${qs ? `?${qs}` : ''}"${active ? ' aria-current="true"' : ''}>${esc(label)}</a>`
		})
		.join('')

	const main = `
<header class="page-head"><div><h1>Signal inbox</h1><p>Every inbound signal with its routing decision and destination result.</p></div></header>
${flashHtml(opts.flash)}
<section aria-labelledby="inbox-h" class="stack">
 <form class="toolbar" method="get" action="${bp}/signals/inbox" role="search">
  <label class="search"><span class="sr">Filter by source</span>${icon('search')}<input type="text" name="source" value="${esc(opts.sourceFilter)}" placeholder="Source id" autocomplete="off"/></label>
  <label class="search"><span class="sr">Filter by project</span><input type="text" name="project" value="${esc(opts.projectFilter)}" placeholder="Project id" autocomplete="off"/></label>
  <button type="submit" class="btn">Filter</button>
  <nav class="tabs" aria-label="Filter by status">${statusTabs}</nav>
 </form>
 <p class="muted small" role="status">${opts.records.length} of ${opts.total} signals shown</p>
 ${list}
</section>`
	return renderShell({ basePath: opts.basePath, view: 'signals' as never, title: 'Signal inbox', main })
}

export type SignalDetailOptions = {
	basePath: string
	record: SignalRecord
	flash?: string
}

export function renderSignalDetail(opts: SignalDetailOptions): string {
	const bp = esc(opts.basePath)
	const r = opts.record
	const now = Date.now()
	const routing = r.routingDecision
	const destResults = r.destinationResults

	const routingRows = routing
		? `<ul class="kv">
		<li><div><b>Destination</b></div><span class="chip">${esc(routing.destination)}</span></li>
		<li><div><b>Confidence</b></div><span>${routing.confidence.toFixed(2)}</span></li>
		<li><div><b>Model</b></div><span>${esc(routing.modelUsed ?? 'none')}</span></li>
		<li><div><b>Escalated</b></div><span>${routing.escalated ? 'Yes (flash -> full)' : 'No'}</span></li>
		<li><div><b>Reason</b></div><span class="small">${esc(routing.reason)}</span></li>
		<li><div><b>Labels</b></div><span>${routing.labels.map((l) => `<span class="chip">${esc(l)}</span>`).join(' ')}</span></li>
		</ul>`
		: '<p class="muted">No routing decision recorded</p>'

	const destRows = destResults.length
		? `<ul class="kv">${destResults.map((d) => `<li><div><b>${esc(d.destination)}</b><span class="d">${esc(d.detail)}</span></div><span class="chip ${d.ok ? 'on' : 'lvl-bad'}">${d.ok ? 'OK' : 'Failed'}</span></li>`).join('')}</ul>`
		: '<p class="muted">No destination results</p>'

	const main = `
<header class="page-head">
 <div>
  <nav class="breadcrumb"><a href="${bp}/signals/inbox">Inbox</a> / ${esc(r.id)}</nav>
  <h1>${esc(r.title ?? 'Signal')}</h1>
 </div>
</header>
${flashHtml(opts.flash)}
<div class="grid2">
 <section class="card" aria-labelledby="meta-h"><div class="card-head"><h2 id="meta-h">Signal</h2></div>
  <ul class="kv">
   <li><div><b>ID</b></div><code>${esc(r.id)}</code></li>
   <li><div><b>Source</b></div><a href="${bp}/signals/sources/${esc(r.sourceId)}">${esc(r.sourceId)}</a></li>
   <li><div><b>Project</b></div><span>${esc(r.projectId ?? 'unknown')}</span></li>
   <li><div><b>Received</b></div>${when(now, r.receivedAt)}</li>
   <li><div><b>Verified</b></div><span class="chip ${r.verified ? 'on' : 'lvl-bad'}">${r.verified ? 'Yes' : 'No'}</span></li>
   <li><div><b>Status</b></div>${statusChip(r.status)}</li>
   <li><div><b>Payload digest</b></div><code class="small">${esc(r.payloadDigest.slice(0, 16))}...</code></li>
   ${r.error ? `<li><div><b>Error</b></div><span class="small">${esc(r.error)}</span></li>` : ''}
  </ul>
  <div class="row-btns" style="margin-top:12px">
   ${postForm(bp, { action: 'replay', signalId: r.id }, 'Replay (dry run)', { confirm: 'Re-run routing for this signal in dry-run mode?' })}
  </div>
 </section>
 <section class="card stack" aria-labelledby="routing-h"><div class="card-head"><h2 id="routing-h">Routing decision</h2></div>${routingRows}</section>
</div>
<section class="card stack" aria-labelledby="dest-h"><div class="card-head"><h2 id="dest-h">Destination results</h2></div>${destRows}</section>
<details class="card stack"><summary class="card-head"><h2>Redacted payload</h2></summary><pre class="payload-pre"><code>${esc(r.redactedPayload)}</code></pre></details>`
	return renderShell({ basePath: opts.basePath, view: 'signals' as never, title: r.title ?? 'Signal', main })
}

export function renderSourceMissing(basePath: string): string {
	return renderShell({
		basePath,
		view: 'signals' as never,
		title: 'Source not found',
		main: `<header class="page-head"><h1>Source not found</h1></header><p><a href="${esc(basePath)}/signals/sources">Back to sources</a></p>`,
	})
}

export function renderSignalMissing(basePath: string): string {
	return renderShell({
		basePath,
		view: 'signals' as never,
		title: 'Signal not found',
		main: `<header class="page-head"><h1>Signal not found</h1></header><p><a href="${esc(basePath)}/signals/inbox">Back to inbox</a></p>`,
	})
}