// `/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 type { FunnelRow } 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 { Feedback } from './telemetry.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 } } /** How far each owner got, newest sign-up first. Undefined when the funnel couldn't be read. */ funnel?: FunnelRow[] } /** When, as a short UTC date and time; `before`: done before the funnel was recorded. */ const when = (at?: string) => (!at ? '·' : at === 'before' ? '✓' : `${esc(at.replace('T', ' ').slice(5, 16))}`) /** The funnel: how many owners reached each step, then one row per owner. */ function funnelSection(rows: FunnelRow[]): string { const steps: [keyof FunnelRow, string][] = [ ['signedUp', 'Signed up'], ['signInStarted', 'Went to sign in'], ['signedIn', 'Signed in'], ['onboarded', 'Onboarded'], ['firstAgent', 'Agent'], ['firstChat', 'Chatted'], ] const counts = steps.map(([k, label]) => `
  • ${rows.filter((r) => r[k]).length} ${label.toLowerCase()}
  • `).join('') const body = rows .map( (r) => `${esc(r.handle)}${steps.map(([k]) => `${when(r[k] as string | undefined)}`).join('')}` + `${r.lastFailure ? `${esc(r.lastFailure.at.replace('T', ' ').slice(5, 16))} ${esc(r.lastFailure.detail ?? '')}` : ''}`, ) .join('') return ( `

    Funnel

    How far each owner got (UTC). Steps before Nov 19 weren't recorded, except sign-up and agents.

    ` + `` + `
    ${steps.map(([, l]) => ``).join('')}${body}
    Owner${l}Last failed sign-in
    ` ) } const 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', CSS + `

    Admin

    ` + `

    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 + table + (v.funnel ? funnelSection(v.funnel) : `

    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.

    `, { 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)}
    ` : ''}
    ` : `

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

    ` return page( 200, 'Logs · Languid', 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.

    ` + (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: (Feedback & { handle: string })[] /** 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 } /** `/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).slice(0, 500) const filter = `

    Kind ` + [undefined, ...kinds].map((x) => (x === v.kind ? `${x ?? 'all'}` : `${x ?? 'all'}`)).join(' ') + '

    ' const rows = shown.length ? `
    ` + shown .map( (f) => `` + ``, ) .join('') + `
    When (UTC)KindAgentFeedback
    ${esc(f.createdAt.replace('T', ' ').slice(5, 16))}${esc(f.kind)}${esc(f.handle)}
    ${esc(f.text)}
    ` + `${f.model || f.version ? `${[f.model ? `${f.provider}/${f.model}` : '', f.version ? f.version.slice(0, 7) : ''].filter(Boolean).map((x) => esc(x)).join(' · ')}` : ''}
    ` : `

    No feedback${v.kind ? ' of this kind' : ''} yet.

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

    Feedback

    ` + `

    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 ? `` : `

    Nothing sent yet.

    ` return page( 200, 'Messages · Admin · Languid', 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 }, ) }