SPB Git

Repository Public

Admin.tsx 17.1 KB 413 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPSearch8 * File             : web/index/src/Admin.tsx9 * Module           : web10 * Repository       : https://git.spboucher.ai/spweb11 * Project Website  : https://search.spboucher.ai12 * Created          : 2026-11-2713 * Last Modified    : 2026-11-2714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { useId, useState, type FormEvent } from 'react';44import {45  Async, Gauge, Notice, Pill, Stat, fmtBytes, fmtDateTime, fmtInt, fmtNum, useDocumentTitle,46} from '@spweb/shared-ui';47import {48  ActionStatus, AdminGate, AdminTabs, AuditLog, ConfirmButton, DataTable, Requires, useAction, useAdmin, useAdminFetch,49} from '@spweb/shared-ui/admin';50import { useT } from '@spweb/shared-ui/i18n/indexAdmin';51import '@spweb/shared-ui/css/admin.css';52import { LEVEL_TONE, isLevel } from './levels';53import { Mark } from './Logo';54import type { EvictResult, ExplainHit, IndexOverview, PurgePreview, Shard, Tombstone } from './types';5556function OverviewView() {57  const { t, lang } = useT();58  const { call, can } = useAdmin();59  const state = useAdminFetch<IndexOverview>('/api/admin/index/overview');60  const act = useAction();61  const compact = (shard: number | null) =>62    act.run(async () => {63      const r = await call<{ started?: boolean }>('POST', '/api/admin/index/compact', { shard });64      // A 2xx answer without "started": true is not a success.65      if (!r || r.started !== true) throw new Error(t('ia.compact.no'));66    }, t('ia.compact.ok')).then(state.reload);67  return (68    <Async state={state}>69      {(o) => {70        const g = o.governor;71        const tone = LEVEL_TONE[g?.level ?? ''] ?? 'info';72        return (73          <>74            <dl className="stats">75              <Stat label={t('cov.version')} value={fmtInt(o.index_version, lang)} />76              <Stat label={t('ia.pending')} value={fmtInt(o.pending_docs, lang)} />77              <Stat label={t('ia.tombstones')} value={fmtInt(o.tombstones, lang)} />78            </dl>79            <h2>{t('ia.shards')}</h2>80            <DataTable81              caption={t('ia.shards')}82              rows={o.shards ?? []}83              rowKey={(s) => s.id}84              cols={[85                { head: t('ia.sh.id'), cell: (s) => s.id },86                { head: t('ia.sh.health'), cell: (s) => <Pill tone={s.healthy ? 'ok' : 'danger'}>{s.healthy ? t('ia.sh.ok') : t('ia.sh.bad')}</Pill> },87                { head: t('ia.sh.docs'), cell: (s) => fmtInt(s.documents, lang), num: true },88                { head: t('ia.sh.segments'), cell: (s) => fmtInt(s.segments, lang), num: true },89                { head: t('ia.sh.bytes'), cell: (s) => fmtBytes(s.bytes, lang), num: true },90                { head: t('ia.sh.commit'), cell: (s) => fmtDateTime(s.last_commit, lang) },91                ...(can('operator')92                  ? [{93                      head: t('adm.actions'),94                      cell: (s: Shard) => <ConfirmButton label={t('ia.compact')} question={t('ia.compact.q')} onConfirm={() => compact(s.id)} disabled={act.busy} />,95                    }]96                  : []),97              ]}98            />99            <Requires role="operator">100              <ConfirmButton label={t('ia.compact.all')} question={t('ia.compact.q')} onConfirm={() => compact(null)} disabled={act.busy} />101            </Requires>102            <ActionStatus a={act} />103104            <h2>{t('ia.gov')}</h2>105            {g && (106              <>107                <p className="row">108                  <span>{t('quota.level')} :</span>109                  <Pill tone={tone}>{isLevel(g.level) ? t(`level.${g.level}`) : g.level}</Pill>110                  {isLevel(g.level) && <span className="muted">{t(`level.${g.level}.d`)}</span>}111                </p>112                <Gauge113                  label={t('quota.used')}114                  value={g.used_bytes}115                  max={g.limit_bytes}116                  tone={tone}117                  text={`${fmtBytes(g.used_bytes, lang)} / ${fmtBytes(g.limit_bytes, lang)}`}118                />119                <dl className="stats">120                  <Stat label={t('ia.gov.free')} value={fmtBytes(g.free_volume_bytes, lang)} />121                </dl>122                {Array.isArray(g.categories) && g.categories.length > 0 && (123                  <>124                    <h3>{t('quota.cats')}</h3>125                    <DataTable126                      caption={t('quota.cats')}127                      rows={g.categories}128                      rowKey={(c) => c.name}129                      cols={[130                        { head: t('quota.cat'), cell: (c) => c.name },131                        { head: t('quota.catUsed'), cell: (c) => fmtBytes(c.used_bytes, lang), num: true },132                        { head: t('quota.catBudget'), cell: (c) => fmtBytes(c.budget_bytes, lang), num: true },133                        { head: '%', cell: (c) => (c.budget_bytes > 0 ? fmtNum((c.used_bytes / c.budget_bytes) * 100, lang) : '—'), num: true },134                      ]}135                    />136                  </>137                )}138              </>139            )}140          </>141        );142      }}143    </Async>144  );145}146147function TombstonesView() {148  const { t, lang } = useT();149  const state = useAdminFetch<{ tombstones: Tombstone[] }>('/api/admin/index/tombstones?limit=100');150  return (151    <>152      <h2>{t('ia.tab.tombstones')}</h2>153      <Async state={state}>154        {(d) => (155          <DataTable156            caption={t('ia.tab.tombstones')}157            rows={d.tombstones ?? []}158            rowKey={(x, i) => `${x.id}-${i}`}159            cols={[160              { head: t('ia.ts.id'), cell: (x) => <code>{x.id}</code> },161              { head: t('adm.reason'), cell: (x) => x.reason },162              { head: t('ia.ts.at'), cell: (x) => fmtDateTime(x.at, lang) },163            ]}164          />165        )}166      </Async>167    </>168  );169}170171type Kind = 'domain' | 'prefix' | 'url';172173/** Purge in three explicit steps: preview, type the pattern, purge with the server's confirm token. */174function PurgeView() {175  const { t, lang } = useT();176  const { call } = useAdmin();177  const act = useAction();178  const id = useId();179  const [kind, setKind] = useState<Kind>('domain');180  const [pattern, setPattern] = useState('');181  const [preview, setPreview] = useState<{ pattern: string; data: PurgePreview } | null>(null);182  const [typed, setTyped] = useState('');183  const [purged, setPurged] = useState<number | null>(null);184185  const reset = () => {186    setPreview(null);187    setTyped('');188  };189  const doPreview = (e: FormEvent) => {190    e.preventDefault();191    const p = pattern.trim();192    if (!p) return;193    reset();194    setPurged(null);195    act.run(() => call<PurgePreview>('POST', '/api/admin/index/purge-preview', { kind, pattern: p }), t('ia.purge.preview')).then((r) => {196      if (r.ok && r.value) setPreview({ pattern: p, data: r.value });197    });198  };199  const doPurge = () => {200    if (!preview || typed !== preview.pattern) return;201    act.run(() => call<{ purged: number }>('POST', '/api/admin/index/purge', { confirm_token: preview.data.confirm_token })).then((r) => {202      if (r.ok) {203        setPurged(r.value?.purged ?? 0);204        setPattern('');205        reset();206      }207    });208  };209210  return (211    <>212      <h2>{t('ia.purge.title')}</h2>213      <p className="muted">{t('ia.purge.lead')}</p>214      <Requires role="admin">215        <form className="form" onSubmit={doPreview}>216          <div className="field">217            <label htmlFor={`${id}-k`}>{t('ia.purge.kind')}</label>218            <select id={`${id}-k`} value={kind} onChange={(e) => { setKind(e.target.value as Kind); reset(); }}>219              <option value="domain">{t('ia.purge.domain')}</option>220              <option value="prefix">{t('ia.purge.prefix')}</option>221              <option value="url">{t('ia.purge.url')}</option>222            </select>223          </div>224          <div className="field">225            <label htmlFor={`${id}-p`}>{t('ia.purge.pattern')}</label>226            <input id={`${id}-p`} type="text" value={pattern} onChange={(e) => { setPattern(e.target.value); reset(); }} required autoCapitalize="off" autoComplete="off" spellCheck={false} />227          </div>228          <div><button type="submit" className="btn" disabled={act.busy || pattern.trim() === ''}>{t('ia.purge.preview')}</button></div>229        </form>230        {preview && (231          <div className="danger-zone" aria-live="polite">232            <p><strong>{t('ia.purge.matches', { n: fmtInt(preview.data.matches, lang), p: preview.pattern })}</strong></p>233            {(preview.data.sample ?? []).length > 0 && (234              <>235                <h3>{t('ia.purge.sample')}</h3>236                <DataTable237                  caption={t('ia.purge.sample')}238                  rows={preview.data.sample}239                  rowKey={(_, i) => i}240                  cols={[241                    { head: t('ia.purge.s.url'), cell: (x) => <code>{x.url}</code> },242                    { head: t('ia.purge.s.title'), cell: (x) => x.title },243                  ]}244                />245              </>246            )}247            {preview.data.matches > 0 ? (248              <div className="form">249                <div className="field">250                  <label htmlFor={`${id}-c`}>{t('ia.purge.confirm')} : <code>{preview.pattern}</code></label>251                  <input id={`${id}-c`} type="text" value={typed} onChange={(e) => setTyped(e.target.value)} autoCapitalize="off" autoComplete="off" spellCheck={false} />252                </div>253                <div className="row">254                  <button type="button" className="btn btn-danger" disabled={act.busy || typed !== preview.pattern} onClick={doPurge}>{t('ia.purge.go')}</button>255                  <button type="button" className="btn" onClick={reset}>{t('ia.purge.cancel')}</button>256                </div>257              </div>258            ) : (259              <p className="muted">{t('ia.purge.zero')}</p>260            )}261          </div>262        )}263        <div aria-live="polite">264          {act.busy || act.error ? <ActionStatus a={act} /> : null}265          {purged !== null && <Notice tone="ok"><p>{t('ia.purge.done', { n: fmtInt(purged, lang) })}</p></Notice>}266        </div>267      </Requires>268    </>269  );270}271272function EvictView() {273  const { t, lang } = useT();274  const { call } = useAdmin();275  const act = useAction();276  const id = useId();277  const [max, setMax] = useState(1000);278  const [res, setRes] = useState<{ dry: boolean; max: number; data: EvictResult } | null>(null);279  const valid = Number.isInteger(max) && max > 0;280  const ready = res !== null && res.dry && res.max === max;281  const send = (dry: boolean) =>282    act.run(() => call<EvictResult>('POST', '/api/admin/index/evict', { max_docs: max, dry_run: dry })).then((r) => {283      if (r.ok && r.value) setRes({ dry, max, data: r.value });284    });285  return (286    <>287      <h2>{t('ia.evict.title')}</h2>288      <p className="muted">{t('ia.evict.lead')}</p>289      <Requires role="admin">290        <div className="row row-end">291          <div className="field">292            <label htmlFor={id}>{t('ia.evict.max')}</label>293            <input id={id} type="number" min={1} step={1} inputMode="numeric" value={Number.isFinite(max) ? max : ''} onChange={(e) => setMax(e.target.valueAsNumber)} />294          </div>295          <button type="button" className="btn" disabled={act.busy || !valid} onClick={() => send(true)}>{t('ia.evict.dry')}</button>296          <ConfirmButton label={t('ia.evict.run')} question={t('ia.evict.q')} onConfirm={() => send(false)} disabled={act.busy || !valid || !ready} danger />297        </div>298        {!ready && <p className="role-note">{t('ia.evict.need')}</p>}299        <div aria-live="polite">300          {act.busy || act.error ? <ActionStatus a={act} /> : null}301          {res && (302            <div className="panel">303              <h3>{res.dry ? t('ia.evict.dryRes') : t('ia.evict.runRes')} ({fmtInt(res.max, lang)})</h3>304              <dl className="stats">305                <Stat label={t('ia.evict.candidates')} value={fmtInt(res.data.candidates, lang)} />306                <Stat label={t('ia.evict.evicted')} value={fmtInt(res.data.evicted, lang)} />307                <Stat label={t('ia.evict.reclaimed')} value={fmtBytes(res.data.reclaimed_bytes, lang)} />308              </dl>309            </div>310          )}311        </div>312      </Requires>313    </>314  );315}316317/** Readable score breakdown: total score, then each component as a bar scaled to the largest value of that component in the result set. */318function ExplainHits({ hits }: { hits: ExplainHit[] }) {319  const { t, lang } = useT();320  if (hits.length === 0) return <p className="muted">{t('adm.empty')}</p>;321  const n3 = (v: number) => fmtNum(v, lang, 3);322  const max = (k: 'bm25' | 'quality' | 'freshness') => hits.reduce((m, h) => Math.max(m, Math.abs(h[k] ?? 0)), 0) || 1;323  const parts = [['bm25', t('ia.ex.bm25')], ['quality', t('ia.ex.quality')], ['freshness', t('ia.ex.fresh')]] as const;324  return (325    <ol className="plain">326      {hits.map((h, i) => (327        <li key={`${h.url}-${i}`} className="hit">328          <div className="hit-head">329            <code>{h.url}</code>330            <span><span className="label">{t('ia.ex.score')} </span><span className="hit-score">{n3(h.score)}</span></span>331          </div>332          <div className="hit-parts">333            {parts.map(([k, label]) => (334              <Gauge key={k} label={label} value={Math.abs(h[k] ?? 0)} max={max(k)} text={n3(h[k])} tone="ink" />335            ))}336          </div>337          {h.explain && (338            <details>339              <summary>{t('ia.ex.explain')}</summary>340              <pre className="explain">{h.explain}</pre>341            </details>342          )}343        </li>344      ))}345    </ol>346  );347}348349function ExplainView() {350  const { t } = useT();351  const id = useId();352  const [req, setReq] = useState<{ q: string; limit: number; n: number } | null>(null);353  // No auto-refresh: the tool runs when asked.354  const state = useAdminFetch<{ hits: ExplainHit[] }>(355    req ? `/api/admin/index/explain?q=${encodeURIComponent(req.q)}&limit=${req.limit}` : null,356    0,357  );358  const submit = (e: FormEvent<HTMLFormElement>) => {359    e.preventDefault();360    const f = new FormData(e.currentTarget);361    const q = String(f.get('q') ?? '').trim();362    const limit = Math.min(20, Math.max(1, Number(f.get('limit')) || 5));363    if (!q) return;364    if (req && req.q === q && req.limit === limit) state.reload();365    else setReq({ q, limit, n: (req?.n ?? 0) + 1 });366  };367  return (368    <>369      <h2>{t('ia.ex.title')}</h2>370      <p className="muted">{t('ia.ex.lead')}</p>371      <form className="row row-end" onSubmit={submit}>372        <div className="field grow">373          <label htmlFor={`${id}-q`}>{t('ia.ex.q')}</label>374          <input id={`${id}-q`} name="q" type="text" required maxLength={256} autoComplete="off" spellCheck={false} />375        </div>376        <div className="field">377          <label htmlFor={`${id}-l`}>{t('ia.ex.limit')}</label>378          <input id={`${id}-l`} name="limit" type="number" min={1} max={20} defaultValue={5} inputMode="numeric" />379        </div>380        <button type="submit" className="btn btn-primary">{t('ia.ex.go')}</button>381      </form>382      {req && (383        <div aria-live="polite">384          <Async state={state}>385            {(d) => (386              <ExplainHits hits={d.hits ?? []} />387            )}388          </Async>389        </div>390      )}391    </>392  );393}394395export default function Admin() {396  const { t } = useT();397  useDocumentTitle(t('ia.title'));398  return (399    <AdminGate title={t('ia.title')} mark={<Mark size={56} />}>400      <AdminTabs401        tabs={[402          { slug: '', label: t('ia.tab.overview'), view: () => <OverviewView /> },403          { slug: 'tombstones', label: t('ia.tab.tombstones'), view: () => <TombstonesView /> },404          { slug: 'purge', label: t('ia.tab.purge'), view: () => <PurgeView /> },405          { slug: 'evict', label: t('ia.tab.evict'), view: () => <EvictView /> },406          { slug: 'explain', label: t('ia.tab.explain'), view: () => <ExplainView /> },407          { slug: 'audit', label: t('ia.tab.audit'), view: () => <AuditLog /> },408        ]}409      />410    </AdminGate>411  );412}413
Files main
Menu

Theme