// `/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 `
  • ${n} ${l.toLowerCase()}${unknown ? ` (${unknown} not recorded)` : ''}
  • ` }) .join('') const body = rows .map( (r) => `${esc(r.handle)}${steps.map(([k]) => `${stepCell(r, k)}`).join('')}` + `${r.lastSeenAt ? short(r.lastSeenAt) : '·'}` + `${[['Sign-in', r.lastFailure], ['Agent', r.lastAgentFailure], ['Chat', r.lastChatFailure]].filter(([, f]) => f).map(([l, f]) => `
    ${l} ${failureCell(f as { at: string; detail?: string })}
    `).join('')}`, ) .join('') const signups = failed.length ? `

    Failed sign-ups

    ` + failed.slice(0, 50).map((e) => ``).join('') + `
    WhenHandle asked forWhy
    ${short(e.createdAt)}${esc(e.handle ?? '')}${esc(e.detail ?? '')}
    ` : '' return ( `

    Funnel

    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'}

    ` + `` + `
    ${steps.map(([, l]) => ``).join('')}${body}
    Owner${l}Last seenLast failures
    ` + signups ) } export const ADMIN_CSS = '' const money = (n: number) => `$${n.toFixed(2)}` /** The invite's QR code, big enough to project, with both files to download. Nothing is saved: the link is the invite. */ const qrFigure = (qr: { svg: string; png: string }) => `
    ${qr.svg}` + `

    Download PNGDownload SVG

    ` const hidden = (name: string, value: string) => `` function plans(o: AdminOwner, form: (action: string, body: string) => string): string { const one = (plan: 'sandbox' | 'volume', label: string) => { const s = o[plan] if (s === 'paid') return `
    ${label}: paid
    ` if (s === 'given') return form('take', `${label}: given `) if (plan === 'volume' && !o.sandbox) return '' return form('give', ``) } return one('sandbox', 'Sandbox') + one('volume', 'Volume') } function row(o: AdminOwner, sandboxes = false): string { const left = o.budgetUsd === undefined ? undefined : o.budgetUsd - o.spentUsd const budget = o.budgetUsd === undefined ? `unlimited` : `${money(o.budgetUsd)}
    ${left! <= 0 ? 'used up' : `${money(left!)} left`}` const agents = o.agents.length ? o.agents.map((a) => `${esc(a.handle)}`).join('
    ') : 'none' const form = (action: string, body: string) => `
    ${hidden('action', action)}${hidden('owner', o.did)}${body}
    ` const forms = form('add', ``) + form('set', ``) + (o.budgetUsd === undefined ? '' : form('unlimited', ``)) return ( `${esc(o.handle)}
    ${esc(o.did)}` + `${agents}${money(o.spentUsd)}${o.providerCostUsd ? `
    ${money(o.providerCostUsd)} at cost` : ''}${budget}` + (sandboxes ? `${plans(o, form)}` : '') + `${forms}` ) } export function adminPage(v: AdminView): Page { const notice = v.notice ? `

    ${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'}:

    ${v.invite.qr ? qrFigure(v.invite.qr) : ''}
    ` : '' const table = v.owners.length ? `
    ${v.sandboxes ? '' : ''}${v.owners.map((o) => row(o, v.sandboxes)).join('')}
    OwnerAgentsSpentBudgetCloudChange
    ` : `

    No one has signed up yet.

    ` return page( 200, 'Admin · Languid', ADMIN_CSS + `

    Admin

    ` + `

    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:

    ` : '') + table + (v.funnel ? funnelSection(v.funnel, v.cohort, v.failedSignups) : `

    Funnel

    The funnel couldn't be read from the PDS just now.

    `) + `

    Invite someone

    ` + `
    ${hidden('action', 'invite')}` + `` + `` + `` + `

    ` + `

    ${v.openInvites} sign-up${v.openInvites === 1 ? '' : 's'} left on open invites.

    ` + `

    Test onboarding

    ` + `

    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.

    ` + `
    ${hidden('action', 'test-signup')}
    ` + (v.tests ? `
    ${hidden('action', 'delete-tests')}

    with their agents, for good

    ` : ''), { 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 ( `
    ` + events .map( (e) => `` + `` + ``, ) .join('') + `
    When (UTC)LevelKindWhat
    ${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)}
    ` : ''}${e.detail ? `
    Output and note
    ${esc(e.detail)}
    ` : ''}
    ` ) } /** `/admin/owners/`: one owner, from the ops space and the service's own state. Never their agents' spaces. */ export function adminOwnerPage(v: AdminOwnerView): Page { const dl = (pairs: [string, string][]) => `
    ${pairs.map(([k, x]) => `
    ${esc(k)}
    ${x}
    `).join('')}
    ` const facts = dl([ ['DID', `${esc(v.did)}`], ['Signed up', v.createdAt ? short(v.createdAt) : '·'], ['Last seen', v.lastSeenAt ? short(v.lastSeenAt) : 'not yet recorded'], ['Spent', `${money(v.spentUsd)}${v.providerCostUsd ? ` (${money(v.providerCostUsd)} at cost)` : ''}`], ['Budget', v.budgetUsd === undefined ? 'unlimited' : money(v.budgetUsd)], ['Agents', v.agents.length ? v.agents.map((a) => `${esc(a)}`).join(', ') : 'none'], ]) const funnel = v.funnel.length ? `
      ${v.funnel.map((e) => `
    1. ${short(e.createdAt)} ${esc(e.step)}${e.detail ? ` ${esc(e.detail)}` : ''}
    2. `).join('')}
    ` : `

    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.

    ` + `
    ${v.usage.byAgent.map((a) => ``).join('')}
    By agentCallsCharged
    ${esc(a.name)}${a.totals.calls}${money(a.totals.charged)}
    ` + `
    ${v.usage.byModel.map((a) => ``).join('')}
    By modelCallsCharged
    ${esc(a.name)}${a.totals.calls}${money(a.totals.charged)}
    ` + `
    ${usedDays.reverse().map((d) => ``).join('')}
    DayCallsCharged
    ${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 ? `
    ` + v.visits .map( (d) => `` + ``, ) .join('') + `
    Day (UTC)PagesFirst – lastTop 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 + '' + `

    ${esc(v.handle)}

    ` + `

    Admin · Logs

    ` + `

    From the ops space and the service's records of this owner. Nothing here is read from their agents' spaces.

    ` + facts + `

    Funnel

    ${funnel}` + // Daily run counts go here once the ops space has them (the run-history work): read them in // adminOwnerRequest and add a section; counts only, never what the runs said. `

    Visits

    ${off}${visits}` + `

    Browser errors

    ${errors}` + `

    Runs

    Daily run counts aren't in the ops space yet.

    ` + `

    Model spend

    ${usage}` + `

    Credit

    ${grants}` + `

    Sessions

    ${sessions}` + `

    Ops events

    ` + (v.fromMemory ? `` : '') + 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 ? `
    ` + shown .map( (e) => `` + `` + ``, ) .join('') + `
    When (UTC)LevelKindWhat
    ${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)}
    ` : ''}${e.detail ? `
    Output and note
    ${esc(e.detail)}
    ` : ''}
    ` : `

    Nothing logged${v.level || v.kind ? ' with these filters' : ''}.

    ` return page( 200, 'Logs · Languid', ADMIN_CSS + '' + `

    Logs

    ` + `

    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.

    ` + (v.fromMemory ? `` : '') + 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: (Omit & { rkey?: string; agent?: string; handle: string; triage?: import('./feedback-triage.ts').FeedbackTriage })[] /** Agents that share, and agents that don't (their feedback stays in their own space). */ sharing: number notSharing: number /** The account it's shared with (ops.languid.ai). */ destination: string kind?: string status?: string notice?: { text: string; error?: boolean } /** Only feedback with no reply to the agent yet. */ open?: boolean } /** `/admin/feedback`: what agents sent the maintainer with their feedback tool. */ export function adminFeedbackPage(v: AdminFeedbackView): Page { const kinds = ['bug', 'idea', 'other'] const shown = v.feedback .filter((f) => (!v.kind || f.kind === v.kind) && (!v.status || v.status === 'all' || (f.triage?.status ?? 'open') === v.status) && (!v.open || !f.reply)) .slice(0, 500) const link = (kind?: string, status?: string, open = v.open) => '/admin/feedback?' + new URLSearchParams({ ...(kind ? { kind } : {}), ...(status ? { status } : {}), ...(open ? { open: '1' } : {}) }) const filter = `

    Kind ` + [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) => f.reply ? `${esc(f.reply.status)}${f.reply.version ? ` ${esc(f.reply.version)}` : ''}
    ${esc(f.reply.text)}
    ` : 'open' const rows = shown.length ? `
    ` + shown .map( (f) => `` + `` + ``, ) .join('') + `
    When (UTC)KindAgentFeedbackReply
    ${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')} · Triage

    Reference: ${esc(f.uri)}

    CID: ${esc(f.cid ?? '')}

    ` + `
    ` + `
    ` : '') + `${f.model || f.version ? `${[f.model ? `${f.provider}/${f.model}` : '', f.version ? f.version.slice(0, 7) : ''].filter(Boolean).map((x) => esc(x)).join(' · ')}` : ''}
    ${status(f)}
    ` : `

    No ${v.open ? 'unanswered ' : ''}feedback${v.kind || v.status ? ' matching this filter' : ''} yet.

    ` return page( 200, 'Feedback · Languid', ADMIN_CSS + '' + `

    Feedback

    ` + (v.notice ? `

    ${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 /** Owners to pick from for a message to one person. */ owners: { did: string; handle: string }[] /** The ops account's handle, which the messages come from. */ from?: string notice?: { text: string; error?: boolean } } /** `/admin/messages`: write a message to every owner's Inbox or to one owner's, and see what went out. */ export function adminMessagesPage(v: AdminMessagesView): Page { const handleOf = new Map(v.owners.map((o) => [o.did, o.handle])) const notice = v.notice ? `

    ${esc(v.notice.text)}

    ` : '' const options = [``, ...v.owners.map((o) => ``)].join('') const sent = v.messages.length ? `
      ` + v.messages .map( (m) => `
    • ${esc(m.createdAt.replace('T', ' ').slice(0, 16))} UTC · to ${m.to ? esc(handleOf.get(m.to) ?? m.to) : 'everyone'} · ${v.dismissed.get(m.rkey) ?? 0} dismissed` + `

      ${esc(m.title)}

      ${messageBody(m.body)}` + `
      ${hidden('action', 'delete')}${hidden('message', m.rkey)}
    • `, ) .join('') + `
    ` : `

    Nothing sent yet.

    ` return page( 200, 'Messages · Admin · Languid', ADMIN_CSS + '' + `

    Messages

    ` + `

    Admin

    ` + `

    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 + `
    ${hidden('action', 'send')}` + `` + `` + `` + `

    ` + `

    Sent

    ` + sent, { path: '/admin', app: true }, ) }