feat: аналитика токенов — разбивка стоимости, сравнение подписок, поддержка OpenCode#17
Closed
NovakPAai wants to merge 1 commit into
Closed
Conversation
…Code support Add comprehensive cost analytics to the dashboard: - Token type breakdown (input/output/cache_read/cache_write) - Context window utilization percentage (avg across all turns) - Multi-period subscription vs API cost comparison with ROI - Per-agent cost breakdown chart - Data coverage transparency (which agents have real/estimated/no data) - OpenCode real token data support via SQLite batch query - SQL injection protection for OpenCode session IDs - Daily spend rate calculation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Owner
|
Closing — tracked as issue #18. The analytics overhaul is a good idea but needs to be done incrementally. Current PR conflicts with recent performance changes in data.js. |
3 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
feat: аналитика токенов — разбивка стоимости, сравнение подписок, поддержка OpenCode
Что сделано
Что изменилось
src/data.js(+183 строки)computeSessionCost()— расширенная сигнатура возврата:tokens.input/output,tokens.cache.read/write/^[a-zA-Z0-9_-]+$/перед shell-выполнениемgetCostAnalytics()— новые поля агрегации:totalInputTokens,totalOutputTokens,totalCacheReadTokens,totalCacheCreateTokensavgContextPct,dailyRate,firstDate,lastDate,daysbyAgent(стоимость/сессии/токены/estimated по каждому агенту),agentNoCostDatasessionsWithDataзаменяетsessions.lengthдляtotalSessionsexecSyncна все сессии вместо O(n)src/frontend/app.js(+193 строки)getSubscriptionConfig()с миграцией из старого формата{plan, paid}→ новый{entries: [{plan, paid, from}]};addSubEntry()/removeSubEntry()с сортировкой по датеsrc/frontend/styles.css(+200 строк).coverage-ok,.coverage-est,.coverage-none)Как это работает
Разбивка токенов
Каждое assistant-сообщение в Claude Code JSONL содержит
usage.input_tokens,usage.output_tokens,usage.cache_creation_input_tokens,usage.cache_read_input_tokens. Теперь они трекаются раздельно и отображаются в виде сетки из 5 карточек с процентами.Токены OpenCode
loadOpenCodeDetail()уже читаетmsgData.tokensиз SQLite, но не использует для расчёта стоимости. Новый код читаетtokens.input,tokens.output,tokens.reasoning,tokens.cache.read,tokens.cache.writeи применяет ценообразование черезmsgData.modelID.Для аналитики один batch-запрос выбирает ВСЕ assistant-сообщения OpenCode разом:
Результаты кэшируются в
opencodeCostCacheи переиспользуются в основном цикле.Сравнение с подпиской
Пользователь добавляет периоды оплаты через localStorage (
codedash-subscription):{ "entries": [{ "plan": "Pro", "paid": 20, "from": "2025-01-01" }, { "plan": "Max", "paid": 100, "from": "2025-03-01" }] }UI показывает: сумму оплаченного vs API-эквивалент, экономию/переплату, множитель ROI, прогресс-бар.
Контекстное окно
avgContextPct = sum(per-turn context%) / turnCount, где per-turn context =input + cache_create + cache_readкак процент от 200K.Ограничения
modelID: фоллбэк на дефолтный прайсинг, помечен как ~est.Тест-план
node bin/cli.js run --port=3333, убедиться что вкладка Cost Analytics загружаетсяCloses #18