SPB Git

Repository Public

Intelligence.tsx 15.0 KB 325 lines tsx

1// SP Mail Next — Réglages › Intelligence : fournisseur (coupé par défaut ; consentement explicite pour un fournisseur externe),2// fonctions, langue, index de la recherche par le sens, usage. Rien n'est activé sans un geste de la personne.3import { useEffect, useId, useState } from "react"4import { fmtDateTime, fmtNumber, t } from "../../i18n"5import type { MsgKey } from "../../i18n"6import { AI_FEATURES, aiFailure, aiIndexRebuild, aiIndexStatus, aiOn, aiSettings, aiUsage, saveAiSettings, type AiFeature, type AiLanguage, type AiProviderName, type AiSettings, type AiSettingsPatch, type AiUsage, type IndexStatus } from "../../next/ai"7import { S, toast } from "../../state/app"8import { useStore } from "../../state/store"9import { confirmAsync, Dialog, Icon, Spinner } from "../kit"10import { issueText, providerName } from "../next/AiParts"11import "../next/ai.css"12import { Section } from "../Page"13import { ErrorBanner, useLoad } from "./shared"1415const FEATURE: Record<AiFeature, [MsgKey, MsgKey]> = {16  summary: ["nx.ai.feature.summary", "nx.ai.feature.summaryHint"], reply: ["nx.ai.feature.reply", "nx.ai.feature.replyHint"], write: ["nx.ai.feature.write", "nx.ai.feature.writeHint"],17  triage: ["nx.ai.feature.triage", "nx.ai.feature.triageHint"], semantic: ["nx.ai.feature.semantic", "nx.ai.feature.semanticHint"],18}19const FEATURE_NAME: Record<string, MsgKey> = { summary: "nx.ai.feature.summary", reply: "nx.ai.feature.reply", write: "nx.ai.feature.write", triage: "nx.ai.feature.triage", semantic: "nx.ai.feature.semantic", extract: "nx.ai.usage.extract" }20const STATUS: Record<string, MsgKey> = { ok: "nx.ai.usage.ok", cached: "nx.ai.usage.cached", error: "nx.ai.usage.error", invalid_output: "nx.ai.usage.invalid", refused: "nx.ai.usage.refused" }2122/** Consentement explicite : nomme le fournisseur, dit ce qui part et où ; « Annuler » a le focus et ne change rien. */23function ConsentDialog({ onConfirm, onClose }: { onConfirm: () => Promise<void>; onClose: () => void }) {24  const [busy, setBusy] = useState(false)25  return (26    <Dialog27      title={t("nx.ai.consent.title")}28      onClose={onClose}29      alert30      footer={31        <>32          <button type="button" className="btn" onClick={onClose} data-autofocus>33            {t("common.cancel")}34          </button>35          <button36            type="button"37            className="btn primary"38            disabled={busy}39            onClick={async () => {40              setBusy(true)41              try {42                await onConfirm()43              } finally {44                setBusy(false)45              }46            }}47          >48            {t("nx.ai.consent.confirm")}49          </button>50        </>51      }52    >53      <div className="stack nx-ai-consent" data-nx-ai="consent">54        <p>{t("nx.ai.consent.sent")}</p>55        <p>{t("nx.ai.consent.scope")}</p>56        <p className="muted">{t("nx.ai.consent.local")}</p>57        <p className="muted">{t("nx.ai.consent.withdraw")}</p>58      </div>59    </Dialog>60  )61}6263function IndexSection({ settings, online }: { settings: AiSettings; online: boolean }) {64  const { state, reload } = useLoad<IndexStatus>((signal) => aiIndexStatus(signal), `${settings.provider}:${settings.features.semantic}`)65  const mailboxes = useStore(S, (s) => s.me?.mailboxes)66  const [busy, setBusy] = useState(false)67  const rebuild = async () => {68    if (!(await confirmAsync({ title: t("nx.ai.index.rebuildTitle"), body: t("nx.ai.index.rebuildBody"), confirmLabel: t("nx.ai.index.rebuild") }))) return69    setBusy(true)70    try {71      const n = await aiIndexRebuild()72      toast({ kind: "success", text: t("nx.ai.index.queued", { n: fmtNumber(n) }) })73      reload()74    } catch (e) {75      toast({ kind: "error", text: t("nx.ai.index.failed"), detail: issueText(aiFailure(e)) })76    } finally {77      setBusy(false)78    }79  }80  const st = state.status === "ready" ? state.data : null81  return (82    <Section83      title={t("nx.ai.index.title")}84      description={t("nx.ai.index.desc")}85      actions={86        st?.available ? (87          <button type="button" className="btn small" onClick={() => void rebuild()} disabled={busy || !online || !aiOn(settings, "semantic")} title={!online ? t("nx.offline") : !aiOn(settings, "semantic") ? t("nx.ai.index.enableFirst") : undefined}>88            <Icon name="refresh" small />89            <span>{t("nx.ai.index.rebuild")}</span>90          </button>91        ) : null92      }93    >94      <div data-nx-index={st ? (st.available ? "available" : "unavailable") : state.status}>95        {state.status === "loading" ? <Spinner label={t("nx.loading")} /> : null}96        {state.status === "error" ? <ErrorBanner text={issueText(aiFailure(state.error))} onRetry={reload} /> : null}97        {st && !st.available ? (98          <div className="banner" role="status">99            <Icon name="warn" small />100            <div>101              <div>{t("nx.ai.index.unavailable")}</div>102              {st.reason ? <div className="muted small set-wrap">{t("nx.ai.index.reason", { reason: st.reason })}</div> : null}103            </div>104          </div>105        ) : null}106        {st?.available ? (107          <div className="stack">108            <p className="small muted set-wrap">109              {t("nx.ai.index.backend", { backend: st.backend ?? "—", model: st.model ?? "—" })}110              {st.last_indexed_at ? ` · ${t("nx.ai.index.last", { date: fmtDateTime(st.last_indexed_at) })}` : ""}111              {!st.enabled ? ` · ${t("nx.ai.index.off")}` : ""}112            </p>113            <div className="table-wrap" tabIndex={0} role="region" aria-label={t("nx.ai.index.title")}>114              <table className="table nx-ai-table">115                <thead>116                  <tr>117                    <th scope="col">{t("nx.ai.index.mailbox")}</th>118                    <th scope="col" className="num">{t("nx.ai.index.indexed")}</th>119                    <th scope="col" className="num">{t("nx.ai.index.queuedCol")}</th>120                    <th scope="col" className="num">{t("nx.ai.index.total")}</th>121                  </tr>122                </thead>123                <tbody>124                  {st.mailboxes.map((m) => (125                    <tr key={m.mailbox_id}>126                      <th scope="row" className="set-wrap">{mailboxes?.find((x) => x.id === m.mailbox_id)?.address ?? m.mailbox_id}</th>127                      <td className="num">{fmtNumber(m.indexed)}</td>128                      <td className="num">{fmtNumber(m.queued)}</td>129                      <td className="num">{fmtNumber(m.total)}</td>130                    </tr>131                  ))}132                </tbody>133              </table>134            </div>135          </div>136        ) : null}137      </div>138    </Section>139  )140}141142function UsageSection({ stamp }: { stamp: string }) {143  const { state, reload } = useLoad<AiUsage>((signal) => aiUsage(30, signal), stamp)144  const u = state.status === "ready" ? state.data : null145  return (146    <Section title={t("nx.ai.usage.title")} description={t("nx.ai.usage.desc")}>147      <div data-nx-usage={state.status}>148        {state.status === "loading" ? <Spinner label={t("nx.loading")} /> : null}149        {state.status === "error" ? <ErrorBanner text={issueText(aiFailure(state.error))} onRetry={reload} /> : null}150        {u ? (151          <div className="stack">152            <p className="small muted">{t("nx.ai.usage.limits", { used: fmtNumber(u.limits.used_24h), day: fmtNumber(u.limits.per_day), minute: fmtNumber(u.limits.per_minute) })}</p>153            {u.rows.length ? (154              <div className="table-wrap" tabIndex={0} role="region" aria-label={t("nx.ai.usage.title")}>155                <table className="table nx-ai-table">156                  <thead>157                    <tr>158                      <th scope="col">{t("nx.ai.usage.day")}</th>159                      <th scope="col">{t("nx.ai.usage.feature")}</th>160                      <th scope="col">{t("nx.ai.usage.provider")}</th>161                      <th scope="col">{t("nx.ai.usage.status")}</th>162                      <th scope="col" className="num">{t("nx.ai.usage.requests")}</th>163                      <th scope="col" className="num">{t("nx.ai.usage.tokens")}</th>164                    </tr>165                  </thead>166                  <tbody>167                    {u.rows.map((r, i) => (168                      <tr key={i}>169                        <td className="nx-ai-nowrap">{r.day}</td>170                        <td>{FEATURE_NAME[r.feature] ? t(FEATURE_NAME[r.feature]) : r.feature}</td>171                        <td className="set-wrap">172                          {providerName(r.provider)}173                          {r.model ? <span className="muted"> · {r.model}</span> : null}174                        </td>175                        <td>{STATUS[r.status] ? t(STATUS[r.status]) : r.status}</td>176                        <td className="num">{fmtNumber(r.requests)}</td>177                        <td className="num nx-ai-nowrap">178                          {fmtNumber(r.input_tokens)} / {fmtNumber(r.output_tokens)}179                        </td>180                      </tr>181                    ))}182                  </tbody>183                </table>184              </div>185            ) : (186              <p className="nx-note">{t("nx.ai.usage.empty")}</p>187            )}188          </div>189        ) : null}190      </div>191    </Section>192  )193}194195export default function Intelligence() {196  const st = useStore(aiSettings.store, (s) => s)197  const online = useStore(S, (s) => s.online)198  const [consent, setConsent] = useState(false)199  const [busy, setBusy] = useState(false)200  const [stamp, setStamp] = useState(0)201  const name = useId()202  useEffect(() => void aiSettings.refresh(), [])203204  const settings = st.items[0]205  if (!settings) {206    if (st.error && !st.loading) return <ErrorBanner text={t("nx.ai.settings.loadFailed")} onRetry={() => void aiSettings.refresh()} />207    return <Spinner label={t("nx.loading")} />208  }209  const locked = busy || !online210  const save = async (patch: AiSettingsPatch): Promise<boolean> => {211    setBusy(true)212    try {213      await saveAiSettings(patch)214      setStamp((n) => n + 1)215      return true216    } catch (e) {217      toast({ kind: "error", text: t("nx.ai.settings.saveFailed"), detail: issueText(aiFailure(e)) })218      void aiSettings.refresh()219      return false220    } finally {221      setBusy(false)222    }223  }224  const choose = (p: AiProviderName) => {225    if (p === settings.provider) return226    // le fournisseur externe ne s'active qu'après le dialogue de consentement ; « Annuler » laisse le choix précédent227    if (p === "anthropic") return setConsent(true)228    void save({ provider: p })229  }230  const providers: { id: AiProviderName; title: string; hint: string; unavailable: string | null }[] = [231    { id: "off", title: t("nx.ai.provider.off"), hint: t("nx.ai.provider.offHint"), unavailable: null },232    { id: "local", title: t("nx.ai.provider.local"), hint: t("nx.ai.provider.localHint"), unavailable: settings.available.local ? null : t("nx.ai.provider.localMissing") },233    { id: "anthropic", title: t("nx.ai.provider.anthropicLong"), hint: t("nx.ai.provider.anthropicHint"), unavailable: settings.available.anthropic ? null : t("nx.ai.provider.anthropicMissing") },234  ]235  const off = settings.provider === "off"236237  return (238    <>239      {!online ? (240        <div className="banner" role="status">241          <Icon name="offline" small />242          <span>{t("nx.offline")}</span>243        </div>244      ) : null}245      <Section246        title={t("nx.ai.settings.provider")}247        description={t("nx.ai.settings.providerDesc")}248        actions={249          <span className={`badge ${off ? "" : "ok"}`} role="status" data-ai-state={settings.provider}>250            {off ? t("nx.ai.settings.stateOff") : t("nx.ai.settings.stateOn")}251          </span>252        }253      >254        <fieldset className="set-fieldset nx-ai-choices">255          <legend className="sr-only">{t("nx.ai.settings.provider")}</legend>256          {providers.map((p) => {257            const disabled = locked || (!!p.unavailable && settings.provider !== p.id)258            return (259              <label key={p.id} className={`nx-ai-choice${settings.provider === p.id ? " on" : ""}${disabled ? " disabled" : ""}`}>260                <input type="radio" name={name} value={p.id} checked={settings.provider === p.id} disabled={disabled} onChange={() => choose(p.id)} />261                <span className="nx-ai-choice-main">262                  <span className="nx-ai-choice-title">{p.title}</span>263                  <span className="small muted">{p.hint}</span>264                  {p.unavailable ? (265                    <span className="small nx-ai-choice-why" data-unavailable={p.id}>266                      {p.unavailable}267                    </span>268                  ) : null}269                  {p.id === "anthropic" && settings.provider === "anthropic" && settings.consent_external_at ? <span className="small muted">{t("nx.ai.consent.given", { date: fmtDateTime(settings.consent_external_at) })}</span> : null}270                </span>271              </label>272            )273          })}274        </fieldset>275      </Section>276277      <Section title={t("nx.ai.settings.features")} description={off ? t("nx.ai.settings.featuresOff") : t("nx.ai.settings.featuresDesc")}>278        <div className="set-list">279          {AI_FEATURES.map((f) => {280            const blocked = f === "semantic" && !settings.available.semantic281            return (282              <div className="set-item" key={f}>283                <label className="check set-item-main nx-ai-feature">284                  <input type="checkbox" checked={settings.features[f] && !off} disabled={locked || off || blocked} onChange={(e) => void save({ features: { [f]: e.target.checked } })} data-ai-feature={f} />285                  <span>286                    <span className="nx-ai-choice-title">{t(FEATURE[f][0])}</span>287                    <span className="small muted set-block">{t(FEATURE[f][1])}</span>288                    {blocked ? <span className="small nx-ai-choice-why set-block">{t("nx.ai.feature.semanticMissing")}</span> : null}289                  </span>290                </label>291              </div>292            )293          })}294        </div>295      </Section>296297      <Section title={t("nx.ai.settings.language")} description={t("nx.ai.settings.languageDesc")}>298        <div className="segmented set-segmented" role="group" aria-label={t("nx.ai.settings.language")}>299          {(["auto", "fr", "en"] as AiLanguage[]).map((l) => (300            <button key={l} type="button" aria-pressed={settings.language === l} disabled={locked} onClick={() => settings.language !== l && void save({ language: l })}>301              {t(l === "auto" ? "nx.ai.lang.auto" : l === "fr" ? "nx.ai.lang.fr" : "nx.ai.lang.en")}302            </button>303          ))}304        </div>305      </Section>306307      <IndexSection settings={settings} online={online} />308      <UsageSection stamp={`${stamp}`} />309310      <Section title={t("nx.ai.privacy.title")}>311        <p className="nx-ai-privacy">{t("nx.ai.privacy.body")}</p>312      </Section>313314      {consent ? (315        <ConsentDialog316          onClose={() => setConsent(false)}317          onConfirm={async () => {318            if (await save({ provider: "anthropic", consent_external: true })) setConsent(false)319          }}320        />321      ) : null}322    </>323  )324}325
Files main
Menu

Theme