import React, { useEffect, useMemo, useRef, useState } from 'react'; import { createRoot } from 'react-dom/client'; import { ArrowClockwise, ArrowSquareOut, CaretDown, Check, CheckCircle, CircleNotch, Clipboard, ClockCounterClockwise, DownloadSimple, GithubLogo, Lightning, List, MagnifyingGlass, Moon, Monitor, Play, Stop, Sun, Trash, WarningCircle, } from '@phosphor-icons/react'; import type { Bootstrap, Job, Model, RunConfig, Target, TargetResult } from '../src/types'; import { embedded, subscribeTheme } from './magpie'; import { AppMenu } from './AppMenu'; import { localeFor, type Locale } from './locale'; import './vendor/magpie-ui.css'; import './style.css'; declare global { interface Window { __FINGERPRINT__?: { token?: string; initialProvider?: string; theme?: string; lang?: string }; } } const apiUrl = (path: string) => new URL(path.replace(/^\//, ''), document.baseURI).toString(); const token = () => window.__FINGERPRINT__?.token; async function api(path: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers); if (token()) headers.set('Authorization', `Bearer ${token()}`); if (init?.body) headers.set('content-type', 'application/json'); const r = await fetch(apiUrl(path), { ...init, headers }); if (r.status === 401) location.reload(); if (!r.ok) { const data = await r.json().catch(() => null); throw new Error(data?.error || `${r.status} ${r.statusText}`); } return r.json(); } type Text = { locale: Locale; detect: string; history: string; about: string; settings: string; ready: string; offline: string; start: string; cancel: string; search: string; selected: string; noModels: string; provider: string; model: string; account: string; protocol: string; effort: string; tier: string; strict: string; targetParallel: string; sampleParallel: string; deadline: string; estimated: string; live: string; results: string; candidates: string; details: string; export: string; demo: string; clear: string; completed: string; running: string; failed: string; queued: string; cancelled: string; }; const zh: Text = { locale: 'zh-Hans', detect: '指纹检测', history: '检测历史', about: '关于', settings: '运行设置', ready: '服务已连接', offline: '服务离线', start: '开始检测', cancel: '取消任务', search: '搜索模型', selected: '已选择', noModels: '暂无可用模型', provider: '提供商', model: '模型', account: '账号', protocol: '协议', effort: '推理强度', tier: '服务等级', strict: '完整样本', targetParallel: '模型并行', sampleParallel: '样本并行', deadline: '超时(秒)', estimated: '预计请求', live: '实时进度', results: '检测结果', candidates: '候选排名', details: '样本详情', export: '导出 JSON', demo: '示例数据', clear: '清空选择', completed: '已完成', running: '运行中', failed: '失败', queued: '排队中', cancelled: '已取消', }; const zhHant: Text = { locale: 'zh-Hant', detect: '指紋檢測', history: '檢測歷史', about: '關於', settings: '執行設定', ready: '服務已連線', offline: '服務離線', start: '開始檢測', cancel: '取消任務', search: '搜尋模型', selected: '已選擇', noModels: '暫無可用模型', provider: '提供者', model: '模型', account: '帳號', protocol: '協定', effort: '推理強度', tier: '服務等級', strict: '完整樣本', targetParallel: '模型並行', sampleParallel: '樣本並行', deadline: '逾時(秒)', estimated: '預計請求', live: '即時進度', results: '檢測結果', candidates: '候選排名', details: '樣本詳情', export: '匯出 JSON', demo: '示例資料', clear: '清除選擇', completed: '已完成', running: '執行中', failed: '失敗', queued: '排隊中', cancelled: '已取消', }; const en: Text = { locale: 'en', detect: 'Fingerprint', history: 'History', about: 'About', settings: 'Run settings', ready: 'Service connected', offline: 'Service offline', start: 'Start detection', cancel: 'Cancel job', search: 'Search models', selected: 'selected', noModels: 'No models available', provider: 'Provider', model: 'Model', account: 'Account', protocol: 'Protocol', effort: 'Reasoning effort', tier: 'Service tier', strict: 'Complete samples', targetParallel: 'Model parallelism', sampleParallel: 'Sample parallelism', deadline: 'Deadline (sec)', estimated: 'Estimated requests', live: 'Live progress', results: 'Results', candidates: 'Candidate ranking', details: 'Sample details', export: 'Export JSON', demo: 'Demo data', clear: 'Clear selection', completed: 'Completed', running: 'Running', failed: 'Failed', queued: 'Queued', cancelled: 'Cancelled', }; const terminal = (state: string) => !['queued', 'running'].includes(state); const integerInRange = (value: unknown, min: number, max: number) => Number.isInteger(Number(value)) && Number(value) >= min && Number(value) <= max; const stateLabel = (t: Text, state: string) => ({ completed: t.completed, running: t.running, failed: t.failed, queued: t.queued, cancelled: t.cancelled, interrupted: t.locale === 'en' ? 'Interrupted' : t.locale === 'zh-Hant' ? '已中斷' : '已中断', scored: t.locale === 'en' ? 'Scored' : t.locale === 'zh-Hant' ? '已評分' : '已评分', partial: t.locale === 'en' ? 'Partial' : t.locale === 'zh-Hant' ? '部分樣本' : '部分样本', unscorable: t.locale === 'en' ? 'Unscorable' : t.locale === 'zh-Hant' ? '不可評分' : '不可评分', not_model: t.locale === 'en' ? 'Unexpected sequence' : t.locale === 'zh-Hant' ? '序列不符合檢測假設' : '序列不符合检测假设', complete: t.locale === 'en' ? 'Complete' : t.locale === 'zh-Hant' ? '完成' : '完成', truncated: t.locale === 'en' ? 'Truncated' : t.locale === 'zh-Hant' ? '已截斷' : '已截断', waiting: t.locale === 'en' ? 'Waiting' : t.locale === 'zh-Hant' ? '等待回應' : '等待响应', streaming: t.locale === 'en' ? 'Streaming' : t.locale === 'zh-Hant' ? '接收中' : '接收中', })[state] || state; const localize = (t: Text, hans: string, hant: string, english: string) => t.locale === 'en' ? english : t.locale === 'zh-Hant' ? hant : hans; function App() { const [lang, setLang] = useState(() => { try { const saved = !embedded ? localStorage.getItem('fp-lang') : null; return localeFor(saved || window.__FINGERPRINT__?.lang); } catch { return localeFor(window.__FINGERPRINT__?.lang); } }); const t = lang === 'en' ? en : lang === 'zh-Hant' ? zhHant : zh; const [theme, setTheme] = useState<'light' | 'dark' | 'system'>(() => { try { return ( (!embedded && (localStorage.getItem('fp-theme') as any)) || window.__FINGERPRINT__?.theme || 'system' ); } catch { return (window.__FINGERPRINT__?.theme as 'light' | 'dark') || 'system'; } }); const [boot, setBoot] = useState(null); const [error, setError] = useState(''); const [section, setSection] = useState<'detect' | 'history' | 'about'>('detect'); const [job, setJob] = useState(null); const [history, setHistory] = useState([]); const [query, setQuery] = useState(''); const [provider, setProvider] = useState('all'); const [selected, setSelected] = useState([]); const [account, setAccount] = useState(''); const [config, setConfig] = useState({ api: 'auto', effort: '', serviceTier: 'default', strict: false, targetParallel: 2, sampleParallel: 3, deadlineSeconds: 300, } as any); const [showAdvanced, setShowAdvanced] = useState(false); const [expanded, setExpanded] = useState(null); const [starting, setStarting] = useState(false); const [downloadingBank, setDownloadingBank] = useState(false); const configValid = integerInRange(config.targetParallel, 1, 3) && integerInRange(config.sampleParallel, 1, 3) && integerInRange(config.deadlineSeconds, 10, 900); useEffect(() => { const media = matchMedia('(prefers-color-scheme: dark)'); const paint = () => { document.documentElement.dataset.theme = theme === 'system' ? (media.matches ? 'dark' : 'light') : theme; }; paint(); media.addEventListener('change', paint); try { if (!embedded) localStorage.setItem('fp-theme', theme); } catch {} return () => media.removeEventListener('change', paint); }, [theme]); useEffect(() => { document.documentElement.lang = lang; try { if (!embedded) localStorage.setItem('fp-lang', lang); } catch {} }, [lang]); useEffect(() => { const onMessage = (e: MessageEvent) => { if (e.source !== window.parent) return; const m = e.data; if (m?.magpie === 1 && m.event === 'action' && m.data?.provider?.id) { setProvider(m.data.provider.id); setSection('detect'); } }; window.addEventListener('message', onMessage); return () => window.removeEventListener('message', onMessage); }, []); useEffect( () => subscribeTheme((next) => { setTheme(next.dark ? 'dark' : 'light'); const locale = localeFor(next.lang); document.documentElement.lang = locale; setLang(locale); }), [], ); const load = async () => { setError(''); try { const b = await api('api/bootstrap'); setBoot(b); setHistory(b.jobs || []); setJob((current) => current || b.jobs.find((j) => !terminal(j.state)) || null); if (window.__FINGERPRINT__?.initialProvider) setProvider(window.__FINGERPRINT__.initialProvider); setError(b.gateway.error || ''); } catch (e) { setError(String(e)); } }; const downloadBank = async () => { if (downloadingBank) return; setDownloadingBank(true); setError(''); try { const result = await api & { error?: string }>( 'api/bank/download', { method: 'POST' }, ); setBoot((current) => current ? { ...current, bank: result.bank, bankStatus: result.bankStatus, bankError: result.error, } : current, ); if (result.error) setError(result.error); } catch (e) { setError(String(e)); } finally { setDownloadingBank(false); } }; useEffect(() => { load(); }, []); useEffect(() => { if (!job || terminal(job.state)) return; const controller = new AbortController(); const id = job.id; const watch = async () => { let done = false; while (!controller.signal.aborted && !done) { try { const response = await fetch(apiUrl(`api/jobs/${id}/events`), { headers: { Authorization: `Bearer ${token()}` }, signal: controller.signal, }); if (response.status === 401) location.reload(); if (!response.ok || !response.body) throw new Error(`Progress connection: HTTP ${response.status}`); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; try { while (!controller.signal.aborted) { const part = await reader.read(); if (part.done) break; buffer += decoder.decode(part.value, { stream: true }); let split: number; while ((split = buffer.indexOf('\n\n')) >= 0) { const event = buffer.slice(0, split); buffer = buffer.slice(split + 2); const data = event.split('\n').find((line) => line.startsWith('data: ')); if (!data) continue; const next = JSON.parse(data.slice(6)) as Job; setJob((current) => (current?.id === id ? next : current)); setHistory((list) => [next, ...list.filter((j) => j.id !== id)]); done = terminal(next.state); } } } finally { await reader.cancel().catch(() => {}); } } catch (e) { if (!controller.signal.aborted) setError(String(e)); } if (!done && !controller.signal.aborted) await new Promise((resolve) => setTimeout(resolve, 1500)); } }; void watch(); return () => controller.abort(); }, [job?.id]); const models = boot?.models || []; const providers = useMemo( () => ['all', ...Array.from(new Set(models.map((m) => m.provider)))], [models], ); const filtered = models.filter( (m) => (provider === 'all' || m.provider === provider) && `${m.name} ${m.id}`.toLowerCase().includes(query.toLowerCase()), ); const selectedModels = models.filter((m) => selected.includes(m.id)); const effortChoices = selectedModels[0]?.efforts.filter((effort) => selectedModels.every((model) => model.efforts.includes(effort)), ) || []; const effort = effortChoices.includes(config.effort) ? config.effort : ''; const estimate = selected.length * 3; const toggle = (id: string) => setSelected((s) => s.includes(id) ? s.filter((x) => x !== id) : s.length < 24 ? [...s, id] : s, ); const setField = (k: string, v: any) => setConfig((c: any) => ({ ...c, [k]: v })); const start = async () => { if (!selected.length || starting) return; if (account && new Set(selectedModels.map((m) => m.provider)).size > 1) { setError( localize( t, '固定账号时请只选择同一提供商的模型。', '固定帳號時請只選擇同一提供者的模型。', 'Select models from one provider when pinning an account.', ), ); return; } setStarting(true); setError(''); const cfg: RunConfig = { targets: selected.map((model) => ({ model, ...(account ? { account } : {}) })), api: config.api, effort, serviceTier: config.serviceTier, strict: config.strict, targetParallel: Number(config.targetParallel), sampleParallel: Number(config.sampleParallel), deadlineSeconds: Number(config.deadlineSeconds), }; try { const j = await api('api/jobs', { method: 'POST', body: JSON.stringify(cfg) }); setJob(j); setHistory((h) => [j, ...h.filter((x) => x.id !== j.id)]); setExpanded(j.results[0]?.id || null); } catch (e) { setError(String(e)); } finally { setStarting(false); } }; const cancel = async (id: string) => { try { const x = await api(`api/jobs/${id}/cancel`, { method: 'POST' }); setJob((current) => (current?.id === id ? x : current)); setHistory((list) => list.map((item) => (item.id === id ? x : item))); } catch (e) { setError(String(e)); } }; const download = async (id: string) => { try { const r = await fetch(apiUrl(`api/jobs/${id}/export`), { headers: token() ? { Authorization: `Bearer ${token()}` } : {}, }); if (!r.ok) throw new Error('Export failed'); const blob = await r.blob(); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `fingerprint-${id}.json`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); } catch (e) { setError(String(e)); } }; const deleteJob = async (id: string) => { try { await api(`api/jobs/${id}`, { method: 'DELETE' }); setHistory((h) => h.filter((x) => x.id !== id)); if (job?.id === id) setJob(null); } catch (e) { setError(String(e)); } }; return (
{!embedded &&

Fingerprint

}
{boot?.demo ? ( {t.demo} ) : ( {!boot ? error ? t.offline : localize(t, '正在连接…', '正在連線…', 'Connecting…') : boot.gateway.reachable ? t.ready : t.offline} )} {!embedded && ( <> )}
{error && (
{error}
)} {section === 'history' ? ( ) : section === 'about' ? ( ) : ( <>

{localize( t, '选择模型,用同一组挑战比较响应指纹。', '選擇模型,用同一組挑戰比較回應指紋。', 'Select models to compare their fingerprints with shared challenges.', )}

{boot?.bank ? ( {localize(t, '参考库', '參考庫', 'Reference bank')} ·{' '} {boot.bank.modelCount ?? '—'} {localize(t, '个模型', '個模型', 'models')} ) : ( {boot?.bankStatus?.state === 'cached' ? localize( t, '参考数据已缓存,将在运行时读取', '參考資料已快取,執行時讀取', 'Reference data cached; it will be read when a run starts', ) : localize( t, '参考数据未下载', '參考資料尚未下載', 'Reference data not downloaded', )} )} {boot?.bankError && ( {boot.bankError} )}

{localize( t, '默认参考源:lm.ikale.io,备用 cdn.jsdmirror.com。仅主动下载或无缓存时启动检测才会连接;来源站点会看到 IP,不接收凭证、提示词或模型回答。', '預設參考來源:lm.ikale.io,備用 cdn.jsdmirror.com。僅主動下載或無快取時開始檢測才會連線;來源網站會看到 IP,不接收憑證、提示詞或模型回答。', 'Default reference sources: lm.ikale.io, with cdn.jsdmirror.com as fallback. Contacted only on download or an uncached run; these hosts see your IP, but receive no credentials, prompts or replies.', )}

{boot?.demo && (
{localize( t, '示例数据,可直接试用检测流程。', '示例資料,可直接試用檢測流程。', 'Demo data. Try the detection workflow.', )}
)}

{localize(t, '选择模型', '選擇模型', 'Models')}{' '} {models.length}

{selected.length} {t.selected}
setQuery(e.target.value)} />
({ value: p, label: p === 'all' ? t.provider : p, }))} onChange={setProvider} />
{filtered.length ? ( filtered.map((m) => ( )) ) : (

{boot ? t.noModels : localize( t, '正在加载模型与参考库…', '正在載入模型與參考庫…', 'Loading models and reference data…', )}

)}

{t.settings}

{localize(t, '完整样本', '完整樣本', 'Complete samples')} {localize( t, '仅接受完整的 3 条采样', '僅接受完整的 3 條取樣', 'Require all three samples', )}
{showAdvanced && (
{!configValid && (

{localize( t, '并行数须为 1–3 的整数,超时须为 10–900 的整数秒。', '並行數須為 1–3 的整數,逾時須為 10–900 的整數秒。', 'Parallelism must be an integer from 1–3; deadline must be 10–900 whole seconds.', )}

)}
)}
{t.estimated} {estimate} 3 × {selected.length || 0}
{job && ( cancel(job.id)} onDownload={() => download(job.id)} /> )} )}
); } function JobView({ job, t, expanded, setExpanded, onCancel, onDownload, }: { job: Job; t: Text; expanded: string | null; setExpanded: (x: string | null) => void; onCancel: () => void; onDownload: () => void; }) { const [showExport, setShowExport] = useState(false); const [copied, setCopied] = useState(false); const exportArea = useRef(null); const total = job.results.length || job.config.targets.length; const done = job.results.filter((r) => r.state === 'completed').length; const finishedSamples = job.results .flatMap((r) => r.samples) .filter((s) => !['queued', 'waiting', 'streaming'].includes(s.state)).length; const json = JSON.stringify({ schema: 'magpie-fingerprint/v1', ...job }, null, 2); const copy = async () => { try { if (!navigator.clipboard) throw new Error('Clipboard unavailable'); await navigator.clipboard.writeText(json); setCopied(true); } catch { exportArea.current?.focus(); exportArea.current?.select(); setCopied(document.execCommand('copy')); } }; return (

{terminal(job.state) ? t.results : t.live}

{job.state === 'running' && }{' '} {stateLabel(t, job.state)} {['queued', 'running'].includes(job.state) ? ( ) : ( )}
{finishedSamples}/{total * 3}{' '} {localize(t, '条采样已结束', '條取樣已結束', 'samples finished')} · {done}/{total}{' '} {localize(t, '个模型完成', '個模型完成', 'models completed')} {job.demo && {t.demo}} {new Date(job.createdAt).toLocaleString()}
{localize(t, '参考库', '參考庫', 'Reference')}: {job.bank.builtAt.slice(0, 19)} SDK {job.bank.sdk} {job.config.effort || 'default'} · {job.config.serviceTier}
{job.error && (
{job.error}
)}
{localize( t, '本批次共享的 3 个挑战', '本批次共用的 3 個挑戰', 'Three challenges shared across this batch', )} {job.challenges.map((c, i) => (
{i + 1} · {c.expected_count} {localize(t, '个数字', '個數字', 'numbers')}

{c.prompt}

))}
{job.results.map((r: TargetResult) => ( setExpanded(expanded === r.id ? null : r.id)} /> ))} {showExport && (
{ if (e.key === 'Escape') setShowExport(false); }} >
{t.export}