/** * 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 ? `` : 'never' } function flashHtml(flash?: string): string { return flash ? `
${esc(flash)}
` : '' } function postForm(bp: string, fields: Record, label: string, opts: { cls?: string; confirm?: string; disabled?: boolean } = {}): string { const hidden = Object.entries(fields) .map(([k, v]) => ``) .join('') return `
${hidden}
` } const STATUS_LABEL: Record = { 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 `${esc(label)}` } const KIND_LABEL: Record = { '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 `
  • ${esc(s.name)}
    ${esc(KIND_LABEL[s.kind] ?? s.kind)}Scope: ${s.projectScope.length ? esc(s.projectScope.join(', ')) : 'all projects'}Created ${esc(fmtTime(s.createdAt))}
    ${esc(inboundUrl)}
    ${s.enabled ? 'Active' : 'Disabled'}
  • ` } 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 ? `
      ${opts.sources.map((s) => sourceRow(bp, s)).join('')}
    ` : `
    ${icon('inbox')}

    No signal sources yet. Create one to start receiving signals.

    ` const main = `

    Signal sources

    Manage inbound signal feeds. Each source gets an endpoint, a signing key, and routing rules.

    ${flashHtml(opts.flash)}

    Create a source

    Sources

    ${list}
    ` 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]) => `
  • ${esc(key)}${esc(m.label)} → ${esc(m.destination)}
  • `) .join('') const main = `

    ${esc(s.name)}

    ${esc(s.note || 'No description')}

    ${flashHtml(opts.flash)}

    Source details

    • ID
      ${esc(s.id)}
    • Kind
      ${esc(KIND_LABEL[s.kind] ?? s.kind)}
    • Inbound URL
      ${esc(inboundUrl)}
    • Signing header
      ${esc(s.signingHeader)}
    • Project scope
      ${s.projectScope.length ? esc(s.projectScope.join(', ')) : 'All projects'}
    • Signals received
      ${opts.recordCount}
    • Status
      ${s.enabled ? 'Active' : 'Disabled'}
    ${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.` })}

    Routing rules

    Confidence threshold: ${rc.confidenceThreshold.toFixed(2)}

      ${criteriaRows || '
    • No criteria configured
    • '}
    ` return renderShell({ basePath: opts.basePath, view: 'signals' as never, title: s.name, main }) } function signalRow(bp: string, r: SignalRecord, now: number): string { return `
  • ${esc(r.title ?? 'Signal')}
    ${esc(r.sourceId)}${r.projectId ? `${esc(r.projectId)}` : ''}${when(now, r.receivedAt)}${r.routingDecision ? `→ ${esc(r.routingDecision.destination)}` : ''}
    ${r.verified ? '' : 'Unverified'}${statusChip(r.status)}
  • ` } 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 ? `
      ${opts.records.map((r) => signalRow(bp, r, now)).join('')}
    ` : `
    ${icon('inbox')}

    No signals yet. Configure a source and send a test payload.

    ` 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 `${esc(label)}` }) .join('') const main = `

    Signal inbox

    Every inbound signal with its routing decision and destination result.

    ${flashHtml(opts.flash)}

    ${opts.records.length} of ${opts.total} signals shown

    ${list}
    ` 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 ? `
    • Destination
      ${esc(routing.destination)}
    • Confidence
      ${routing.confidence.toFixed(2)}
    • Model
      ${esc(routing.modelUsed ?? 'none')}
    • Escalated
      ${routing.escalated ? 'Yes (flash -> full)' : 'No'}
    • Reason
      ${esc(routing.reason)}
    • Labels
      ${routing.labels.map((l) => `${esc(l)}`).join(' ')}
    ` : '

    No routing decision recorded

    ' const destRows = destResults.length ? `
      ${destResults.map((d) => `
    • ${esc(d.destination)}${esc(d.detail)}
      ${d.ok ? 'OK' : 'Failed'}
    • `).join('')}
    ` : '

    No destination results

    ' const main = `

    ${esc(r.title ?? 'Signal')}

    ${flashHtml(opts.flash)}

    Signal

    • ID
      ${esc(r.id)}
    • Source
      ${esc(r.sourceId)}
    • Project
      ${esc(r.projectId ?? 'unknown')}
    • Received
      ${when(now, r.receivedAt)}
    • Verified
      ${r.verified ? 'Yes' : 'No'}
    • Status
      ${statusChip(r.status)}
    • Payload digest
      ${esc(r.payloadDigest.slice(0, 16))}...
    • ${r.error ? `
    • Error
      ${esc(r.error)}
    • ` : ''}
    ${postForm(bp, { action: 'replay', signalId: r.id }, 'Replay (dry run)', { confirm: 'Re-run routing for this signal in dry-run mode?' })}

    Routing decision

    ${routingRows}

    Destination results

    ${destRows}

    Redacted payload

    ${esc(r.redactedPayload)}
    ` 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: `

    Source not found

    Back to sources

    `, }) } export function renderSignalMissing(basePath: string): string { return renderShell({ basePath, view: 'signals' as never, title: 'Signal not found', main: `

    Signal not found

    Back to inbox

    `, }) }