File size: 11,551 Bytes
ffba252
 
 
 
 
 
 
 
 
 
 
ee20373
 
 
 
 
ffba252
 
 
 
ee20373
 
 
 
 
 
 
 
 
ffba252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee20373
 
ffba252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee20373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee20373
ffba252
 
 
 
 
 
 
ee20373
ffba252
ee20373
ffba252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee20373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba252
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import { useState, useEffect, useCallback } from 'react'

interface ProviderStatus {
  name: string
  key: string
  modelCount: number
  lastUpdated: string | null
  hasScript: boolean
  refreshing: boolean
}

interface BenchmarkSourceStatus {
  key: string
  refreshing: boolean
}

interface BenchmarkStatus {
  entryCount: number
  lastUpdated: string | null
  refreshing: boolean
  sources?: BenchmarkSourceStatus[]
}

const BENCHMARK_SOURCE_NAMES: Record<string, string> = {
  llmstats:  'LLMStats',
  hf:        'HF Leaderboard',
  livebench: 'LiveBench',
  arena:     'Chatbot Arena',
  aider:     'Aider',
}

interface FetchResult {
  provider: string
  success: boolean
  error?: string
}

function formatAge(iso: string | null): string {
  if (!iso) return 'never'
  const diff = Date.now() - new Date(iso).getTime()
  const mins = Math.floor(diff / 60000)
  const hours = Math.floor(mins / 60)
  const days = Math.floor(hours / 24)
  if (days > 0) return `${days}d ago`
  if (hours > 0) return `${hours}h ago`
  if (mins > 0) return `${mins}m ago`
  return 'just now'
}

interface Props {
  onClose: () => void
  onDataUpdated: () => void
}

