Skip to content

feat(dashboard): раздел «Квоты провайдеров» — только локальный serve (#168) - #169

Merged
axisrow merged 3 commits into
mainfrom
ao/llm_benchmark-42/provider-quota-ui
Jul 23, 2026
Merged

axisrow merged 3 commits into
mainfrom
ao/llm_benchmark-42/provider-quota-ui

Conversation

@axisrow

@axisrow axisrow commented Jul 23, 2026 •

Copy link
Copy Markdown
Owner

Closes #168

Что

UI-раздел «Квоты провайдеров» на главной дашборда (index.html), рендерится исключительно при локальном запуске (bench.py serve). На GitHub Pages его нет — квоты это личные данные разработчика (расход $, лимиты аккаунтов), на публичной витрине рейтингов им не место.

Backend /api/provider_quota готов с #166; здесь — capabilities-флаг + фронт.

Как определён «локально»

По устоявшемуся паттерну /api/capabilities (модель /api/question-reviews, /api/delete_project):

  • bench.py serve → фронт тянет /api/capabilities, видит provider_quota: true → рендерит раздел (скелетон + кнопка).
  • GitHub Pages → эндпоинта /api/* нет (404) → раздел отсутствует.

UX: загрузка по кнопке, не при page-load

Раздел рендерит скелетон (заголовок + кнопка «Обновить квоты») без данных. Live-квоты грузятся только по явному клику.

Почему: /api/provider_quota дёргает live endpoint'ы провайдеров; для openai/anthropic это OAuth refresh + write-back cred-файла (~/.codex, ~/.claude). refresh_token одноразовый — авто-fetch при каждом просмотре дашборда был бы silent credential mutation. Кнопка делает refresh/write-back осознанным действием (как CLI scripts/provider_quota.py), а не срабатывающим на каждый page load.

Изменения

  • dashboard_server.py: /api/capabilities += provider_quota: true.
  • docs/index.html: canShowQuotas() (best-effort capabilities) → при provider_quota===true рендер скелетона + кнопки; refreshQuotas() по клику → плитки.
    • Плитки: ok (зелёный — тариф + items), error (красный — сообщение), unavailable (серый — причина), not_connected (нейтрально-серый). Read-only, без управления/записи.
    • Все значения через UI.escapeHtml. Переиспользованы premium-card, section-heading, badge-status-*, CSS-переменные.
  • docs/assets/app.css: .quota-tile, .badge-status-neutral, .quota-items/* — минимально поверх существующих токенов.

Тесты

  • tests/test_question_reviews_api.py — /api/capabilities содержит provider_quota: True.
  • tests/test_e2e_dashboard.py::ProviderQuotaLocalE2ETests (Playwright, реальный serve()):
    • скелетон рендерится без авто-данных (нет FIX-риска авто-fetch cred);
    • после клика — плитки всех 4 статусов color-coded;
    • основная разметка (рейтинги/проекты) не сломана, квоты — первая секция.
  • tests/test_e2e_dashboard.py::ProviderQuotaStaticE2ETests (Pages): раздел НЕ рендерится.

Верификация

python -m py_compile dashboard_server.py   # OK
ruff check .                                # All checks passed!
python -m pytest -q                         # 946 passed, 18 skipped

Follow-up (вне scope #168)

Backend readonly-режим credential safety — отдельный follow-up issue: collect_all_quotas(readonly=True) + openai/anthropic handlers не делают refresh/write-back при readonly=True, при истёкшем access → статус «требуется логин». Этот PR фиксит риск на уровне UX (загрузка по кнопке), follow-up закроет его в корне (backend read-only путь).

🤖 Generated with Claude Code

…168)

UI-секция на главной дашборда (index.html), рендерится исключительно при
локальном запуске (bench.py serve). На GitHub Pages её нет — квоты это
личные данные разработчика (расход $, лимиты аккаунтов).

Backend:
- /api/capabilities теперь содержит provider_quota: true (фронт по нему
  понимает, что мы в локальном serve). /api/provider_quota готов с PR #166.

Frontend (docs/index.html + app.css):
- best-effort fetch /api/capabilities → provider_quota===true →
  /api/provider_quota → панель «Квоты провайдеров» вверху страницы.
  На Pages /api/* нет → раздел отсутствует (модель /api/question-reviews).
- Плитки по провайдерам: ok (зелёный, тариф+items), error (красный,
  сообщение), unavailable/not_connected (нейтрально-серый). Read-only.
- XSS-safe через UI.escapeHtml; переиспользованы premium-card, section-heading,
  badge-status-*, существующие CSS-переменные.

Тесты:
- HTTP: /api/capabilities содержит provider_quota: True.
- Локальный E2E (Playwright): панель рендерится, все 4 статуса color-coded,
  /api/provider_quota дёргается (мок _collect_provider_quota), основная
  разметка не сломана, квоты сверху над рейтингом.
- Статический E2E (Pages): раздел НЕ рендерится (нет /api/capabilities).

Co-Authored-By: Claude <noreply@anthropic.com>
@axisrow

axisrow commented Jul 23, 2026

Copy link
Copy Markdown
Owner Author

🔍 Local review (cycle 1)

Reviewed locally (/review + Codex companion sol/xhigh), no bots pinged.

Verdict Reviewer Finding Location
RISK-ACCEPTED codex A read-only page load can rotate and lose CLI credentials (OAuth refresh_token rotation + cred write-back on every /api/provider_quota call) docs/index.html:168
SKIP→cleanup claude Cosmetic: content.firstChild vs prepend; neutral badge label '—' redundant; duplicated heading in renderProviderQuotas; unused muted field in quotaStatusMeta docs/index.html

codex critical — credential rotation (RISK-ACCEPTED by owner)

Claim (verified against code): every successful dashboard load auto-calls /api/provider_quota. The collector (scripts/provider_quota.py) refreshes expired OpenAI/Anthropic OAuth credentials on 401, rotating the documented one-time refresh_token and writing it back to ~/.codex/auth.json / ~/.claude/.credentials.json via _atomic_write. If that write fails, the old on-disk token is already invalidated by the provider and the new one is lost — ordinary dashboard viewing becomes an unexpected credential mutation that can force reauth.

Verification: factual chain confirmed by reading provider_quota.collect_all_quotas → quota_openai_chatgpt/quota_anthropic_claude → _refresh_and_retry → _oauth_refresh + _atomic_write. The refresh_token IS one-time and rotated (PR #166 hardened _atomic_write against exactly this loss). The risk is real.

Owner decision: accept the risk, no fix. Rationale: local serve is single-user (127.0.0.1, same-origin) — whoever runs it IS the admin and already trusts scripts/provider_quota.py with the same credential access from the CLI. The refresh is necessary for live quotas to be visible at all (expired access_token → error instead of data). Follow-up candidates (deferred): (a) make the dashboard quota path read-only at the backend (collect_all_quotas(readonly=True) skips refresh/write-back), or (b) load quotas on explicit button click instead of on page load. Out of scope for #168 (frontend-only issue).

claude — cosmetic findings

Deferred to the final cleanup pass (minor, non-blocking).

Totals: 0 FIX, 1 RISK-ACCEPTED, 1 SKIP (cosmetic).

axisrow and others added 2 commits July 23, 2026 14:24
cycle-review codex critical: авто-fetch /api/provider_quota при каждом
открытии дашборда дёргал live endpoint'ы провайдеров, а для openai/anthropic
это OAuth refresh + write-back cred-файла (~/.codex, ~/.claude). refresh_token
одноразовый — при неудачной _atomic_write старый токен уже инвалидирован
провайдером, новый потерян → повторный логин. Обычный просмотр дашборда
становился silent credential mutation.

Fix (frontend-only, в scope #168): раздел «Квоты» рендерит скелетон
(заголовок + кнопка «Обновить квоты») без данных; live-загрузка — только по
явному клику. refresh/write-back cred теперь осознанное действие (как CLI
scripts/provider_quota.py), не срабатывает на каждый page load.

Backend readonly-режим (collect_all_quotas + handlers не делают refresh при
readonly=True) — отдельный follow-up issue (трогает scripts/provider_quota.py,
вне frontend-scope #168).

Тесты:
- test_quota_section_shell_renders_without_autoload: скелетон без данных,
  плейсхолдер на месте (нет авто-fetch).
- test_quota_panel_renders_all_statuses_on_click: после клика — плитки всех
  статусов color-coded (ok/unavailable/error/not_connected).
- test_no_quota_panel_on_static_pages: на Pages раздела нет (canShowQuotas=false).

Co-Authored-By: Claude <noreply@anthropic.com>
Cycle-review cleanup (non-blocking, round 1+2):
- content.prepend(...) вместо insertBefore(..., content.firstChild) — чище,
  не зависит от ведущего TextNode.
- quota-badge возвращает статус-специфичную метку (OK/Ошибка/—) вместо
  унифицированного «квота» — текст бейджа снова несёт информацию (цвет был
  и так, но текст в cycle-1 fix'е стал одинаковым).

Тесты: 946 passed, 18 skipped (badge-классы не изменились, метки E2E не
проверяет — только классы цвета).

Co-Authored-By: Claude <noreply@anthropic.com>
@axisrow

axisrow commented Jul 23, 2026

Copy link
Copy Markdown
Owner Author

📋 Review summary — all cycles

Reviewed locally (/review + Codex sol/xhigh), 3 rounds. 0 open FIX.

Cycle Reviewer Finding Verdict Resolution
1 codex A read-only page load can rotate and lose CLI credentials (auto-fetch /api/provider_quota → OAuth refresh + cred write-back) FIX Fixed in 50895a3 — quota loading moved to explicit button click
1 claude Cosmetic: firstChild vs prepend; badge label redundant; duplicated heading; unused muted field SKIP Applied in 3f53eb0 (most auto-resolved by the fix; rest in cleanup)
2 codex credential-rotation fix complete — /api/provider_quota only via button click APPROVE —
2 claude badge text «квота» identical across statuses (redundant) SKIP Applied in 3f53eb0 — status-specific labels (OK/Ошибка/—) restored
3 codex safe cosmetic substitutions, no critical issue APPROVE —
3 claude clean — no issues APPROVE —

Totals: 1 FIX (resolved), 2 SKIP (applied), 0 UNVERIFIED.

Follow-up (out of scope #168): backend readonly-credential-safety (collect_all_quotas(readonly=True) skips refresh/write-back) — separate issue. This PR closes the risk at the UX layer (click-to-load); follow-up closes it at the root.

Cycle-review mode: local (review-only on merge — merge is yours to trigger, CI green assumed per local-mode contract).

@axisrow
axisrow merged commit 3ed35b8 into main Jul 23, 2026
1 check passed
@axisrow
axisrow deleted the ao/llm_benchmark-42/provider-quota-ui branch July 23, 2026 06:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UI: раздел «Квоты провайдеров» — только в локальном serve (админ-часть), не на GitHub Pages

1 participant