Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

10.8 KB
Raw Blame
// Server admin › Call quality › levels: which levels assistants can pick (Standard always,
// Premium and Ultra by switch; Ultra only with a realtime model), the level new assistants start on, and, collapsed,
// the default models per level. Turning a level off moves its assistants to Standard at once, with Undo in the toast.
import {
  CALL_QUALITY_LABELS,
  type CallQuality,
  type CallQualityAdminData,
  type CallQualityAdminLevel,
  type ModelChoice,
  type ProviderName,
  providerSpec,
} from '@linedesk/actions'
import { type MessageKey, msg } from '@linedesk/i18n'
import { T, useT } from '@linedesk/i18n/react'
import { useState } from 'react'
import { setQueryData, useQuery } from '../cachedQuery.ts'
import { i18n } from '../i18n/index.tsx'
import { pricePerMinute } from '../settings/levelModel.ts'
import { appLink } from '../ui/AppLink.tsx'
import { Select, type SelectOption, Switch } from '../ui/controls.tsx'
import { Card } from '../ui/form.tsx'
import { Badge } from '../ui/kit.tsx'
import { Loading } from '../ui/LoadStates.tsx'
import { SettingRow, SkeletonSettingRow } from '../ui/SettingRow.tsx'
import { type AdminInputs, runAdmin } from './api.ts'
import { errorText, type Notify } from './notify.ts'
import { FoldOut } from '../ui/FoldOut.tsx'

export const CALL_QUALITY = 'admin.callQuality'
export const loadCallQuality = async () => (await runAdmin('callQuality.get', {})) as unknown as CallQualityAdminData

type SetInput = AdminInputs['callQuality.set']
const save = async (input: SetInput) => (await runAdmin('callQuality.set', input)) as unknown as CallQualityAdminData

/** Each level's line, with its price where the install bills. */
const LINE: Record<CallQuality, { price: MessageKey; plain: MessageKey }> = {
  standard: { price: msg('admin.callQuality.standardPrice'), plain: msg('admin.callQuality.standard') },
  premium: { price: msg('admin.callQuality.premiumPrice'), plain: msg('admin.callQuality.premium') },
  ultra: { price: msg('admin.callQuality.ultraPrice'), plain: msg('admin.callQuality.ultra') },
}
const lineOf = (data: CallQualityAdminData, level: CallQuality) => {
  const cents = data.centsPerMinute?.[level]
  return cents == null ? i18n().t(LINE[level].plain) : i18n().t(LINE[level].price, { price: pricePerMinute(cents) })
}

/** A model picker's options: the level's models in list order, and the current one if a list changed since. */
const choices = (list: readonly ModelChoice[], current: string | null): SelectOption<string>[] => [
  ...list.map(m => ({ value: m.id, label: m.name })),
  ...(current && !list.some(m => m.id === current) ? [{ value: current, label: current }] : []),
]

const providerLabel = (provider: string) => {
  try {
    return providerSpec(provider as ProviderName).label
  } catch {
    return provider
  }
}

/**
 * Saves a change. A level turned off says how many assistants moved to Standard, with Undo: the level back on and
 * those assistants back on it.
 */
export async function changeCallQuality(input: SetInput, offLevel: 'premium' | 'ultra' | undefined, notify: Notify) {
  const t = i18n().t
  try {
    const next = await save(input)
    setQueryData(CALL_QUALITY, next)
    if (!offLevel) return
    const moved = next.moved?.find(m => m.level === offLevel)?.assistantIds ?? []
    notify(t('admin.callQuality.off', { level: CALL_QUALITY_LABELS[offLevel], count: moved.length }), async () =>
      setQueryData(
        CALL_QUALITY,
        await save({
          [offLevel]: true,
          ...(moved.length ? { restore: { level: offLevel, assistantIds: moved } } : {}),
        }),
      ),
    )
  } catch (e) {
    notify(errorText(e))
  }
}