export function ManagementPanel({ onClose, onDataUpdated }: Props) {
  const [providers, setProviders] = useState<ProviderStatus[]>([])
  const [benchmarks, setBenchmarks] = useState<BenchmarkStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [results, setResults] = useState<Record<string, { success: boolean; error?: string }>>({})
  const [bmResult, setBmResult] = useState<{ success: boolean; error?: string } | null>(null)
  const [bmSourceResults, setBmSourceResults] = useState<Record<string, { success: boolean; error?: string }>>({})
  const [refreshingBmSource, setRefreshingBmSource] = useState<Record<string, boolean>>({})
  const [refreshingAll, setRefreshingAll] = useState(false)
  const [serverAvailable, setServerAvailable] = useState(true)

  const fetchStatus = useCallback(async () => {
    try {
      const res = await fetch('/api/status')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      const data = await res.json()
      setProviders(data.providers)
      if (data.benchmarks) setBenchmarks(data.benchmarks)
      setServerAvailable(true)
      setError(null)
    } catch (e: any) {
      setServerAvailable(false)
      setError('Management server not running. Start it with: node server.js')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchStatus()
  }, [fetchStatus])

  const refreshProvider = async (key: string, name: string) => {
    setProviders((prev) =>
      prev.map((p) => (p.name === name ? { ...p, refreshing: true } : p))
    )
    setResults((r) => ({ ...r, [name]: { success: false } }))

    try {
      const res = await fetch(`/api/fetch/${key}`, { method: 'POST' })
      const data: FetchResult = await res.json()
      setResults((r) => ({ ...r, [name]: { success: data.success, error: data.error } }))
      if (data.success) onDataUpdated()
    } catch {
      setResults((r) => ({ ...r, [name]: { success: false, error: 'Request failed' } }))
    }

    await fetchStatus()
  }

  const refreshBenchmarks = async () => {
    setBenchmarks((b) => b ? { ...b, refreshing: true } : null)
    setBmResult(null)
    try {
      const res = await fetch('/api/fetch/benchmarks', { method: 'POST' })
      const data = await res.json()
      setBmResult({ success: data.success, error: data.error })
      if (data.success) onDataUpdated()
    } catch {
      setBmResult({ success: false, error: 'Request failed' })
    }
    await fetchStatus()
  }

  const refreshBenchmarkSource = async (source: string) => {
    setRefreshingBmSource((s) => ({ ...s, [source]: true }))
    setBmSourceResults((r) => ({ ...r, [source]: { success: false } }))
    try {
      const res = await fetch(`/api/fetch/benchmarks/${source}`, { method: 'POST' })
      const data = await res.json()
      setBmSourceResults((r) => ({ ...r, [source]: { success: data.success, error: data.error } }))
      if (data.success) onDataUpdated()
    } catch {
      setBmSourceResults((r) => ({ ...r, [source]: { success: false, error: 'Request failed' } }))
    }
    setRefreshingBmSource((s) => ({ ...s, [source]: false }))
    await fetchStatus()
  }

  const refreshAll = async () => {
    setRefreshingAll(true)
    setResults({})
    try {
      const res = await fetch('/api/fetch', { method: 'POST' })
      const data = await res.json()
      const resultMap: Record<string, { success: boolean; error?: string }> = {}
      for (const r of data.results ?? []) {
        resultMap[r.provider] = { success: r.success, error: r.error }
      }
      setResults(resultMap)
      onDataUpdated()
    } catch {
      setError('Refresh all failed')
    }
    setRefreshingAll(false)
    await fetchStatus()
  }

  const scriptCount = providers.filter((p) => p.hasScript).length

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>Data Management</h2>
          <button className="modal-close" onClick={onClose}></button>
        </div>

        {!serverAvailable && (
          <div className="server-warning">
            <strong>Management server offline.</strong> Run <code>node server.js</code> in the project root to enable live updates.
          </div>
        )}

        {loading && <div className="panel-loading">Loading status…</div>}

        {!loading && serverAvailable && (
          <>
            <div className="panel-actions">
              <button
                className="btn-refresh-all"
                onClick={refreshAll}
                disabled={refreshingAll || scriptCount === 0}
              >
                {refreshingAll ? '⟳ Refreshing all…' : `⟳ Refresh all (${scriptCount} providers)`}
              </button>
            </div>

            <table className="management-table">
              <thead>
                <tr>
                  <th>Provider</th>
                  <th>Models</th>
                  <th>Last updated</th>
                  <th>Status</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {providers.map((p) => {
                  const result = results[p.name]
                  const isRefreshing = p.refreshing || refreshingAll
                  return (
                    <tr key={p.name}>
                      <td className="mgmt-provider">{p.name}</td>
                      <td className="mgmt-count">{p.modelCount}</td>
                      <td className="mgmt-age">{formatAge(p.lastUpdated)}</td>
                      <td className="mgmt-status">
                        {result ? (
                          result.success ? (
                            <span className="badge-ok">✓ updated</span>
                          ) : (
                            <span className="badge-err" title={result.error}>✗ failed</span>
                          )
                        ) : (
                          <span className={`badge-script ${p.hasScript ? 'has-script' : 'manual'}`}>
                            {p.hasScript ? 'auto' : 'manual'}
                          </span>
                        )}
                      </td>
                      <td>
                        {p.hasScript && (
                          <button
                            className="btn-refresh"
                            onClick={() => refreshProvider(p.key, p.name)}
                            disabled={isRefreshing}
                          >
                            {isRefreshing ? '⟳' : '↻'}
                          </button>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>

            {benchmarks && (
              <>
                <h3 className="mgmt-section-heading">Benchmark Data</h3>
                <table className="management-table">
                  <thead>
                    <tr>
                      <th>Source</th>
                      <th>Entries</th>
                      <th>Last updated</th>
                      <th>Status</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* All-sources row */}
                    <tr>
                      <td className="mgmt-provider">All sources</td>
                      <td className="mgmt-count">{benchmarks.entryCount.toLocaleString()}</td>
                      <td className="mgmt-age">{formatAge(benchmarks.lastUpdated)}</td>
                      <td className="mgmt-status">
                        {bmResult ? (
                          bmResult.success ? (
                            <span className="badge-ok">✓ updated</span>
                          ) : (
                            <span className="badge-err" title={bmResult.error}>✗ failed</span>
                          )
                        ) : (
                          <span className="badge-script has-script">auto</span>
                        )}
                      </td>
                      <td>
                        <button
                          className="btn-refresh"
                          onClick={refreshBenchmarks}
                          disabled={benchmarks.refreshing}
                        >
                          {benchmarks.refreshing ? '⟳' : '↻'}
                        </button>
                      </td>
                    </tr>
                    {/* Per-source rows */}
                    {(benchmarks.sources ?? []).map((src) => {
                      const result = bmSourceResults[src.key]
                      const isRefreshing = src.refreshing || refreshingBmSource[src.key]
                      return (
                        <tr key={src.key}>
                          <td className="mgmt-provider mgmt-source-indent">
                            {BENCHMARK_SOURCE_NAMES[src.key] ?? src.key}
                          </td>
                          <td className="mgmt-count"></td>
                          <td className="mgmt-age"></td>
                          <td className="mgmt-status">
                            {result ? (
                              result.success ? (
                                <span className="badge-ok">✓ updated</span>
                              ) : (
                                <span className="badge-err" title={result.error}>✗ failed</span>
                              )
                            ) : null}
                          </td>
                          <td>
                            <button
                              className="btn-refresh"
                              onClick={() => refreshBenchmarkSource(src.key)}
                              disabled={isRefreshing}
                            >
                              {isRefreshing ? '⟳' : '↻'}
                            </button>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </>
            )}
          </>
        )}

        {error && !loading && <div className="panel-error">{error}</div>}
      </div>
    </div>
  )
}