// `/admin`: the installation owner's page for the people they invited. Each owner's model budget
// (what their agents' calls on the service's model keys may cost, in US dollars), with forms to add
// credit, set the budget, or lift it; and a form for a new invite. Plain forms, no script.
//
// Only the installation owner ever sees it: the server answers everyone else with the not-found page.
import QRCode from 'qrcode'
import { FUNNEL_SINCE, type FunnelEvent, type FunnelRow, type FunnelTime } from './funnel.ts'
import { messageBody } from './inbox-page.ts'
import { MESSAGE_LIMITS, type InboxMessage } from './messages.ts'
import { KINDS, LEVELS, RETENTION_DAYS, type OpsEvent } from './ops.ts'
import type { CreditGrant } from './billing.ts'
import type { FeedbackItem } from './telemetry.ts'
import type { UsageSummary } from './usage.ts'
import type { Visit } from './visits.ts'
import { esc, page, type Page } from './web.ts'
/** A QR code of `url`: SVG markup to show on the page, and a 1024px PNG as a data URL to download. */
export async function inviteQr(url: string) {
const svg = await QRCode.toString(url, { type: 'svg', margin: 2, errorCorrectionLevel: 'M' })
const png = await QRCode.toDataURL(url, { width: 1024, margin: 2, errorCorrectionLevel: 'M' })
return { svg, png }
}
export interface AdminOwner {
did: string
handle: string
createdAt: string
budgetUsd?: number
spentUsd: number
/** What those calls cost at the provider; spentUsd less this is Languid's margin. */
providerCostUsd?: number
agents: { name: string; handle: string }[]
/** Their cloud sandbox and volume: paid (through Stripe), given (by the installation owner), or none. */
sandbox?: 'paid' | 'given'
volume?: 'paid' | 'given'
}
export interface AdminView {
/** Cloud sandboxes are offered, so they can be given. */
sandboxes?: boolean
owners: AdminOwner[]
openInvites: number
notice?: { text: string; error?: boolean }
/** A new invite's sign-up link, shown once, right after it's made. */
invite?: { url: string; expiresAt: string; budgetUsd?: number; uses?: number; qr?: { svg: string; png: string } }
/** A new Test onboarding link, shown once. */
testLink?: string
/** How many test owners there are (left out of `owners` and the funnel). */
tests?: number
/** How far each owner got, newest sign-up first. Undefined when the funnel couldn't be read. */
funnel?: FunnelRow[]
/** Sign-ups that failed before an account was made, newest first. */
failedSignups?: FunnelEvent[]
/** The funnel's cohort (a key of COHORTS); empty for all owners. */
cohort?: string
}
/** A short UTC date and time. */
const short = (at: string) => `${esc(at.replace('T', ' ').slice(5, 16))}`
/** When, as a short UTC date and time; `before`: done before the funnel was recorded. */
const when = (at?: string) => (!at ? '·' : at === 'before' ? '✓' : short(at))
/** A step's cell: when, or that nothing could have recorded it, or (a dot) not reached. */
function stepCell(r: FunnelRow, k: FunnelTime): string {
const at = r[k]
if (!at && r.unrecorded?.includes(k)) return 'not recorded'
if (k === 'signedIn' && at && r.signedInDerived) return `${short(at)} derived`
if (k === 'onboardingOpened' && at && r.screens?.length) return `${when(at)}
${r.screens.map(esc).join(', ')}`
return when(at)
}
const failureCell = (f?: { at: string; detail?: string }) => (f ? `${short(f.at)} ${esc(f.detail ?? '')}` : '')
/** Cohorts the funnel can be cut to: everyone, or owners who signed up since a day. */
export const COHORTS: { key: string; label: string; days?: number; since?: string }[] = [
{ key: '', label: 'All owners' },
{ key: '7d', label: 'Last 7 days', days: 7 },
{ key: '30d', label: 'Last 30 days', days: 30 },
{ key: 'recorded', label: 'Since the funnel began', since: FUNNEL_SINCE },
]
/** The first sign-up time a cohort includes, if it's cut. */
export function cohortSince(key: string | undefined, now = Date.now()): string | undefined {
const c = COHORTS.find((x) => x.key === key)
if (!c) return undefined
return c.since ?? (c.days ? new Date(now - c.days * 86400_000).toISOString() : undefined)
}
/** The funnel: how many owners reached each step, then one row per owner, then failed sign-ups. */
function funnelSection(all: FunnelRow[], cohort = '', failed: FunnelEvent[] = []): string {
const since = cohortSince(cohort)
const rows = since ? all.filter((r) => (r.signedUp ?? '') >= since) : all
const steps: [FunnelTime, string][] = [
['signedUp', 'Signed up'],
['signInStarted', 'Went to sign in'],
['signedIn', 'Signed in'],
['onboardingOpened', 'Saw onboarding'],
['onboarded', 'Onboarded'],
['firstAgentFormOpened', 'Saw agent form'],
['firstAgent', 'Agent'],
['firstChat', 'Chatted'],
]
const label = COHORTS.find((c) => c.key === cohort)?.label ?? 'All owners'
const cohorts =
`
Cohort ` + COHORTS.map((c) => (c.key === cohort ? `${esc(c.label)}` : `${esc(c.label)}`)).join(' ') + '
' const counts = steps .map(([k, l]) => { const n = rows.filter((r) => r[k]).length const unknown = rows.filter((r) => !r[k] && r.unrecorded?.includes(k)).length return `| When | Handle asked for | Why |
|---|---|---|
| ${short(e.createdAt)} | ${esc(e.handle ?? '')} | ${esc(e.detail ?? '')} |
How far each owner got (UTC). Recording began Nov 19 19:38; “not recorded” marks steps an owner who signed up earlier may have reached unseen, a dot a step not reached.
` + cohorts + `${esc(label)}: ${rows.length} owner${rows.length === 1 ? '' : 's'}
` + `| Owner | ${steps.map(([, l]) => `${l} | `).join('')}Last seen | Last failures |
|---|
${esc(v.notice.text)}
` : '' const invite = v.invite ? `New invite (${v.invite.budgetUsd === undefined ? 'unlimited' : `${money(v.invite.budgetUsd)} budget`}, ` + `expires ${esc(v.invite.expiresAt.slice(0, 10))}). Shown once, works ${(v.invite.uses ?? 1) > 1 ? `for ${v.invite.uses} people` : 'once'}:
${esc(v.invite.url)}
| Owner | Agents | Spent | Budget | ${v.sandboxes ? 'Cloud | ' : ''}Change |
|---|
No one has signed up yet.
` return page( 200, 'Admin · Languid', ADMIN_CSS + `Control room · Logs · Feedback · Messages
` + `Invited owners and their spend on the service's model keys. Their own ChatGPT or Anthropic keys don't count.
` + notice + invite + (v.testLink ? `Test sign-up link, works once for a day. Open it in a private window so you stay signed in here:
${esc(v.testLink)}
The funnel couldn't be read from the PDS just now.
`) + `${v.openInvites} sign-up${v.openInvites === 1 ? '' : 's'} left on open invites.
` + `Sign up as a brand-new person with a throwaway account. Test accounts have a $5 budget and stay out of the owner list and the funnel.
` + `` + (v.tests ? `` : ''), { path: '/admin', app: true }, ) } export interface AdminOwnerView { did: string handle: string createdAt?: string lastSeenAt?: string budgetUsd?: number spentUsd: number providerCostUsd?: number /** Their agents, by name only. */ agents: string[] /** Their funnel steps, oldest first. */ funnel: FunnelEvent[] /** Ops events whose subject is their DID or one of their agents, newest first. */ events: OpsEvent[] /** The ops space couldn't be read; events are this process's only. */ fromMemory?: boolean /** Their sessions still kept: kind and when only. */ sessions: { kind: string; createdAt: string }[] /** Model spend over the last 30 days. */ usage: UsageSummary grants: CreditGrant[] /** They share usage (Share usage with Languid); visits and browser errors are kept only then. */ sharing: boolean /** Their daily visits, newest day first; undefined when they couldn't be read. */ visits?: Visit[] } /** Ops events as /admin/logs shows them. */ function eventRows(events: OpsEvent[]): string { const at = (s: string) => `${esc(s.replace('T', ' ').slice(5, 19))}` return ( `| When (UTC) | Level | Kind | What |
|---|---|---|---|
| ${at(e.createdAt)}${e.count && e.count > 1 ? ` ×${e.count}, last ${at(e.lastAt ?? e.createdAt)}` : ''} | ` +
`${esc(e.level)} | ${esc(e.kind)} | ` + `${e.name ? `${esc(e.name)} ` : ''}${esc(e.message)}` +
`${e.subject || e.method ? `${[e.subject, e.method].filter(Boolean).map((x) => esc(x!)).join(' · ')}` : ''}` + `${e.version ? ` ${esc(e.version.slice(0, 7))}` : ''}` + `${e.stack ? ` Stack${esc(e.stack)}Output and note${esc(e.detail)} |
No steps recorded.
` const sessions = v.sessions.length ? `None kept.
` const t = v.usage.total const usedDays = v.usage.days.filter((d) => d.totals.calls) const usage = t.calls ? `${t.calls} call${t.calls === 1 ? '' : 's'}, ${money(t.charged)} charged (${money(t.cost)} at cost) in the last 30 days.
` + `| By agent | Calls | Charged |
|---|---|---|
| ${esc(a.name)} | ${a.totals.calls} | ${money(a.totals.charged)} |
| By model | Calls | Charged |
|---|---|---|
| ${esc(a.name)} | ${a.totals.calls} | ${money(a.totals.charged)} |
| Day | Calls | Charged |
|---|---|---|
| ${esc(d.day)} | ${d.totals.calls} | ${money(d.totals.charged)} |
No model calls in the last 30 days.
` const grants = v.grants.length ? `None.
` const client = v.events.filter((e) => e.kind === 'client') const others = v.events.filter((e) => e.kind !== 'client') const events = others.length ? eventRows(others.slice(0, 200)) : `No ops events about them or their agents.
` const off = v.sharing ? '' : `They don't share usage, so nothing new is kept here.
` const visits = v.visits === undefined ? `Visits couldn't be read just now.
` : v.visits.length ? `| Day (UTC) | Pages | First – last | Top pages |
|---|---|---|---|
| ${esc(d.day)} | ${d.count} | ${esc(d.firstAt.slice(11, 16))} – ${esc(d.lastAt.slice(11, 16))} | ` + `${Object.entries(d.routes).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([r, n]) => `${esc(r)} ${n}`).join(', ')} |
No visits recorded.
` const errors = client.length ? eventRows(client.slice(0, 100)) : `No browser errors.
` return page( 200, `${v.handle} · Admin · Languid`, ADMIN_CSS + '' + `From the ops space and the service's records of this owner. Nothing here is read from their agents' spaces.
` + facts + `Daily run counts aren't in the ops space yet.
` + `The ops space couldn't be read; these are only what this process saw since it started.
` : '') + events, { path: '/admin', app: true }, ) } export interface AdminLogsView { events: OpsEvent[] /** The PDS couldn't be read: these are only what this process saw since it started. */ fromMemory: boolean level?: string kind?: string } /** `/admin/logs`: the service's ops events (src/ops.ts), newest first, filtered by level and kind. */ export function adminLogsPage(v: AdminLogsView): Page { const shown = v.events.filter((e) => (!v.level || e.level === v.level) && (!v.kind || e.kind === v.kind)).slice(0, 500) const link = (level?: string, kind?: string) => { const q = new URLSearchParams({ ...(level ? { level } : {}), ...(kind ? { kind } : {}) }).toString() return `/admin/logs${q ? `?${q}` : ''}` } const filter = (label: string, values: readonly string[], current: string | undefined, href: (x?: string) => string) => `${label} ` + [undefined, ...values].map((x) => (x === current ? `${x ?? 'all'}` : `${x ?? 'all'}`)).join(' ') + '
' const at = (s: string) => `${esc(s.replace('T', ' ').slice(5, 19))}` const rows = shown.length ? `| When (UTC) | Level | Kind | What |
|---|---|---|---|
| ${at(e.createdAt)}${e.count && e.count > 1 ? ` ×${e.count}, last ${at(e.lastAt ?? e.createdAt)}` : ''} | ` +
`${esc(e.level)} | ${esc(e.kind)} | ` + `${e.name ? `${esc(e.name)} ` : ''}${esc(e.message)}` +
`${e.subject || e.method ? `${[e.subject, e.method].filter(Boolean).map((x) => esc(x!)).join(' · ')}` : ''}` + `${e.version ? ` ${esc(e.version.slice(0, 7))}` : ''}` + `${e.stack ? ` Stack${esc(e.stack)}Output and note${esc(e.detail)} |
Nothing logged${v.level || v.kind ? ' with these filters' : ''}.
` return page( 200, 'Logs · Languid', ADMIN_CSS + '' + `The service's errors and lifecycle, kept in the ops space for ${RETENTION_DAYS} days. Live output: fly logs -a languid-nimbus. Agents' own error reports are on Error reports. Problems people report from their computers (the Windows installer, setup, languid report) are kind report.
The ops space couldn't be read; these are only what this process saw since it started.
` : '') + filter('Level', LEVELS, v.level, (x) => link(x, v.kind)) + filter('Kind', KINDS, v.kind, (x) => link(v.level, x)) + rows, { path: '/admin', app: true }, ) } export interface AdminFeedbackView { /** Newest first, from every agent whose owner shares it. */ feedback: (OmitKind ` + [undefined, ...kinds].map((x) => (x === v.kind ? `${x ?? 'all'}` : `${x ?? 'all'}`)).join(' ') + '
' + 'Triage ' + [undefined, 'open', 'resolved'].map((x) => x === v.status ? `${x ?? 'all'}` : `${x ?? 'all'}`).join(' ') + '
' + 'Reply ' + [false, true].map((o) => (o === !!v.open ? `${o ? 'open only' : 'any'}` : `${o ? 'open only' : 'any'}`)).join(' ') + '
' const status = (f: Pick| When (UTC) | Kind | Agent | Feedback | Reply |
|---|---|---|---|---|
| ${esc(f.createdAt.replace('T', ' ').slice(5, 16))} | ${esc(f.kind)} | ${esc(f.handle)}${f.agent ? ` ${esc(f.agent)} · ${esc(f.rkey ?? '')}` : ''} | ` +
`${esc(f.text)} ` +
(f.uri ? `${esc(f.triage?.status ?? 'open')} · TriageReference: CID: | ` +
`${status(f)} |
No ${v.open ? 'unanswered ' : ''}feedback${v.kind || v.status ? ' matching this filter' : ''} yet.
` return page( 200, 'Feedback · Languid', ADMIN_CSS + '' + `${esc(v.notice.text)}
` : '') + 'Triage notes are private to the maintainer, and resolving does not send a message. To answer an agent, run languid feedback reply; it hears back on its next turn.
From ${v.sharing} agent${v.sharing === 1 ? '' : 's'} whose owners share with ${esc(v.destination)}. ${v.notSharing} don't share yet. Error reports are on Error reports.
` + filter + rows, { path: '/admin', app: true }, ) } export interface AdminMessagesView { messages: InboxMessage[] /** Owners who dismissed each message, by its key. */ dismissed: Map${esc(v.notice.text)}
` : '' const options = [``, ...v.owners.map((o) => ``)].join('') const sent = v.messages.length ? `Nothing sent yet.
` return page( 200, 'Messages · Admin · Languid', ADMIN_CSS + '' + `Messages show in owners’ Inbox${v.from ? ` from ${esc(v.from)}` : ''} until they dismiss them. A message to everyone reaches the owners who have signed up by the time you send it. Blank lines start paragraphs, and web addresses become links.
` + notice + `` + `