export function CallQualityCard({ notify }: { notify: Notify }) {
  const t = useT()
  const query = useQuery(CALL_QUALITY, loadCallQuality)
  const [open, setOpen] = useState(false)
  const data = query.data
  const change = (input: SetInput, offLevel?: 'premium' | 'ultra') => changeCallQuality(input, offLevel, notify)
  const level = (l: CallQuality) => data?.levels.find(x => x.level === l)
  const enabledLevels = data?.levels.filter(l => l.enabled).map(l => l.level) ?? ['standard']
  return (
    <Card
      id="call-quality"
      className="adm-cq"
      title={t('admin.callQuality.title')}
      description={
        data?.centsPerMinute ? (
          <T k="admin.callQuality.descriptionBilling" values={{ link: appLink('#admin/billing') }} />
        ) : undefined
      }
    >
      <Loading
        what={t('admin.callQuality.what')}
        loading={!data}
        error={query.error}
        onRetry={() => void query.reload()}
        skeleton={
          <>
            <SkeletonSettingRow title={CALL_QUALITY_LABELS.standard} control="none" />
            <SkeletonSettingRow title={CALL_QUALITY_LABELS.premium} />
            <SkeletonSettingRow title={CALL_QUALITY_LABELS.ultra} />
          </>
        }
      >
        {data && (
          <>
            <SettingRow
              title={CALL_QUALITY_LABELS.standard}
              description={lineOf(data, 'standard')}
              control={<span className="adm-cq-always">{t('admin.callQuality.alwaysOn')}</span>}
            />
            <SettingRow
              title={CALL_QUALITY_LABELS.premium}
              description={lineOf(data, 'premium')}
              control={
                <Switch
                  label={CALL_QUALITY_LABELS.premium}
                  on={data.settings.premium}
                  onChange={on => void change({ premium: on }, on ? undefined : 'premium')}
                />
              }
            />
            <SettingRow
              title={CALL_QUALITY_LABELS.ultra}
              description={data.realtimeSetUp ? lineOf(data, 'ultra') : t('admin.callQuality.ultraNeedsRealtime')}
              control={
                <Switch
                  label={CALL_QUALITY_LABELS.ultra}
                  on={data.realtimeSetUp && data.settings.ultra}
                  onChange={on => void change({ ultra: on }, on ? undefined : 'ultra')}
                  disabled={!data.realtimeSetUp}
                />
              }
            />
            <SettingRow
              title={t('admin.callQuality.newAssistants')}
              description={t('admin.callQuality.newAssistantsHelp')}
              control={
                <Select
                  id="adm-cq-default"
                  size="sm"
                  align="end"
                  value={data.settings.default}
                  options={enabledLevels.map(l => ({ value: l, label: CALL_QUALITY_LABELS[l] }))}
                  onChange={next => void change({ default: next })}
                  label={t('admin.callQuality.newAssistants')}
                />
              }
            />
            <FoldOut
              className="adm-cq-models"
              open={open}
              onToggle={setOpen}
              summary={t('admin.callQuality.showModels')}
              openSummary={t('admin.callQuality.hideModels')}
            >
              <p className="help adm-cq-foot">{t('admin.callQuality.modelsHelp')}</p>
              {(['standard', 'premium'] as const).map(l => {
                const lv = level(l)
                return lv && <StageModels key={l} level={lv} change={change} />
              })}
              {level('ultra') && <UltraModels level={level('ultra')!} change={change} />}
            </FoldOut>
          </>
        )}
      </Loading>
    </Card>
  )
}

type ModelsProps = { level: CallQualityAdminLevel; change: (input: SetInput) => Promise<void> }

function GroupHead({ level }: { level: CallQualityAdminLevel }) {
  const t = useT()
  return (
    <b className="adm-cq-group-head">
      {CALL_QUALITY_LABELS[level.level]}
      {!level.enabled && <Badge>{t('admin.callQuality.offBadge')}</Badge>}
    </b>
  )
}

/** Standard or Premium: the language model, a voice model per voice provider set up, and speech recognition. */
function StageModels({ level, change }: ModelsProps) {
  const t = useT()
  const l = level.level as 'standard' | 'premium'
  const voices = Object.entries(level.voiceModels).filter(([, list]) => list.length > 0)
  if (!level.models.length && !voices.length && !level.sttModels.length) return null
  return (
    <div className="adm-cq-group">
      <GroupHead level={level} />
      {level.models.length > 0 && (
        <SettingRow
          title={t('admin.callQuality.languageModel')}
          control={
            <Select
              id={`adm-cq-${l}-llm`}
              size="sm"
              align="end"
              value={level.defaults.llm ?? ''}
              options={choices(level.models, level.defaults.llm)}
              onChange={llm => void change({ models: { [l]: { llm } } })}
              label={t('admin.callQuality.languageModel')}
            />
          }
        />
      )}
      {voices.map(([provider, list]) => (
        <SettingRow
          key={provider}
          title={
            voices.length > 1
              ? t('admin.callQuality.voiceModelOf', { provider: providerLabel(provider) })
              : t('admin.callQuality.voiceModel')
          }
          control={
            <Select
              id={`adm-cq-${l}-voice-${provider}`}
              size="sm"
              align="end"
              value={level.defaults.voice[provider] ?? ''}
              options={choices(list, level.defaults.voice[provider] ?? null)}
              onChange={model => void change({ models: { [l]: { voice: { [provider]: model } } } })}
              label={
                voices.length > 1
                  ? t('admin.callQuality.voiceModelOf', { provider: providerLabel(provider) })
                  : t('admin.callQuality.voiceModel')
              }
            />
          }
        />
      ))}
      {level.sttModels.length > 0 && (
        <SettingRow
          title={t('admin.callQuality.speechRecognition')}
          control={
            <Select
              id={`adm-cq-${l}-stt`}
              size="sm"
              align="end"
              value={level.defaults.stt ?? ''}
              options={choices(level.sttModels, level.defaults.stt)}
              onChange={stt => void change({ models: { [l]: { stt } } })}
              label={t('admin.callQuality.speechRecognition')}
            />
          }
        />
      )}
    </div>
  )
}

/** Ultra: the realtime model. */
function UltraModels({ level, change }: ModelsProps) {
  const t = useT()
  if (!level.realtimeModels.length) return null
  return (
    <div className="adm-cq-group">
      <GroupHead level={level} />
      <SettingRow
        title={t('admin.callQuality.realtimeModel')}
        control={
          <Select
            id="adm-cq-ultra-realtime"
            size="sm"
            align="end"
            value={level.defaults.realtime ?? ''}
            options={choices(level.realtimeModels, level.defaults.realtime)}
            onChange={realtime => void change({ models: { ultra: { realtime } } })}
            label={t('admin.callQuality.realtimeModel')}
          />
        }
      />
    </div>
  )
}