commit 7850e0d21e90309e99c561371a1b4891bb9fb0cb Author: Vassiliy Yegorov Date: Thu Nov 26 22:05:28 2026 +0700 cost-balance-footer 1.10.7: spending, tokens, cache, limits and CBR rates in SQLite diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8b56f7f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +.DS_Store +*.log +.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..a62ae40 --- /dev/null +++ b/README.md @@ -0,0 +1,349 @@ +# cost-balance-footer + +Показатели в нижней строке под полем ввода: + +- **Расход ≈ …** — оценка стоимости сессии по прайсу DeepSeek (только для + маршрутов `deepseek-account` / `deepseek-official`). +- **… ₽ (… ₽)** — остаток денег без подписи, только иконка: кошельки аккаунта + DeepSeek, а когда выбрана модель стороннего оператора — его кошелёк, + полученный Host-половиной плагина. У OpenRusRouter это баланс всего кошелька + (`account_balance`), а не остаток под лимитом ключа: лимит меняется в кабинете + и не должен выглядеть как трата. В скобках — остаток под лимитом ключа + (`limit − usage`, не меньше нуля); если лимит у ключа не задан, в скобках + остаётся имя провайдера (`DeepSeek` для аккаунта DeepSeek, `OpenRusRouter` — + displayName оператора). Имя провайдера есть в подсказке при наведении в обоих + случаях, как и сумма под лимитом. +- **… ₽** — остаток на сегодняшний день от дневного лимита без подписи: иконка + часов и сумма; цвет по проценту расхода, клик открывает статистику. + +## Статистика, лимиты и цвета + +В Settings → **Статистика** четыре вкладки: **Потребление** (деньги), **Токены**, +**Кеш** и **Правка истории**. Переключатель периода (день / неделя / месяц) общий +для всех. + +**Потребление** — расход за день, неделю и месяц: + +- переключатель периода и три карточки с суммой, лимитом и двухцветной + полосой прогресса; +- график: за день — 24 столбика по часам, за неделю и месяц — по дням; + на ненулевых столбиках написано значение — целое число без копеек и без + знака валюты; нулевые часы и дни не рисуются и не подписываются, а доля + меньше половины единицы не подписывается, чтобы на графике не появлялся + «0»; значения пишутся **над** столбиками, а соседние подписи стоят на двух + уровнях (2 и 14 px над верхом), чтобы не накладываться друг на друга; + дни, вышедшие за дневной лимит, помечены красным сверху; + клик по столбику раскрывает выбранный день по часам; +- поля условных лимитов **провайдера** (в валюте его кошелька) и кнопка + «Заполнить из месячного» (день = месяц / 30, неделя = месяц × 7 / 30). + +**Токены** — сколько токенов израсходовано за выбранный период: карточки «Вход» +(без кеша, с отдельной строкой про кеш-запись), «Из кеша» и «Выход», сумма +токенов за период, график по часам или дням и таблица по моделям (вход / кеш / +выход). Считаются все маршруты, не только DeepSeek: цены тут не нужны. + +**Кеш** — доля входного трафика, обслуженного из кеша: процент, сколько токенов +пришло из кеша и сколько мимо, график доли по часам или дням (шкала 0–100 %) и +та же таблица по моделям с долей кеша. Доля считается как +`из кеша / (вход + кеш-запись + из кеша)`; выход в знаменатель не входит. + +Высота модалки фиксируется по самой высокой вкладке — «Потреблению»: панель +измеряет её, пока та на экране, и держит этот размер для остальных вкладок +(запас только растёт, поэтому раскрытый день или другой период не сжимают окно +под курсором). В разделе настроек тот же компонент ведёт себя так же. + +Токенная история начинается с момента установки этой версии плагина и пишется, +пока приложение открыто: проекция `tokenUsage` приходит из сессии, и плагин +раскладывает её приращения по часам (только приращения — «первый взгляд» на +сессию в общую историю не попадает, иначе очистка кеша браузера записала бы ту +же сессию второй раз). + +**Валюта и курс ЦБ.** Оператор биллингуется в рублях, кошелёк DeepSeek — в +долларах или юанях. Чтобы рублёвая статистика не теряла траты после переключения +на DeepSeek, плагин пересчитывает их в рубли по курсу Центрального банка +(`cbr-xml-daily.ru`, публикуется раз в рабочий день). Курс забирает и кэширует +Host-половина: не чаще раза в сутки, с запасом в SQLite (`fx_rates`), поэтому +при недоступной сети остаются последние известные значения, а не нули. В +рублёвых суммах (карточки, графики, остаток дня) складываются все валюты по +курсу; вид в долларах или юанях остаётся «сырым», без обратного пересчёта. +Исторические суммы конвертируются по текущему дневному курсу — это оценка, а не +бухгалтерская выписка. Если курса валюты ещё нет, она не попадает в рублёвую +сумму, а под карточками появляется строка «Курса USD пока нет…»; когда курс +получен, там же выводится «Курс ЦБ: USD 80,50 ₽ · CNY 11,23 ₽». + +**Как считается расход.** Плагин не угадывает цены токенов у сторонних шлюзов: +каждое успешное чтение баланса — это проба, но расход считается не по остатку +под лимитом ключа, а по счётчику реальных списаний шлюза (`usage`). Остаток под +лимитом — это `min(баланс кошелька, остаток лимита)`, поэтому правка лимита в +панели биллинга двигала его без единого оплаченного запроса, и плагин +засчитывал разницу как трату. Метр трат выбирается по порядку: счётчик `usage` +из ответа шлюза; иначе — баланс всего кошелька (`account_balance`), который +уменьшается только от реальных списаний (пополнение его поднимает, и такая проба +просто переякоривается); и только если шлюз не отдаёт ни того, ни другого — +остаток, но лишь пока лимит, от которого он посчитан, не менялся. Метр +сравнивается только с пробой той же природы (то же окно лимита, тот же лимит), +поэтому смена окна или лимита пересоздаёт пробу, а не выдумывает трату. Дельта +распределяется по часам, прошедшим с предыдущей пробы (не более 72 часов), +чтобы пропуск в работе приложения не превращался в один столбик. История +живёт в SQLite на машине, а не в браузере — `~/.dsh/storages/cost-balance.sqlite`, +см. «Где хранится история» (сбор начинается с момента установки этой версии +плагина; всё, что списано раньше, неизвестно). Кнопка «Сбросить историю» на +вкладке «Правка истории» стирает записанные суммы и токены, сохраняя лимиты; ею +же убираются суммы, которые старая версия записала при правке лимита. + +**Ручная правка истории.** На одноимённой вкладке выбираете день и вводите итог +за этот день; там же — кнопка «Сбросить историю». Записанные часы этого дня +заменяются одной суммой, распределённой по уже прошедшим часам (за прошлый день — +по всем 24, за сегодня — по текущий час, чтобы сумма сразу попала в остаток дня). +Ноль очищает день. Так заполняется история за дни, когда плагин ещё не собирал +данные: например, 280 ₽ за вчера и 25 ₽ за сегодня. + +**Полоска и перерасход.** В полосе под суммой синий — расход в пределах лимита, +красный — перерасход. Шкала нормируется на большее из двух: пока расход ниже +лимита, полоса синяя и заполняется по проценту от лимита; после выхода за +лимит синяя часть упирается ровно в уровень лимита, а остаток полосы красный — +красная доля и есть то, насколько расход вышел за лимит. Это работает для дня, +недели и месяца одинаково: полоса больше не обрезается на 100 % и не +перекрашивается целиком. Численно перерасход виден и текстом: под суммой +вместо «из 1 000 ₽» появляется «перерасход 200 ₽ из 1 000 ₽», а в строке +выбранного периода — то же вместо «осталось 0 ₽ из 1 000 ₽». До лимита всё +по-прежнему: синяя полоса и «осталось 750 ₽ из 1 000 ₽». + +**Дни с перерасходом.** В недельном и месячном графике столбик дня, который вышел +за дневной лимит, двухцветный: синий до уровня дневного лимита, красный выше — +та же логика, что и в полосе карточки. Подсказка по наведению добавляет сумму: +«9.11 — 780 ₽, перерасход 380 ₽», а под графиком появляется пояснение «Красное +в столбике — часть выше дневного лимита». В дневном графике по часам подсветки +нет: лимит задан на день, а не на час. + +**Строка статуса.** Баланс остаётся нейтральным серым, как раньше, и по клику +обновляется; подписи «Баланс» больше нет — только иконка, сумма кошелька и в +скобках остаток под лимитом ключа. Справа от него тем же шрифтом и размером +выводится остаток на день — просто `410 ₽`, без слова «День:» — и он +окрашивается по проценту использованного дневного лимита: зелёный — меньше +70 %, жёлтый — 70–100 %, красный — лимит выбран. Когда дневной лимит +перерасходован, остаток уходит в минус и показывается красным — `-200 ₽`, а +подсказка при наведении добавляет сумму перерасхода: +«День: потрачено 600 ₽ из 400 ₽, перерасход 200 ₽». Минус стоит перед знаком +валюты (`-$200`, но `-200 ₽` — у рубля символ остаётся суффиксом). Ровно на +лимите показывается «0 ₽». Клик по этому чтению открывает раздел статистики. +Если дневной лимит не задан, на том же месте показывается нейтральная +«Статистика». Недельный и месячный лимиты участвуют только в разделе +статистики. + +**Лимиты привязаны к провайдеру, а не к окну.** Ключ записи — владелец кошелька +(`openrusrouter` или `deepseek`), валюта хранится внутри записи: у оператора это +рубли, у аккаунта DeepSeek — валюта его кошелька. Запись одна на всех: её видят +любое окно, любой профиль и любой сеанс, потому что лимиты лежат в общей +SQLite-базе, а не в браузере. Панель подписывает, чьи лимиты показаны +(«Для OpenRusRouter в ₽»), и переключается вместе с провайдером выбранной модели; +если у текущего провайдера лимитов нет, панель показывает того, у кого они есть, +— лимиты не «исчезают» при смене модели. + +В доке остаток дня считается по лимиту провайдера, который списывает выбранную +модель; если у него лимита нет, берётся провайдер с дневным лимитом и расходом +за сегодня — поэтому остаток дня не превращается в голую «Статистику». + +## Где хранится история + +Расход, пробы баланса и условные лимиты лежат в SQLite-базе Host-половины: + +``` +~/.dsh/storages/cost-balance.sqlite # $DSH_HOME или ~/.dsh; переопределяется $DSH_COST_BALANCE_DB +``` + +Схема нормализованная, её версия — `PRAGMA user_version` (сейчас 4), файл помечен +`PRAGMA application_id = 0x43425350` («CBSP»), поэтому чужую базу по этому пути +плагин не примет: + +- `spend_hours(hour, currency, amount)` — часы расхода (локальный epoch-час); +- `spend_samples(provider, currency, observed_at, amount, wallet, used, cap, reset_window, reset_at)` — + последняя проба на провайдера, то есть метр трат; +- `spend_limits(owner, currency, day, week, month)` — условные лимиты по + провайдеру (v3); +- `usage_hours(hour, model, miss, cache_write, cache_read, output)` — токены по + часам и моделям (вкладки «Токены» и «Кеш»); +- `fx_rates(code, rate, rate_date, fetched_at)` — дневной курс ЦБ (рублей за + единицу валюты), кэш на сутки; +- `spend_meta(key, value)` — валюта документа. + +Обновление схемы идёт на месте: все таблицы создаются через +`CREATE TABLE IF NOT EXISTS`, поэтому файл версии 1 при первом открытии +получает `usage_hours`, а таблица лимитов перестраивается в v3 без потери +истории. Старые ключи лимитов по валюте переезжают во владельцев: рубли — к +`openrusrouter`, валюта кошелька аккаунта — к `deepseek` (если в файле были и +юани, и доллары, побеждают юани). База более новой версии, чем понимает плагин, +не открывается. + +Файл создаётся с правами `0600`, каталог — `0700`, журнал — WAL. + +**API.** Клиент читает и пишет документ целиком: + +``` +GET /api/cost-balance/spend -> { ok, state } +PUT /api/cost-balance/spend { state, mode } // mode: merge | replace | limits | day | clear +POST /api/cost-balance/spend/import { state } // устаревший одноразовый импорт +GET /api/cost-balance/rates -> { ok, base: "RUB", date, rates: { USD, CNY, EUR } } +``` + +`mode` по умолчанию — `merge`: окна опрашивают один и тот же кошелёк и видят одни +и те же списания, поэтому по каждому часу и модели берётся **большее** значение +(суммирование удвоило бы расход), проба — более свежая, а лимиты берутся из общей +базы и лишь дополняются владельцами, которых там нет. Остальные режимы — +явные действия: `limits` заменяет только лимиты, `day` перезаписывает один день +(с готовыми часовыми бакетами), `clear` стирает историю, сохраняя лимиты, +`replace` — полная замена. Так автоматическая запись одного окна не затирает +ручную правку другого. + +Оба маршрута зарегистрированы как raw-handler (`handler`), а не как `resource`: +`dsh-host-webserver` обслуживает resource-маршруты только для GET/HEAD и на любой +другой метод отвечает 405 **до** сопоставления пути. Из-за этого первая версия +хранилища молча теряла каждое сохранение и разовый импорт — база оставалась +пустой, а клиент уходил в резервный режим. Handler владеет ответом и принимает +PUT/POST сам. + +Клиент держит синхронную копию документа в памяти и отправляет его через 250 мс +после изменения (явные действия — сразу); GET раз в 30 секунд подтягивает то, что +записало другое окно. Неудачная запись не теряет данные в памяти — следующее +изменение отправит документ заново. + +**Миграция.** Сразу после обновления Host ещё не перезапущен, и клиент работает +со старым `localStorage` (ключ `dsh-cost-balance/spend/v1`) как с резервом. +После перезапуска Host клиент **сливает** накопленную историю с базой (а не +импортирует только в пустую): по часам и моделям — максимум, пробы — свежее, +лимиты дополняются недостающими владельцами. Поэтому история не теряется, даже +если другое окно успело записать свою, более короткую копию; слияние +идемпотентно и не удваивает расход. После успешной записи старый ключ удаляется. +В резервном режиме клиент повторяет попытку на каждом опросе (раз в 30 секунд), +поэтому перезапущенный Host подхватывается без перезагрузки страницы; +предупреждение в консоли пишется один раз. + +## Установка + +Репозиторий: `ssh://git@git.realmanual.ru:2022/pub/cost-balance-footer.git` +(веб-страница — `https://git.realmanual.ru/pub/cost-balance-footer`). + +```bash +git clone ssh://git@git.realmanual.ru:2022/pub/cost-balance-footer.git \ + ~/.dsh/plugins/cost-balance-footer +``` + +Затем подключите папку к своему профилю DSH `web` (и/или `desktop`) — в +`~/.dsh/profiles//package.json`: + +```json +{ + "dependencies": { + "@local/dsh-cost-balance-footer": "link:/Users//.dsh/plugins/cost-balance-footer" + }, + "dsh": { + "profile": { + "bundles": [ + "@deepseek-ai/dsh-base", + "@deepseek-ai/dsh-web-app", + "@local/dsh-cost-balance-footer" + ] + } + } +} +``` + +После правки профиля переустановите зависимости профиля +(`cd ~/.dsh/profiles/web && pnpm install`) и перезапустите DSH: Host-половина +(маршруты баланса, курса и хранилища) грузится только при старте процесса, а +клиентская часть подхватывается при перезагрузке страницы. + +Нужен Python? Нет. Нужен доступ к Credentials: ключ оператора +(`OPENRUSROUTER_API_KEY`) резолвится на Host через `ctx.credentials` или +переменную окружения с тем же именем — в браузер он не попадает. + +## Где живёт плагин + +Исходники лежат в общей папке `~/.dsh/plugins/cost-balance-footer` (вне +репозиториев), а профили DSH `web` и `desktop` подключают её через +`link:` в своём `package.json`. Поэтому плагин доступен во всех рабочих +пространствах, включая новые. Репозиторий на Gitea — точка распространения: +правки в папке коммитятся и пушатся туда. + +## Сторонний оператор (OpenRusRouter) + +Когда `modelSelection` сессии указывает провайдера не из DeepSeek, клиент +запрашивает баланс у Host-маршрута: + +``` +GET /api/cost-balance/operator-balance?provider=openrusrouter +``` + +Host-половина (`index.js`) держит карту `PROVIDERS`: URL баланса, ссылка на +credential (`apiKeyEnv`) и подпись. Ключ разрешается через `ctx.credentials` +на Host, наружу уходит только число остатка — сам ключ в браузер не попадает. +Ответ: `{ ok: true, provider, displayName, amount, symbol, source }` либо +`{ ok: false, reason }` (`unknown-provider`, `missing-credential`, `network`, +`http-error`, `bad-payload`, `unknown-shape`). Клиент по `unknown-provider` +откатывается к балансу аккаунта DeepSeek, по остальным причинам показывает +«Баланс —», а код причины — в подсказке при наведении: `http-404` означает, +что маршрут не зарегистрирован вовсе, `missing-credential` — что Host не смог +разрешить ключ. + +**Почему маршрут мог пропасть.** Host-половина читала `webServer` один раз при +загрузке. Порядок загрузки плагинов зависит от состава профиля, и если плагин +применялся раньше, чем веб-сервер отдавал сервис, `ctx.get('webServer')` +возвращал `undefined` — маршрут молча не регистрировался, браузер получал 404, +и чтение показывало «Баланс —». Теперь плагин объявляет +`inject = ['webServer']` и монтирует маршрут через `ctx.inject`, то есть ждёт +сервис (и перерегистрирует маршрут, если сервис заменится). + +Парсер остатка берёт кошелёк (`data.account_balance`), иначе остаток под лимитом +(`data.limit_remaining`, `data.balance`), иначе `data.credits`. Отдельно он +читает счётчик трат — `data.usage`, `data.limit`, `data.limit_window`, +`data.limit_resets_at` — и отдаёт его клиенту в полях `used`, `limit`, `window`, +`resetsAt`. Поэтому парсер подходит OpenRouter-совместимым шлюзам, а правка +лимита ключа в кабинете больше не выглядит как расход. + +**Валюта:** кошелёк OpenRusRouter номинирован в рублях, поэтому в записи +`PROVIDERS` стоит `symbol: '₽'`, и он имеет приоритет над любым полем +`currency` в ответе шлюза (оно может отсутствовать или быть неверным). +Клиент рисует рубли суффиксом — `890,40 ₽`; остальные валюты остаются +префиксом (`$10.00`). + +Чтобы добавить ещё одного оператора, допишите запись в `PROVIDERS`: + +```js +another: { + balanceUrl: 'https://gateway.example/v1/auth/key', + apiKeyEnv: 'ANOTHER_API_KEY', // ссылка на credential, не сам ключ + symbol: '₽', // '₽' рисуется суффиксом, прочие — префиксом + displayName: 'Another', +} +``` + +Маршрут зарегистрирован на loopback-веб-сервере профиля и отдаёт только +остаток для известных провайдеров; ключ никогда не возвращается. Обновление +баланса — при смене модели, раз в минуту и по клику на показатель. + +## Кнопка перезагрузки + +В подвале боковой панели, рядом со строками настроек и меню профиля (слот +`sidebar.footer.action`, там же кнопка плагина cordis), есть кнопка-«пилюля» со +стрелкой и подписью **reload**, прижатая к левому краю строки (с тем же отступом, +что и строки настроек). В свёрнутой панели подпись не помещается и остаётся только +иконка. Кнопка перезагружает страницу — +так применяются свежие клиентские бандлы и настройки интерфейса без похода в меню +профиля. + +**Сессии и агенты при этом не перезагружаются.** Они живут на Host-половине: +загрузка страницы лишь переподключает интерфейс к тем же сессиям, а идущий ход +агента продолжается и доигрывается в ленте после переподключения. Ожидающие +подтверждения остаются в сессии и снова показываются. Теряется только состояние +самой страницы: неотправленный текст в поле ввода, открытые диалоги и позиция +прокрутки. + +## Компактная подпись кэша + +Штатная пилюля использования в том же доке пишет «Попадание в кэш: 87 %» +(в других языках — «Cache hit 87 %» и т. п.). Клиентская половина плагина +переписывает этот текст в DOM, оставляя только процент. Переопределить словарь +через `ctx.locale.register` нельзя: сервис локали отклоняет второй словарь для +уже занятой пары «пространство имён + язык», а строка принадлежит поставке DSH. +Наблюдатель ограничен элементом `[data-composer-stat="usage"]` и ничего не +делает, если подписи уже нет. diff --git a/client.js b/client.js new file mode 100644 index 0000000..3757863 --- /dev/null +++ b/client.js @@ -0,0 +1,3447 @@ +/** + * Cost and balance readings in the composer dock. + * + * The Client half of `@local/dsh-cost-balance-footer`. It contributes one + * entry to `conversation.composer.dock`, beside the shipped activity and usage + * pills, and renders two readings: + * + * - `Spent ≈ …` — an estimate of what this session has cost so far, priced + * from the durable `tokenUsage` projection with DeepSeek's published list + * prices. Each observed usage delta is priced in the tariff band (peak or + * idle, Beijing time) that was in force when it was observed, and the + * per-model, per-band token counters are cached in `localStorage` so a page + * reload does not re-price or double-count the session's history. + * - `Balance …` — the account's remaining recharge and granted wallets, read + * through the account Remote on mount, after a turn advances the usage + * projection, and on demand by clicking the reading. + * + * Both are display-only: they never consume a model request, write Session + * events, or touch another plugin's DOM. + */ +window.__ModuleLoader__.load({ + id: '@local/dsh-cost-balance-footer', + factory(require) { + const React = require('react'); + const ReactDOM = require('react-dom'); + const h = React.createElement; + + const NS = 'costBalance'; + const PLUGIN_ID = '@local/dsh-cost-balance-footer'; + const CSS_ID = `${PLUGIN_ID}/composer-dock.css`; + const DEFAULT_MODEL = 'deepseek-flash'; + + /** + * DeepSeek list prices, peak band, per 1M tokens. Idle-band prices are + * exactly half (DeepSeek's published tariff: Beijing time Monday-Friday + * 9:00-12:00 and 14:00-18:00 is peak, everything else including weekends + * and Chinese public holidays is idle). CNY figures are the official + * Chinese price table; USD figures are the published English one. + */ + const PEAK_PRICES = { + CNY: { + 'deepseek-flash': { miss: 2, hit: 0.04, output: 8 }, + 'deepseek-v4-pro': { miss: 9, hit: 0.3, output: 27 }, + }, + USD: { + 'deepseek-flash': { miss: 0.3, hit: 0.006, output: 0.6 }, + 'deepseek-v4-pro': { miss: 1.32, hit: 0.044, output: 3.96 }, + }, + }; + const CURRENCY_SYMBOL = { CNY: '¥', USD: '$' }; + const DEFAULT_CURRENCY = 'CNY'; + /** Cache-write tokens have no DeepSeek price of their own; they bill as uncached input. */ + const BANDS = ['peak', 'idle']; + + const STORAGE_PREFIX = 'dsh-cost-balance/'; + const STORAGE_VERSION = 1; + const BALANCE_MIN_INTERVAL_MS = 30_000; + const BALANCE_POLL_MS = 60_000; + /** Re-read the tariff band so the lamp flips at the peak/idle boundary. */ + const TARIFF_POLL_MS = 30_000; + + // #region price helpers + + /** Map a provider-owned model id onto one of the priced DeepSeek routes. */ + function pricedModel(model) { + const id = typeof model === 'string' ? model.toLowerCase() : ''; + if (id.includes('pro')) return 'deepseek-v4-pro'; + if (id.includes('flash')) return 'deepseek-flash'; + return DEFAULT_MODEL; + } + + /** Peak-band list price for one model id and display currency. */ + function priceOf(model, currency) { + const table = PEAK_PRICES[currency] ?? PEAK_PRICES[DEFAULT_CURRENCY]; + return table[pricedModel(model)] ?? table[DEFAULT_MODEL]; + } + + /** Beijing-time tariff band at one instant. */ + function bandAt(time) { + const beijing = new Date(time + 8 * 3_600_000); + const day = beijing.getUTCDay(); + if (day === 0 || day === 6) return 'idle'; + const hour = beijing.getUTCHours(); + return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18) ? 'peak' : 'idle'; + } + + function emptyBand() { + return { miss: 0, hit: 0, out: 0 }; + } + + function emptyBuckets() { + return { peak: emptyBand(), idle: emptyBand() }; + } + + // #endregion + + // #region cost ledger + + /** + * Per-session token ledger. Counters are token counts (never money), so a + * later currency or price change re-prices the same observations instead + * of compounding an old conversion. + */ + function createLedger(sessionId) { + const storageKey = STORAGE_PREFIX + String(sessionId); + const state = readState(); + + function readState() { + try { + const raw = window.localStorage.getItem(storageKey); + if (typeof raw === 'string') { + const parsed = JSON.parse(raw); + if (parsed && parsed.version === STORAGE_VERSION && parsed.models && typeof parsed.models === 'object') { + return { + version: STORAGE_VERSION, + last: parsed.last && typeof parsed.last === 'object' ? parsed.last : null, + lastRaw: parsed.lastRaw && typeof parsed.lastRaw === 'object' ? parsed.lastRaw : null, + models: parsed.models, + }; + } + } + } catch { + /* Private mode, quota, or a corrupt cache: fall back to a fresh ledger. */ + } + return { version: STORAGE_VERSION, last: null, lastRaw: null, models: {} }; + } + + function writeState() { + try { + window.localStorage.setItem(storageKey, JSON.stringify(state)); + } catch { + /* A memory-only ledger still works for this page. */ + } + } + + function bucketsOf(model) { + const key = pricedModel(model); + let buckets = state.models[key]; + if (buckets === undefined || buckets === null) { + buckets = emptyBuckets(); + state.models[key] = buckets; + } + for (const band of BANDS) { + if (buckets[band] === undefined) buckets[band] = emptyBand(); + } + return buckets; + } + + function add(model, band, delta) { + const buckets = bucketsOf(model); + const target = buckets[band] ?? (buckets[band] = emptyBand()); + target.miss += delta.miss; + target.hit += delta.hit; + target.out += delta.out; + } + + function snapshotOf(usage) { + return { + miss: count(usage.uncachedInputTokens) + count(usage.cacheWriteTokens), + hit: count(usage.cacheReadTokens), + out: count(usage.outputTokens), + }; + } + + /** The same observation with cache writes kept apart, for the history. */ + function rawSnapshotOf(usage) { + return { + miss: count(usage.uncachedInputTokens), + write: count(usage.cacheWriteTokens), + hit: count(usage.cacheReadTokens), + out: count(usage.outputTokens), + }; + } + + return { + sessionId, + /** + * Fold one durable usage observation into the ledger. + * @param usage - `tokenUsage` projection value. + * @param model - model route of the requests that produced the delta. + * @param priced - whether DeepSeek list prices describe that route. + */ + observe(usage, model, priced) { + const raw = rawSnapshotOf(usage); + const current = { + miss: raw.miss + raw.write, + hit: raw.hit, + out: raw.out, + }; + const previousRaw = + state.lastRaw !== null && typeof state.lastRaw === 'object' ? state.lastRaw : null; + /* The raw delta is what the shared token history records: it keeps + * cache writes apart and never includes the pre-installation bulk. */ + const rawDelta = + previousRaw === null + ? undefined + : { + miss: Math.max(0, raw.miss - count(previousRaw.miss)), + write: Math.max(0, raw.write - count(previousRaw.write)), + hit: Math.max(0, raw.hit - count(previousRaw.hit)), + out: Math.max(0, raw.out - count(previousRaw.out)), + }; + state.lastRaw = raw; + if (state.last === null) { + /* First sight of this session: price its whole history at the + * band in force now, then continue with exact per-band deltas. */ + if (priced) add(model, bandAt(Date.now()), current); + state.last = current; + writeState(); + return undefined; + } + const previous = state.last; + const delta = { + miss: Math.max(0, current.miss - count(previous.miss)), + hit: Math.max(0, current.hit - count(previous.hit)), + out: Math.max(0, current.out - count(previous.out)), + }; + state.last = current; + if (priced && delta.miss + delta.hit + delta.out > 0) { + add(model, bandAt(Date.now()), delta); + } + writeState(); + return rawDelta; + }, + /** + * Estimated money spent so far, in the requested wallet currency. + * @param currency - 'CNY' or 'USD'. + */ + cost(currency) { + let total = 0; + for (const [model, buckets] of Object.entries(state.models)) { + const price = PEAK_PRICES[currency]?.[model] ?? PEAK_PRICES[currency]?.[DEFAULT_MODEL]; + if (price === undefined) continue; + for (const band of BANDS) { + const counts = buckets[band] ?? emptyBand(); + const factor = band === 'peak' ? 1 : 0.5; + total += + ((count(counts.miss) * price.miss) + + (count(counts.hit) * price.hit) + + (count(counts.out) * price.output)) * + (factor / 1_000_000); + } + } + return total; + }, + }; + } + + function count(value) { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0; + } + + // #endregion + + // #region spend ledger + + /** + * Machine-local spending history and the user's own soft limits. + * + * Money is counted from the balance readings this plugin already polls, but + * not from the remainder alone: a gateway that caps a key reports what is + * left *under that cap*, so editing the cap in the billing cabinet moved + * the reading and the ledger booked the difference as spending. Each + * reading is reduced to a spend meter instead — the gateway's own usage + * counter, the whole-account wallet, or the remainder while its cap stays + * unchanged — and only a meter that grew between two samples is spending. + * That keeps the numbers honest for third-party gateways too, where a token + * has no price this plugin knows. + * + * A delta covers the time since the previous sample, so it is spread evenly + * over the hours it may have happened in (capped) instead of landing as one + * spike on the hour the app came back. + * + * Hour buckets are keyed by local epoch hour, so day/week/month windows and + * the hourly view follow the user's own time zone. + */ + const SPEND_KEY = 'dsh-cost-balance/spend/v1'; + const SPEND_VERSION = 1; + const SPEND_EVENT = 'dsh-cost-balance/spend-changed'; + const SPEND_ROUTE = '/api/cost-balance/spend'; + const SPEND_TIMEOUT_MS = 5_000; + const SPEND_PERSIST_DELAY_MS = 250; + const SPEND_PULL_MS = 30_000; + const HOUR_MS = 3_600_000; + const MAX_SMEAR_HOURS = 72; + const SPEND_RETENTION_DAYS = 400; + const RATIO_WARN = 0.7; + const SYMBOL_TO_CURRENCY = { '₽': 'RUB', $: 'USD', '¥': 'CNY' }; + const CURRENCY_TO_SYMBOL = { RUB: '₽', USD: '$', CNY: '¥' }; + const LIMIT_PERIODS = ['day', 'week', 'month']; + + function emptySpend() { + return { version: SPEND_VERSION, currency: 'RUB', hours: {}, samples: {}, limits: {}, tokens: {} }; + } + + /** + * The ledger now lives in the Host's SQLite database. This half keeps a + * synchronous in-memory copy: the dock and the statistics render from it + * without waiting for a round trip, every mutation updates it, notifies the + * views and schedules a debounced PUT of the whole document. A GET on mount + * hydrates it, and a periodic GET picks up what another window recorded. + * + * The browser storage is read only once, to migrate the history written by + * older versions, and is used as a fallback while a Host without the ledger + * route is still running — the Client bundle hot-reloads before the Host + * process restarts. + */ + let spendState = emptySpend(); + /** `pending` until the Host answers, then `server` (SQLite) or `local`. */ + let spendMode = 'pending'; + let spendWarned = false; + /** Operations queued for the Host: explicit edits, then merges. */ + let pendingOps = []; + let mergePending = false; + + /* ------------------------------------------------------------------ */ + /* Daily central-bank rates */ + /* ------------------------------------------------------------------ */ + + /** + * DeepSeek wallets bill in dollars or yuan while the operator wallet and + * the user's budgets are in rubles. The Host caches the Central Bank rates + * for a day; this half keeps them in memory and folds foreign spend into + * the ruble totals, so switching providers does not hide spending. + */ + const FX_ROUTE = '/api/cost-balance/rates'; + const FX_EVENT = 'dsh-cost-balance/rates-changed'; + const FX_REFRESH_MS = 6 * 3_600_000; + let fxRates = {}; + let fxDate = ''; + let fxStatus = 'idle'; + let fxRequest = null; + + function notifyFx() { + try { + window.dispatchEvent(new CustomEvent(FX_EVENT)); + } catch { + /* Non-browser test rigs have no CustomEvent. */ + } + } + + async function refreshFxRates() { + if (fxRequest !== null) return fxRequest; + if (fxStatus === 'idle') fxStatus = 'loading'; + fxRequest = (async () => { + try { + const response = await fetch(FX_ROUTE, { + cache: 'no-store', + credentials: 'same-origin', + signal: AbortSignal.timeout(SPEND_TIMEOUT_MS), + }); + if (!response.ok) throw new Error(`http-${String(response.status)}`); + const payload = await response.json(); + if (payload === null || typeof payload !== 'object' || payload.ok !== true) { + throw new Error('bad-payload'); + } + const rates = {}; + for (const [code, value] of Object.entries(payload.rates ?? {})) { + const rate = finite(value); + if (/^[A-Z]{3}$/.test(code) && rate !== undefined && rate > 0) rates[code] = rate; + } + fxRates = rates; + fxDate = typeof payload.date === 'string' ? payload.date : ''; + fxStatus = Object.keys(rates).length > 0 ? 'ready' : 'unavailable'; + } catch { + fxStatus = Object.keys(fxRates).length > 0 ? 'ready' : 'unavailable'; + } finally { + fxRequest = null; + } + notifyFx(); + })(); + return fxRequest; + } + let persistTimer = 0; + let persistRunning = false; + let persistAgain = false; + + function notifySpend() { + try { + window.dispatchEvent(new CustomEvent(SPEND_EVENT)); + } catch { + /* Non-browser test rigs have no CustomEvent; nothing to notify. */ + } + } + + /** Whether a document key is a local epoch-hour bucket. */ + function isHourKey(key) { + const hour = Number(key); + return Number.isSafeInteger(hour) && hour >= 0; + } + + /** Clamp one document to the ledger shape shared with the Host. */ + function parseSpend(value) { + const state = emptySpend(); + if (value === null || typeof value !== 'object') return state; + if (typeof value.currency === 'string' && value.currency !== '') state.currency = value.currency; + if (value.hours !== null && typeof value.hours === 'object') { + for (const [key, bucket] of Object.entries(value.hours)) { + if (!isHourKey(key) || bucket === null || typeof bucket !== 'object') continue; + const amounts = {}; + for (const [currency, amount] of Object.entries(bucket)) { + const parsed = finite(amount); + if (parsed === undefined || parsed === 0) continue; + amounts[currency] = parsed; + } + if (Object.keys(amounts).length > 0) state.hours[key] = amounts; + } + } + if (value.samples !== null && typeof value.samples === 'object') { + for (const [provider, sample] of Object.entries(value.samples)) { + if (sample === null || typeof sample !== 'object') continue; + state.samples[provider] = { ...sample }; + } + } + if (value.limits !== null && typeof value.limits === 'object') { + const read = (raw) => { + const parsed = finite(raw); + return parsed !== undefined && parsed > 0 ? parsed : 0; + }; + for (const [key, limits] of Object.entries(value.limits)) { + if (limits === null || typeof limits !== 'object') continue; + /* Older documents keyed limits by currency; the shared ledger keys + * them by the provider that owns the wallet. */ + const legacy = /^[A-Z]{3}$/.test(key); + const owner = legacy ? ownerForCurrency(key) : key; + if (!/^[a-z0-9-]{1,32}$/.test(owner)) continue; + const stored = + typeof limits.currency === 'string' && /^[A-Z]{3}$/.test(limits.currency) + ? limits.currency + : legacy + ? key + : state.currency; + /* One entry per owner: when a legacy document carries both wallet + * currencies, the yuan entry wins over the dollar one. */ + const previous = state.limits[owner]; + if (previous !== undefined && previous.currency === 'CNY' && stored === 'USD') continue; + state.limits[owner] = { + currency: stored, + day: read(limits.day), + week: read(limits.week), + month: read(limits.month), + }; + } + } + if (value.tokens !== null && typeof value.tokens === 'object') { + for (const [key, models] of Object.entries(value.tokens)) { + if (!isHourKey(key) || models === null || typeof models !== 'object') continue; + const entries = {}; + const read = (raw) => { + const parsed = finite(raw); + return parsed !== undefined && parsed > 0 ? parsed : 0; + }; + for (const [model, entry] of Object.entries(models)) { + if (entry === null || typeof entry !== 'object') continue; + const miss = read(entry.miss); + const write = read(entry.write); + const hit = read(entry.hit); + const out = read(entry.out); + if (miss + write + hit + out <= 0) continue; + entries[model] = { miss, write, hit, out }; + } + if (Object.keys(entries).length > 0) state.tokens[key] = entries; + } + } + return state; + } + + /** The document written by versions that kept it in `localStorage`. */ + function readLegacySpend() { + try { + const raw = window.localStorage.getItem(SPEND_KEY); + if (typeof raw === 'string') { + const parsed = JSON.parse(raw); + if (parsed !== null && typeof parsed === 'object' && parsed.version === SPEND_VERSION) { + return parseSpend(parsed); + } + } + } catch { + /* Private mode, quota, or a corrupt cache: start a fresh ledger. */ + } + return emptySpend(); + } + + function writeLegacySpend(state) { + try { + window.localStorage.setItem(SPEND_KEY, JSON.stringify(state)); + } catch { + /* A memory-only ledger still works for this page. */ + } + } + + /** The ledger the views render from. */ + function readSpend() { + return spendState; + } + + /** + * Replace the in-memory ledger, publish it, and persist it. + * + * Ordinary writes carry `mode: 'merge'`: several windows poll the same + * wallet and the Host folds their observations together instead of letting + * the last writer win. Explicit edits (limits, one day, clearing) name + * their operation so they are not swallowed by a merge. + */ + function writeSpend(state, op) { + /* Callers mutate the cached document in place, so the published state + * must be a fresh object: React skips an update that returns the same + * reference, and the dock would keep showing the previous reading. */ + spendState = { + ...state, + hours: { ...state.hours }, + samples: { ...state.samples }, + limits: { ...state.limits }, + tokens: { ...state.tokens }, + }; + if (spendMode === 'server') { + if (op !== undefined && op.mode !== 'merge') { + pendingOps.push(op); + if (persistTimer !== 0) { + window.clearTimeout(persistTimer); + persistTimer = 0; + } + void flushSpend(); + } else { + mergePending = true; + scheduleSpendPersist(); + } + } else if (spendMode === 'local') { + writeLegacySpend(spendState); + } + notifySpend(); + } + + function isEmptySpend(state) { + return ( + Object.keys(state.hours).length === 0 && + Object.keys(state.samples).length === 0 && + Object.keys(state.limits).length === 0 + ); + } + + /** One bounded JSON call to the Host half. */ + async function spendRequest(route, method, body) { + const init = { + method, + cache: 'no-store', + credentials: 'same-origin', + signal: AbortSignal.timeout(SPEND_TIMEOUT_MS), + }; + if (body !== undefined) { + init.headers = { 'content-type': 'application/json' }; + init.body = JSON.stringify(body); + } + const response = await fetch(route, init); + if (!response.ok) throw new Error(`http-${String(response.status)}`); + return response.json(); + } + + /** + * Fold a browser document into the shared one. + * + * Two windows polling the same wallet observe the same spend, so summing + * their hours would double count it; taking the larger value per hour (and + * per model for tokens) keeps the richer observation instead. Samples take + * the newer reading, limits keep what the shared ledger already has and + * take the browser copy only for owners it does not cover. + */ + function mergeSpendDocuments(base, extra) { + const merged = { + ...base, + hours: {}, + samples: { ...base.samples }, + limits: { ...base.limits }, + tokens: {}, + }; + for (const [key, bucket] of Object.entries(base.hours)) merged.hours[key] = { ...bucket }; + for (const [key, models] of Object.entries(base.tokens)) { + merged.tokens[key] = { ...models }; + } + for (const [hour, bucket] of Object.entries(extra.hours)) { + const target = merged.hours[hour] ?? (merged.hours[hour] = {}); + for (const [currency, amount] of Object.entries(bucket)) { + const current = target[currency]; + if (typeof current !== 'number' || amount > current) target[currency] = amount; + } + } + for (const [hour, models] of Object.entries(extra.tokens)) { + const target = merged.tokens[hour] ?? (merged.tokens[hour] = {}); + for (const [model, entry] of Object.entries(models)) { + const current = target[model]; + if (current === undefined) { + target[model] = { ...entry }; + continue; + } + target[model] = { + miss: Math.max(current.miss, entry.miss), + write: Math.max(current.write, entry.write), + hit: Math.max(current.hit, entry.hit), + out: Math.max(current.out, entry.out), + }; + } + } + for (const [provider, sample] of Object.entries(extra.samples)) { + const current = merged.samples[provider]; + if (current === undefined || (sample.at ?? 0) > (current.at ?? 0)) { + merged.samples[provider] = { ...sample }; + } + } + for (const [owner, limits] of Object.entries(extra.limits)) { + if (merged.limits[owner] === undefined) merged.limits[owner] = { ...limits }; + } + return merged; + } + + /** + * Load the ledger from the Host, folding the browser history into it once. + * Any failure leaves the old browser storage in charge, so the plugin keeps + * working against a Host that predates the ledger route. + */ + async function hydrateSpend() { + const legacy = readLegacySpend(); + try { + const payload = await spendRequest(SPEND_ROUTE, 'GET'); + if (payload === null || typeof payload !== 'object' || payload.ok !== true) { + throw new Error('bad-payload'); + } + let state = parseSpend(payload.state); + if (!isEmptySpend(legacy)) { + /* Another window may have reached the database first; fold this + * window's history into it instead of skipping the migration. */ + state = mergeSpendDocuments(state, legacy); + await spendRequest(SPEND_ROUTE, 'PUT', { state, mode: 'merge' }); + try { + window.localStorage.removeItem(SPEND_KEY); + } catch { + /* The merged copy still stands even if the old key cannot be removed. */ + } + } + spendState = state; + spendMode = 'server'; + } catch (error) { + spendState = legacy; + spendMode = 'local'; + /* A Host that predates the ledger route is expected right after an + * update; warn once, then keep retrying quietly on the ledger poll. */ + if (!spendWarned) { + spendWarned = true; + try { + console.warn('cost-balance: spending ledger route unavailable, using browser storage', error); + } catch { + /* A test rig without a console still gets the fallback. */ + } + } + } + if (spendMode === 'server') spendWarned = false; + notifySpend(); + return spendState; + } + + /** + * Pull what another window recorded, unless local changes are unsaved. + * In the browser-storage fallback this retries the one-time migration, so + * a Host restarted with the ledger route takes over without a page reload. + */ + async function pullSpend() { + if (spendMode === 'local') { + await hydrateSpend(); + return; + } + if (spendMode !== 'server' || persistTimer !== 0 || persistRunning) return; + try { + const payload = await spendRequest(SPEND_ROUTE, 'GET'); + if (payload === null || typeof payload !== 'object' || payload.ok !== true) return; + const next = parseSpend(payload.state); + if (JSON.stringify(next) === JSON.stringify(spendState)) return; + spendState = next; + notifySpend(); + } catch { + /* Keep the current copy; the next pull retries. */ + } + } + + function scheduleSpendPersist() { + if (persistTimer !== 0) return; + persistTimer = window.setTimeout(() => { + persistTimer = 0; + void flushSpend(); + }, SPEND_PERSIST_DELAY_MS); + } + + /** + * Write the current document back, one request at a time: a mutation that + * lands while a PUT is in flight marks another round, so the database ends + * on the newest copy instead of racing an older one. + */ + async function flushSpend() { + if (persistRunning) { + persistAgain = true; + return; + } + persistRunning = true; + try { + do { + persistAgain = false; + while (pendingOps.length > 0) { + const op = pendingOps.shift(); + await spendRequest(SPEND_ROUTE, 'PUT', { + state: spendState, + mode: op.mode, + ...(op.day === undefined ? {} : { day: op.day }), + }); + } + if (mergePending) { + mergePending = false; + await spendRequest(SPEND_ROUTE, 'PUT', { state: spendState, mode: 'merge' }); + } + } while (persistAgain || pendingOps.length > 0 || mergePending); + } catch { + /* The next mutation retries; the in-memory ledger stays correct. */ + } finally { + persistRunning = false; + } + } + + /** Local epoch hour that one instant belongs to. */ + function hourKey(ms) { + return Math.floor(ms / HOUR_MS) * HOUR_MS; + } + + function startOfDay(ms) { + const date = new Date(ms); + date.setHours(0, 0, 0, 0); + return date.getTime(); + } + + /** Monday 00:00 of the week holding `ms`. */ + function startOfWeek(ms) { + const date = new Date(startOfDay(ms)); + const offset = (date.getDay() + 6) % 7; + date.setDate(date.getDate() - offset); + return date.getTime(); + } + + function startOfMonth(ms) { + const date = new Date(ms); + date.setHours(0, 0, 0, 0); + date.setDate(1); + return date.getTime(); + } + + function addHourSpend(state, currency, hourStart, amount) { + if (!(amount > 0)) return; + const key = String(hourStart); + const bucket = state.hours[key] ?? (state.hours[key] = {}); + bucket[currency] = (bucket[currency] ?? 0) + amount; + } + + /** Drop buckets older than the retention window. */ + function pruneSpend(state) { + const cutoff = hourKey(Date.now() - SPEND_RETENTION_DAYS * 24 * HOUR_MS); + for (const key of Object.keys(state.hours)) { + if (Number(key) < cutoff) delete state.hours[key]; + } + for (const key of Object.keys(state.tokens ?? {})) { + if (Number(key) < cutoff) delete state.tokens[key]; + } + } + + /** Finite number from a number or a numeric string, else undefined. */ + function finite(value) { + if (typeof value === 'number') return Number.isFinite(value) ? value : undefined; + if (typeof value === 'string' && value.trim() !== '') { + const parsed = Number(value); + if (Number.isFinite(parsed)) return parsed; + } + return undefined; + } + + /** + * The quantity a reading moves only when money is really spent. + * + * Polling a remainder cannot tell a purchase from a bookkeeping change, and + * a gateway that caps a key reports the remainder *under that cap*, so + * editing the cap moved it and the ledger booked the move as spending. + * Each reading is therefore reduced to one meter, preferred in this order: + * + * - the gateway's own `usage` counter for the current window: only billed + * requests move it; + * - the whole-account wallet: only billed requests lower it (a top-up + * raises it, and a raised meter is rebased, never booked); + * - the displayed remainder, but only while the cap it is computed against + * stays the same. + * + * A meter carries a tag — the window identity, the meter kind, the key cap — + * and a delta is booked only between two samples with the same tag. A + * changed tag rebases the sample instead of inventing a spend for the + * difference. + */ + function meterOf(sample) { + if (sample === null || typeof sample !== 'object') return undefined; + const used = finite(sample.used); + if (used !== undefined) { + return { tag: `usage|${sample.window ?? ''}|${sample.resetsAt ?? ''}`, value: used }; + } + const wallet = finite(sample.wallet); + if (wallet !== undefined) return { tag: 'wallet', value: -wallet }; + const amount = finite(sample.amount); + if (amount !== undefined) return { tag: `balance|${finite(sample.cap) ?? ''}`, value: -amount }; + return undefined; + } + + /** + * Fold one balance reading into the history. + * @param provider - balance owner, e.g. `deepseek` or `openrusrouter`. + * @param sample - what the reading knows: `amount` (the displayed + * remainder) plus, when the gateway reports them, `wallet`, `used`, + * `cap`, `window` and `resetsAt`. + * @param currency - ISO code the amounts are denominated in. + * @param at - observation time. + */ + function recordBalanceSample(provider, sample, currency, at) { + if (typeof provider !== 'string' || provider === '') return; + if (typeof currency !== 'string' || currency === '') return; + const meter = meterOf(sample); + if (meter === undefined) return; + const state = readSpend(); + const previous = state.samples[provider]; + state.samples[provider] = { ...sample, currency, at }; + state.currency = currency; + const before = meterOf(previous); + if ( + before !== undefined && + previous.currency === currency && + Number.isFinite(previous.at) && + before.tag === meter.tag + ) { + const spent = meter.value - before.value; + if (spent > 0) { + const elapsed = Math.max(0, at - previous.at); + const hours = Math.min(MAX_SMEAR_HOURS, Math.max(1, Math.ceil(elapsed / HOUR_MS))); + const perHour = spent / hours; + const firstHour = hourKey(at) - (hours - 1) * HOUR_MS; + for (let index = 0; index < hours; index += 1) { + addHourSpend(state, currency, firstHour + index * HOUR_MS, perHour); + } + } + } + pruneSpend(state); + writeSpend(state); + } + + /** Rubles per one unit of `currency`, or undefined when it is unknown. */ + function rateOf(currency) { + if (currency === 'RUB') return 1; + const rate = fxRates[currency]; + return typeof rate === 'number' && Number.isFinite(rate) && rate > 0 ? rate : undefined; + } + + /** Currencies with recorded spending that the current rates cannot convert. */ + function unconvertedCurrencies(state) { + const codes = new Set(); + for (const bucket of Object.values(state.hours ?? {})) { + for (const [code, amount] of Object.entries(bucket ?? {})) { + if (code !== 'RUB' && amount > 0 && rateOf(code) === undefined) codes.add(code); + } + } + return [...codes]; + } + + /** + * Money of one window in `currency`. + * + * A ruble total folds every wallet in, using the daily Central Bank rates; + * another currency keeps only its own entries, because converting into a + * foreign unit would invent a number nobody budgeted in. + */ + function sumMoney(state, currency, fromMs, toMs = Date.now()) { + if (currency !== 'RUB') return sumSpend(state, currency, fromMs, toMs); + let total = 0; + for (const [key, bucket] of Object.entries(state.hours ?? {})) { + const hour = Number(key); + if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue; + for (const [code, amount] of Object.entries(bucket ?? {})) { + const rate = rateOf(code); + if (rate === undefined || typeof amount !== 'number' || !Number.isFinite(amount)) continue; + total += amount * rate; + } + } + return total; + } + + /** Money spent in `currency` from `fromMs` (inclusive) through now. */ + function sumSpend(state, currency, fromMs, toMs = Date.now()) { + let total = 0; + for (const [key, bucket] of Object.entries(state.hours)) { + const hour = Number(key); + if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue; + const value = bucket?.[currency]; + if (typeof value === 'number' && Number.isFinite(value)) total += value; + } + return total; + } + + /** + * Soft limits belong to the provider that bills the model, not to the + * window or to whatever currency happened to be written last: the + * operator's wallet is in rubles, the DeepSeek account in its own wallet + * currency. Every window and session reads the same owner entry from the + * shared ledger. + */ + function limitOwner(provider) { + return provider === 'openrusrouter' ? 'openrusrouter' : 'deepseek'; + } + + /** The owner a wallet currency belongs to (legacy currency-keyed limits). */ + function ownerForCurrency(currency) { + return currency === 'RUB' ? 'openrusrouter' : 'deepseek'; + } + + function limitOwnerLabel(owner) { + return owner === 'openrusrouter' ? 'OpenRusRouter' : 'DeepSeek'; + } + + /** Configured soft limits for one owner; zero means "not set". */ + function limitsOf(state, owner) { + const stored = state.limits?.[owner]; + const read = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0); + return { + day: read(stored?.day), + week: read(stored?.week), + month: read(stored?.month), + }; + } + + /** Whether an owner has at least one limit set. */ + function hasLimits(state, owner) { + const limits = limitsOf(state, owner); + return limits.day > 0 || limits.week > 0 || limits.month > 0; + } + + /** Currency of an owner's limits, or the fallback. */ + function limitCurrency(state, owner, fallback) { + const code = state.limits?.[owner]?.currency; + return typeof code === 'string' && code !== '' ? code : fallback; + } + + /** + * Which owner's limits a panel should show. The current provider wins when + * it has limits; otherwise the owner that does, so limits never appear to + * vanish just because the session uses another provider. + */ + function resolveLimitOwner(state, preferred) { + if (preferred !== undefined && hasLimits(state, preferred)) return preferred; + const owners = Object.keys(state.limits ?? {}).filter((owner) => hasLimits(state, owner)); + if (owners.length > 0) return owners[0]; + return preferred ?? ownerForCurrency(state.currency); + } + + function writeLimits(owner, currency, limits) { + const state = readSpend(); + const store = (value) => { + const parsed = Number(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : 0; + }; + state.limits[owner] = { + currency, + day: store(limits.day), + week: store(limits.week), + month: store(limits.month), + }; + state.currency = currency; + writeSpend(state, { mode: 'limits' }); + } + + /** Forget the recorded spending and token history, keeping the soft limits. */ + function clearSpendHistory() { + const state = readSpend(); + state.hours = {}; + state.samples = {}; + state.tokens = {}; + writeSpend(state, { mode: 'clear' }); + } + + /** Local `YYYY-MM-DD` value for a date input. */ + function dateInputValue(ms) { + const date = new Date(ms); + const pad = (value) => String(value).padStart(2, '0'); + return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; + } + + /** Local day start from a `YYYY-MM-DD` value, or undefined. */ + function parseDayInput(value) { + if (typeof value !== 'string') return undefined; + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + if (match === null) return undefined; + const time = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime(); + return Number.isFinite(time) ? time : undefined; + } + + /** + * Replace one local day's recorded spending with a single total. + * + * Only the day sum is known by hand, never its hourly split, so the total is + * spread over the hours of that day that have already passed: a past day is + * flat across all 24, and today only up to the current hour, so the sum is + * visible in the day window straight away. Zero (or an empty amount that + * reaches here) clears the day instead. + */ + function writeDayTotal(currency, dayStart, amount) { + const state = readSpend(); + const dayEnd = dayStart + 24 * HOUR_MS; + for (const key of Object.keys(state.hours)) { + const hour = Number(key); + if (Number.isFinite(hour) && hour >= dayStart && hour < dayEnd) delete state.hours[key]; + } + const value = Number(amount); + const buckets = {}; + if (Number.isFinite(value) && value > 0) { + const elapsed = Math.max(1, Math.min(24, Math.ceil((Math.min(Date.now(), dayEnd) - dayStart) / HOUR_MS))); + const firstHour = hourKey(dayStart); + const perHour = value / elapsed; + for (let index = 0; index < elapsed; index += 1) { + const hour = firstHour + index * HOUR_MS; + addHourSpend(state, currency, hour, perHour); + buckets[String(hour)] = perHour; + } + } + state.currency = currency; + /* The Host replaces just this day, so a manual correction is not undone + * by another window's automatic merge. */ + writeSpend(state, { mode: 'day', day: { start: dayStart, currency, buckets } }); + } + + /** Model id used as a key in the token history. */ + function tokenModelId(model) { + const id = typeof model === 'string' && model.trim() !== '' ? model.trim() : 'unknown'; + return id.length > 64 ? id.slice(0, 64) : id; + } + + /** + * Fold one raw token delta into the hour it was observed in. + * + * Cache writes are stored apart from uncached input: pricing folds them + * together, but the cache tab has to show how much was written into the + * cache versus read from it. + */ + function recordTokenSample(model, delta, at) { + if (delta === undefined || delta === null) return; + const miss = finite(delta.miss) ?? 0; + const write = finite(delta.write) ?? 0; + const hit = finite(delta.hit) ?? 0; + const out = finite(delta.out) ?? 0; + if (miss + write + hit + out <= 0) return; + const state = readSpend(); + const key = String(hourKey(at)); + const id = tokenModelId(model); + const bucket = state.tokens[key] ?? {}; + const entry = bucket[id] ?? { miss: 0, write: 0, hit: 0, out: 0 }; + state.tokens[key] = { + ...bucket, + [id]: { + miss: entry.miss + miss, + write: entry.write + write, + hit: entry.hit + hit, + out: entry.out + out, + }, + }; + pruneSpend(state); + writeSpend(state); + } + + /** Colour band for one spent/limit pair. */ + function limitLevel(spent, limit) { + if (!(limit > 0)) return 'none'; + const ratio = spent / limit; + if (ratio >= 1) return 'over'; + if (ratio >= RATIO_WARN) return 'warn'; + return 'ok'; + } + + /** + * Geometry of the two-tone limit bar. The bar is normalised to the larger + * of the spend and the limit, so an overrun stays inside the card instead + * of being clipped at 100%: the blue part ends exactly at the limit and + * the red part is the excess. With no limit both widths are zero and the + * track stays empty. + */ + function limitBar(spent, limit) { + const over = limit > 0 && spent > limit; + const scale = over ? spent : limit; + /* A visible sliver for a nonzero spend, an empty track for a zero one. */ + const baseWidth = spent > 0 && scale > 0 ? Math.max(2, (Math.min(spent, limit) / scale) * 100) : 0; + return { + over, + baseWidth, + overWidth: over ? Math.max(0, 100 - baseWidth) : 0, + overAmount: over ? spent - limit : 0, + }; + } + + /** + * Live view of the ledger: notified on local writes, pulled from the Host + * while the page is open so another window's records show up too, and + * re-read when the tab becomes visible again. + */ + function useSpendLedger() { + const [state, setState] = React.useState(readSpend); + React.useEffect(() => { + const refresh = () => setState(readSpend()); + const pull = () => { + void pullSpend().finally(refresh); + }; + /* While the old browser storage is in charge, another tab still writes + * there; follow those writes the way the previous version did. */ + const onStorage = () => { + if (spendMode !== 'local') return; + spendState = readLegacySpend(); + refresh(); + }; + const onVisibility = () => { + if (document.visibilityState === 'visible') pull(); + }; + window.addEventListener(SPEND_EVENT, refresh); + window.addEventListener('storage', onStorage); + document.addEventListener('visibilitychange', onVisibility); + const timer = window.setInterval(pull, SPEND_PULL_MS); + return () => { + window.removeEventListener(SPEND_EVENT, refresh); + window.removeEventListener('storage', onStorage); + document.removeEventListener('visibilitychange', onVisibility); + window.clearInterval(timer); + }; + }, []); + return state; + } + + /** Daily Central Bank rates; rerenders the views when they arrive. */ + function useFxRates() { + const [snapshot, setSnapshot] = React.useState(() => ({ + rates: fxRates, + date: fxDate, + status: fxStatus, + })); + React.useEffect(() => { + const refresh = () => setSnapshot({ rates: fxRates, date: fxDate, status: fxStatus }); + window.addEventListener(FX_EVENT, refresh); + if (fxStatus === 'idle') void refreshFxRates(); + return () => window.removeEventListener(FX_EVENT, refresh); + }, []); + return snapshot; + } + + // #endregion + + // #region formatting + + const formatters = new Map(); + + function formatNumber(value, digits) { + try { + let formatter = formatters.get(digits); + if (formatter === undefined) { + formatter = new Intl.NumberFormat(undefined, { + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }); + formatters.set(digits, formatter); + } + return formatter.format(value); + } catch { + return value.toFixed(digits); + } + } + + /** Money for a pill: sub-unit amounts keep enough digits to stay nonzero. */ + function formatMoney(value, currency) { + return formatMoneySymbol(value, CURRENCY_SYMBOL[currency] ?? ''); + } + + /** Money with one explicit currency symbol (third-party operator balances). */ + function formatMoneySymbol(value, symbol) { + const abs = Math.abs(value); + const text = formatNumber(value, abs > 0 && abs < 1 ? 4 : 2); + /* Rubles read as a suffix; other wallet currencies stay prefixed. */ + return symbol === '₽' ? `${text} ${symbol}` : symbol + text; + } + + /** A per-1M rate with its trailing zeros trimmed. */ + function formatRate(value) { + return String(Number(value.toFixed(4))); + } + + /** + * Human name of the provider serving the selected model, for the balance + * reading. Ids come from `modelSelection`; the branded spellings are + * fixed here because an id such as `openrusrouter` does not title-case + * into the operator's own name. + */ + function providerLabel(provider) { + if (provider === undefined || provider === null || provider === '') return 'DeepSeek'; + if (provider === 'deepseek-account' || provider === 'deepseek-official') return 'DeepSeek'; + if (provider === 'openrusrouter') return 'OpenRusRouter'; + return provider.charAt(0).toUpperCase() + provider.slice(1); + } + + // #endregion + + // #region icons + + function CostIcon() { + return h( + 'svg', + { viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': true, style: { display: 'block', flex: 'none' } }, + h('circle', { cx: 8, cy: 8, r: 6, fill: 'none', stroke: 'currentColor', strokeWidth: 1.2 }), + h('path', { + d: 'M5.6 5.1 8 8l2.4-2.9M8 8v3.7M6.1 9.3h3.8', + fill: 'none', + stroke: 'currentColor', + strokeWidth: 1.2, + strokeLinecap: 'round', + strokeLinejoin: 'round', + }), + ); + } + + function BalanceIcon() { + return h( + 'svg', + { viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': true, style: { display: 'block', flex: 'none' } }, + h('rect', { + x: 1.9, + y: 4.3, + width: 12.2, + height: 8.2, + rx: 1.7, + fill: 'none', + stroke: 'currentColor', + strokeWidth: 1.2, + }), + h('path', { d: 'M1.9 7.1h6.2', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }), + h('circle', { cx: 11.3, cy: 10, r: 0.9, fill: 'currentColor' }), + ); + } + + // #endregion + + // #region statistics + + /** + * Money with a compact, integer-leaning rendering for charts and chips. + * The sign goes outside the currency symbol, so a negative remainder reads + * "-200 ₽" / "-$200" rather than "$-200", and the ruble stays a suffix. + */ + function formatShortMoney(value, symbol) { + const abs = Math.abs(value); + const digits = abs > 0 && abs < 1 ? 2 : 0; + const text = formatNumber(abs, digits); + const sign = value < 0 ? '-' : ''; + return symbol === '₽' ? `${sign}${text} ${symbol}` : `${sign}${symbol}${text}`; + } + + function daysInMonth(ms) { + const date = new Date(ms); + return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); + } + + /** 24 hourly totals for one local day. */ + function hourlySeries(state, currency, dayStart) { + const values = []; + for (let hour = 0; hour < 24; hour += 1) { + const from = dayStart + hour * HOUR_MS; + values.push(sumMoney(state, currency, from, from + HOUR_MS - 1)); + } + return values; + } + + /** One total per local day, `count` days from `fromMs`. */ + function dailySeries(state, currency, fromMs, count) { + const cursor = new Date(fromMs); + cursor.setHours(0, 0, 0, 0); + const values = []; + for (let index = 0; index < count; index += 1) { + const from = cursor.getTime(); + values.push(sumMoney(state, currency, from, from + 24 * HOUR_MS - 1)); + cursor.setDate(cursor.getDate() + 1); + } + return values; + } + + function weekdayShort(ms) { + try { + return new Intl.DateTimeFormat(undefined, { weekday: 'short' }).format(new Date(ms)); + } catch { + return String(new Date(ms).getDay()); + } + } + + function dayLabel(ms) { + const date = new Date(ms); + return `${date.getDate()}.${String(date.getMonth() + 1).padStart(2, '0')}`; + } + + /** Compact token counts: 980, 12.4K, 1.23M. */ + function formatTokens(value) { + const abs = Math.abs(value); + if (abs >= 1_000_000) return `${formatNumber(value / 1_000_000, 2)}M`; + if (abs >= 1_000) return `${formatNumber(value / 1_000, abs >= 10_000 ? 0 : 1)}K`; + return formatNumber(value, 0); + } + + function formatPercent(value) { + if (!Number.isFinite(value) || value <= 0) return '0%'; + return `${formatNumber(value >= 10 ? Math.round(value) : Math.round(value * 10) / 10, value >= 10 ? 0 : 1)}%`; + } + + /** Token totals of one window, with the input side folded for display. */ + function tokenTotals(state, fromMs, toMs) { + const totals = { miss: 0, write: 0, hit: 0, out: 0 }; + for (const [key, models] of Object.entries(state.tokens ?? {})) { + const hour = Number(key); + if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue; + for (const entry of Object.values(models ?? {})) { + if (entry === null || typeof entry !== 'object') continue; + totals.miss += finite(entry.miss) ?? 0; + totals.write += finite(entry.write) ?? 0; + totals.hit += finite(entry.hit) ?? 0; + totals.out += finite(entry.out) ?? 0; + } + } + totals.input = totals.miss + totals.write; + totals.total = totals.input + totals.hit + totals.out; + return totals; + } + + /** Cache-read share of the input traffic (hit against hit + input). */ + function cacheShare(totals) { + const inputSide = (totals.input ?? 0) + (totals.hit ?? 0); + return inputSide > 0 ? ((totals.hit ?? 0) / inputSide) * 100 : 0; + } + + /** One row per model of one window, largest first. */ + function tokenModels(state, fromMs, toMs) { + const models = new Map(); + for (const [key, buckets] of Object.entries(state.tokens ?? {})) { + const hour = Number(key); + if (!Number.isFinite(hour) || hour < fromMs || hour > toMs) continue; + for (const [model, entry] of Object.entries(buckets ?? {})) { + if (entry === null || typeof entry !== 'object') continue; + const row = models.get(model) ?? { model, miss: 0, write: 0, hit: 0, out: 0 }; + row.miss += finite(entry.miss) ?? 0; + row.write += finite(entry.write) ?? 0; + row.hit += finite(entry.hit) ?? 0; + row.out += finite(entry.out) ?? 0; + models.set(model, row); + } + } + return [...models.values()] + .map((row) => ({ + ...row, + input: row.miss + row.write, + total: row.miss + row.write + row.hit + row.out, + })) + .sort((left, right) => right.total - left.total); + } + + /** + * Background of one daily bar. Days that went past the daily limit reuse + * the two-tone language of the card bar: blue up to the limit, red above, + * so the days with an overrun stand out in the week/month chart. + */ + function barBackground(value, dayLimit) { + if (!(dayLimit > 0) || value <= dayLimit) return undefined; + const share = (dayLimit / value) * 100; + return ( + 'linear-gradient(to top,' + + ' var(--dsw-alias-state-business-primary) 0 ' + share + '%,' + + ' var(--dsw-alias-state-error-primary) ' + share + '% 100%)' + ); + } + + /** + * Bar chart built from plain flex boxes so it scales with the panel. + * + * `valueLabel` prints the bar's number above it. Adjacent bars are placed + * on two vertical levels: 24 or 31 bars in one row are narrow, and two + * three-digit labels side by side would otherwise collide. + */ + function BarChart({ values, labels, formatTitle, highlight, selected, onSelect, dayLimit, scaleMax, valueLabel }) { + const max = Math.max(1, scaleMax ?? Math.max(...values)); + return h( + 'div', + { className: 'dshStats_chart' }, + h( + 'div', + { className: 'dshStats_bars' }, + values.map((value, index) => { + /* Zero buckets keep an empty slot: no stub bar and no label, so + * the chart shows only hours and days that actually have spend. */ + const heightPct = value > 0 ? Math.max(3, (value / max) * 100) : 0; + const label = valueLabel === undefined ? null : valueLabel(value); + const level = index % 2; + /* The value is a sibling of the bar, not a child: the bar carries + * opacity, and a label inside it would fade together with it. Both + * levels sit above the bar top, so neighbours at a similar height + * never share one row. */ + const labelStyle = + label === null || label === undefined + ? undefined + : { bottom: `calc(${heightPct}% + ${level === 0 ? 2 : 14}px)` }; + return h( + 'div', + { + key: index, + className: 'dshStats_barSlot', + title: formatTitle(index, value), + }, + h('div', { + className: [ + 'dshStats_bar', + highlight === index ? 'dshStats_barCurrent' : '', + selected === index ? 'dshStats_barSelected' : '', + onSelect === undefined ? '' : 'dshStats_barClickable', + ] + .filter((name) => name !== '') + .join(' '), + style: { + height: `${heightPct}%`, + background: barBackground(value, dayLimit), + }, + onClick: onSelect === undefined ? undefined : () => onSelect(index), + }), + label === null || label === undefined + ? null + : h( + 'span', + { + className: 'dshStats_barValue', + 'data-level': level === 0 ? 'low' : 'high', + style: labelStyle, + }, + label, + ), + ); + }), + ), + h( + 'div', + { className: 'dshStats_axis' }, + labels.map((label, index) => h('span', { key: index, className: 'dshStats_axisLabel' }, label)), + ), + ); + } + + /** + * Spending history, period totals, hourly detail, and the soft limits. + * Mounted twice: inside Settings and as a dock overlay. + */ + function StatsPanel({ t, onClose, provider }) { + const spend = useSpendLedger(); + const fx = useFxRates(); + const [period, setPeriod] = React.useState('day'); + const [view, setView] = React.useState('spend'); + const [selectedDay, setSelectedDay] = React.useState(null); + /* The spending tab is the tallest one, and a modal that grows and + * shrinks as the user flips tabs is disorienting. Measure it while it is + * on screen and reserve that height for the shorter tabs; the reserve + * only grows, so expanding a day or switching the period never shrinks + * the dialog under the pointer. */ + const rootRef = React.useRef(null); + const [reservedHeight, setReservedHeight] = React.useState(0); + React.useEffect(() => { + if (view !== 'spend') return; + const node = rootRef.current; + if (node === null || node === undefined) return; + const height = typeof node.offsetHeight === 'number' ? node.offsetHeight : 0; + if (height > 0) setReservedHeight((previous) => (height > previous ? height : previous)); + }, [view, period, selectedDay, spend]); + const now = Date.now(); + /* Limits belong to the provider that bills the selected model; in the + * settings section there is no provider, so the owner that has limits + * wins and they never look as if they disappeared. */ + const limitOwnerId = resolveLimitOwner( + spend, + provider === undefined ? undefined : limitOwner(provider), + ); + const currency = limitCurrency(spend, limitOwnerId, spend.currency); + const symbol = CURRENCY_TO_SYMBOL[currency] ?? ''; + const limits = limitsOf(spend, limitOwnerId); + const limitsKey = `${currency}:${limits.day}:${limits.week}:${limits.month}`; + /* The inputs keep their raw text so a half-typed "0." is not rounded + * away; the ledger stores the parsed number. */ + const draftOf = (value) => ({ + day: value.day > 0 ? String(value.day) : '', + week: value.week > 0 ? String(value.week) : '', + month: value.month > 0 ? String(value.month) : '', + }); + const [draft, setDraft] = React.useState(() => draftOf(limits)); + React.useEffect(() => { + setDraft(draftOf(limits)); + }, [limitsKey]); + + /* Manual correction of one day's total. The per-hour split of a past day + * is rarely worth reconstructing, so the user types the day sum and the + * recorded hours of that day are replaced by it. */ + const [manualDate, setManualDate] = React.useState(() => dateInputValue(Date.now())); + const [manualAmount, setManualAmount] = React.useState(''); + const manualStart = parseDayInput(manualDate); + const manualTotal = + manualStart === undefined ? 0 : sumSpend(spend, currency, manualStart, manualStart + 24 * HOUR_MS - 1); + const manualKey = `${manualDate}:${Math.round(manualTotal * 100)}`; + React.useEffect(() => { + setManualAmount(manualTotal > 0 ? String(Math.round(manualTotal * 100) / 100) : ''); + }, [manualKey]); + + const dayStart = startOfDay(now); + const weekStart = startOfWeek(now); + const monthStart = startOfMonth(now); + const spent = { + day: sumMoney(spend, currency, dayStart, now), + week: sumMoney(spend, currency, weekStart, now), + month: sumMoney(spend, currency, monthStart, now), + }; + + const fxRateLine = + currency === 'RUB' && fx.status === 'ready' && Object.keys(fx.rates).length > 0 + ? t('stats.fxNote', { + rates: Object.entries(fx.rates) + .map(([code, rate]) => `${code} ${formatNumber(rate, 2)} ₽`) + .join(' · '), + }) + : null; + const fxMissingCodes = currency === 'RUB' ? unconvertedCurrencies(spend) : []; + const fxMissingLine = + fxMissingCodes.length > 0 + ? t('stats.fxMissing', { codes: fxMissingCodes.join(', ') }) + : null; + const fxNotes = + fxRateLine === null && fxMissingLine === null + ? null + : h( + 'div', + { className: 'dshStats_fxNotes' }, + fxRateLine === null ? null : h('p', { key: 'rate', className: 'dshStats_hint' }, fxRateLine), + fxMissingLine === null + ? null + : h('p', { key: 'missing', className: 'dshStats_hint' }, fxMissingLine), + ); + + /* Values printed on the bars: plain numbers, no kopecks and no currency + * symbol (the currency is already named by the section subtitle). A + * smeared delta can leave a fraction in a bucket; rounding it to zero + * must not print "0" on the chart, so only a non-zero rounded value is + * labelled and drawn at all. */ + const moneyValueLabel = (value) => { + const rounded = Math.round(value); + return rounded > 0 ? formatNumber(rounded, 0) : null; + }; + const tokenValueLabel = (value) => { + const rounded = Math.round(value); + return rounded > 0 ? formatTokens(rounded) : null; + }; + const shareValueLabel = (value) => { + const rounded = Math.round(value); + return rounded > 0 ? formatPercent(rounded) : null; + }; + + const periodName = (key) => t(`stats.period.${key}`); + const levelOf = (key) => limitLevel(spent[key], limits[key]); + + const cards = h( + 'div', + { className: 'dshStats_cards' }, + LIMIT_PERIODS.map((key) => { + const level = levelOf(key); + const limit = limits[key]; + const spentNow = spent[key]; + const bar = limitBar(spentNow, limit); + return h( + 'button', + { + key, + type: 'button', + className: ['dshStats_card', period === key ? 'dshStats_cardActive' : ''].filter(Boolean).join(' '), + 'data-level': level, + onClick: () => { + setPeriod(key); + setSelectedDay(null); + }, + }, + h('span', { className: 'dshStats_cardLabel' }, periodName(key)), + h('span', { className: 'dshStats_cardValue' }, formatShortMoney(spentNow, symbol)), + h( + 'span', + { className: 'dshStats_cardLimit' }, + limit > 0 + ? bar.over + ? t('stats.overLimit', { + over: formatShortMoney(bar.overAmount, symbol), + limit: formatShortMoney(limit, symbol), + }) + : t('stats.ofLimit', { limit: formatShortMoney(limit, symbol) }) + : t('stats.noLimit'), + ), + h( + 'span', + { className: 'dshStats_progress' }, + bar.baseWidth > 0 + ? h('span', { + className: 'dshStats_progressFill', + style: { width: `${bar.baseWidth}%` }, + }) + : null, + bar.overWidth > 0 + ? h('span', { + className: 'dshStats_progressOver', + style: { width: `${bar.overWidth}%` }, + }) + : null, + ), + ); + }), + ); + + let chart; + let detail = null; + if (period === 'day') { + const values = hourlySeries(spend, currency, dayStart); + chart = h(BarChart, { + values, + labels: values.map((_, hour) => (hour % 3 === 0 ? String(hour) : '')), + formatTitle: (hour, value) => + t('stats.hourTitle', { + hour: String(hour).padStart(2, '0'), + amount: formatShortMoney(value, symbol), + }), + highlight: new Date(now).getHours(), + valueLabel: moneyValueLabel, + }); + } else { + const count = period === 'week' ? 7 : daysInMonth(now); + const from = period === 'week' ? weekStart : monthStart; + const values = dailySeries(spend, currency, from, count); + const dayStarts = []; + const walker = new Date(from); + walker.setHours(0, 0, 0, 0); + for (let index = 0; index < count; index += 1) { + dayStarts.push(walker.getTime()); + walker.setDate(walker.getDate() + 1); + } + const selectedIndex = selectedDay === null ? -1 : dayStarts.indexOf(startOfDay(selectedDay)); + chart = h(BarChart, { + values, + labels: dayStarts.map((day, index) => + period === 'week' ? weekdayShort(day) : index % 5 === 0 ? String(new Date(day).getDate()) : '', + ), + formatTitle: (index, value) => + limits.day > 0 && value > limits.day + ? t('stats.dayOverTitle', { + date: dayLabel(dayStarts[index]), + amount: formatShortMoney(value, symbol), + over: formatShortMoney(value - limits.day, symbol), + }) + : t('stats.dayTitle', { + date: dayLabel(dayStarts[index]), + amount: formatShortMoney(value, symbol), + }), + highlight: dayStarts.indexOf(dayStart), + selected: selectedIndex >= 0 ? selectedIndex : undefined, + onSelect: (index) => setSelectedDay(dayStarts[index]), + dayLimit: limits.day, + valueLabel: moneyValueLabel, + }); + if (selectedDay !== null) { + const detailStart = startOfDay(selectedDay); + const hours = hourlySeries(spend, currency, detailStart); + detail = h( + 'div', + { className: 'dshStats_detail' }, + h( + 'div', + { className: 'dshStats_detailHeader' }, + h( + 'span', + { className: 'dshStats_detailTitle' }, + t('stats.hourlyFor', { date: dayLabel(detailStart) }), + ), + h( + 'button', + { + type: 'button', + className: 'dshStats_linkButton', + onClick: () => setSelectedDay(null), + }, + t('stats.back'), + ), + ), + h(BarChart, { + values: hours, + labels: hours.map((_, hour) => (hour % 3 === 0 ? String(hour) : '')), + formatTitle: (hour, value) => + t('stats.hourTitle', { + hour: String(hour).padStart(2, '0'), + amount: formatShortMoney(value, symbol), + }), + valueLabel: moneyValueLabel, + }), + ); + } + } + + const periodLimit = limits[period]; + const periodSpent = spent[period]; + const periodOver = periodLimit > 0 && periodSpent > periodLimit; + const summary = h( + 'div', + { className: 'dshStats_summary' }, + h('span', { className: 'dshStats_summaryAmount', 'data-level': levelOf(period) }, formatShortMoney(periodSpent, symbol)), + periodLimit > 0 + ? h( + 'span', + { className: 'dshStats_summaryNote', 'data-level': periodOver ? 'over' : undefined }, + periodOver + ? t('stats.overLimit', { + over: formatShortMoney(periodSpent - periodLimit, symbol), + limit: formatShortMoney(periodLimit, symbol), + }) + : t('stats.leftOfLimit', { + left: formatShortMoney(Math.max(0, periodLimit - periodSpent), symbol), + limit: formatShortMoney(periodLimit, symbol), + }), + ) + : h('span', { className: 'dshStats_summaryNote' }, t('stats.noLimit')), + ); + + /* Tokens and cache reuse the period selector and the same hourly/daily + * buckets as the spending chart. */ + const bucketStep = period === 'day' ? HOUR_MS : 24 * HOUR_MS; + const bucketStarts = []; + if (period === 'day') { + for (let hour = 0; hour < 24; hour += 1) bucketStarts.push(dayStart + hour * HOUR_MS); + } else { + const count = period === 'week' ? 7 : daysInMonth(now); + const walker = new Date(period === 'week' ? weekStart : monthStart); + walker.setHours(0, 0, 0, 0); + for (let index = 0; index < count; index += 1) { + bucketStarts.push(walker.getTime()); + walker.setDate(walker.getDate() + 1); + } + } + const periodFrom = period === 'day' ? dayStart : period === 'week' ? weekStart : monthStart; + const bucketTotals = bucketStarts.map((start) => tokenTotals(spend, start, start + bucketStep - 1)); + const tokenPeriod = tokenTotals(spend, periodFrom, now); + const modelRows = tokenModels(spend, periodFrom, now); + const bucketLabels = + period === 'day' + ? bucketStarts.map((_, hour) => (hour % 3 === 0 ? String(hour) : '')) + : period === 'week' + ? bucketStarts.map((day) => weekdayShort(day)) + : bucketStarts.map((day, index) => (index % 5 === 0 ? String(new Date(day).getDate()) : '')); + const chartHighlight = period === 'day' ? new Date(now).getHours() : bucketStarts.indexOf(dayStart); + const tokenTitle = (index, value) => + period === 'day' + ? t('stats.tokens.hourTitle', { hour: String(index).padStart(2, '0'), amount: formatTokens(value) }) + : t('stats.tokens.dayTitle', { date: dayLabel(bucketStarts[index]), amount: formatTokens(value) }); + const cacheTitle = (index, value) => + period === 'day' + ? t('stats.cache.hourTitle', { hour: String(index).padStart(2, '0'), percent: formatPercent(value) }) + : t('stats.cache.dayTitle', { date: dayLabel(bucketStarts[index]), percent: formatPercent(value) }); + + const modelTable = (columns) => + h( + 'div', + { className: 'dshStats_tableBlock' }, + h('div', { className: 'dshStats_chartTitle' }, t('stats.tokens.byModel')), + modelRows.length === 0 + ? h('p', { className: 'dshStats_hint' }, t('stats.tokens.empty')) + : h( + 'div', + { className: 'dshStats_table' }, + h( + 'div', + { className: 'dshStats_tableRow dshStats_tableHead' }, + h('span', null, t('stats.tokens.model')), + columns.map((column) => + h('span', { key: column.key, className: 'dshStats_num' }, t(column.label)), + ), + ), + modelRows.map((row) => + h( + 'div', + { key: row.model, className: 'dshStats_tableRow' }, + h('span', { className: 'dshStats_modelCell', title: row.model }, row.model), + columns.map((column) => + h('span', { key: column.key, className: 'dshStats_num' }, column.value(row)), + ), + ), + ), + ), + ); + + const tokenCards = h( + 'div', + { className: 'dshStats_cards' }, + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.input')), + h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.input)), + h( + 'span', + { className: 'dshStats_cardLimit' }, + t('stats.tokens.writeNote', { amount: formatTokens(tokenPeriod.write) }), + ), + ), + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.cached')), + h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.hit)), + h( + 'span', + { className: 'dshStats_cardLimit' }, + t('stats.cache.shareNote', { percent: formatPercent(cacheShare(tokenPeriod)) }), + ), + ), + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.tokens.output')), + h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.out)), + h( + 'span', + { className: 'dshStats_cardLimit' }, + t('stats.tokens.totalNote', { amount: formatTokens(tokenPeriod.total) }), + ), + ), + ); + + const cacheCards = h( + 'div', + { className: 'dshStats_cards' }, + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.ratio')), + h('span', { className: 'dshStats_cardValue' }, formatPercent(cacheShare(tokenPeriod))), + h( + 'span', + { className: 'dshStats_cardLimit' }, + t('stats.cache.summaryNote', { + hit: formatTokens(tokenPeriod.hit), + total: formatTokens(tokenPeriod.input + tokenPeriod.hit), + }), + ), + ), + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.hit')), + h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.hit)), + ), + h( + 'div', + { className: 'dshStats_card dshStats_cardStatic' }, + h('span', { className: 'dshStats_cardLabel' }, t('stats.cache.miss')), + h('span', { className: 'dshStats_cardValue' }, formatTokens(tokenPeriod.input)), + ), + ); + + const tokensContent = [ + tokenCards, + h( + 'div', + { className: 'dshStats_summary' }, + h('span', { className: 'dshStats_summaryAmount' }, formatTokens(tokenPeriod.total)), + h('span', { className: 'dshStats_summaryNote' }, t('stats.tokens.unit')), + ), + h( + 'div', + { className: 'dshStats_chartBlock' }, + h( + 'div', + { className: 'dshStats_chartTitle' }, + period === 'day' ? t('stats.byHour') : t('stats.byDay'), + ), + h(BarChart, { + values: bucketTotals.map((totals) => totals.total), + labels: bucketLabels, + formatTitle: tokenTitle, + highlight: chartHighlight, + valueLabel: tokenValueLabel, + }), + ), + modelTable([ + { key: 'input', label: 'stats.tokens.input', value: (row) => formatTokens(row.input) }, + { key: 'hit', label: 'stats.tokens.cached', value: (row) => formatTokens(row.hit) }, + { key: 'out', label: 'stats.tokens.output', value: (row) => formatTokens(row.out) }, + ]), + ]; + + const cacheContent = [ + cacheCards, + h( + 'div', + { className: 'dshStats_chartBlock' }, + h( + 'div', + { className: 'dshStats_chartTitle' }, + period === 'day' ? t('stats.byHour') : t('stats.byDay'), + ), + h(BarChart, { + values: bucketTotals.map((totals) => cacheShare(totals)), + labels: bucketLabels, + formatTitle: cacheTitle, + highlight: chartHighlight, + scaleMax: 100, + valueLabel: shareValueLabel, + }), + ), + modelTable([ + { key: 'hit', label: 'stats.cache.hit', value: (row) => formatTokens(row.hit) }, + { key: 'miss', label: 'stats.cache.miss', value: (row) => formatTokens(row.input) }, + { key: 'share', label: 'stats.cache.ratio', value: (row) => formatPercent(cacheShare(row)) }, + ]), + ]; + + + const applyLimits = (next) => { + setDraft(next); + writeLimits(limitOwnerId, currency, next); + }; + + const deriveFromMonth = () => { + const month = Number(draft.month); + if (!Number.isFinite(month) || month <= 0) return; + applyLimits({ + day: String(Math.round(month / 30)), + week: String(Math.round((month * 7) / 30)), + month: String(Math.round(month)), + }); + }; + + /* Readings recorded before the ledger learned to ignore bookkeeping + * changes stay in the history; one click drops them without touching the + * limits. */ + const resetHistory = () => { + const ask = typeof window === 'undefined' ? undefined : window.confirm; + if (typeof ask === 'function' && !ask(t('stats.resetConfirm'))) return; + clearSpendHistory(); + }; + + const applyManualDay = () => { + if (manualStart === undefined) return; + const text = String(manualAmount).trim(); + if (text === '') return; + /* A decimal comma is what the Russian keyboard produces; an unparsable + * amount must not silently clear the day. */ + const parsed = Number(text.replace(',', '.')); + if (!Number.isFinite(parsed) || parsed < 0) return; + writeDayTotal(currency, manualStart, parsed); + }; + + const historyContent = [ + h( + 'div', + { className: 'dshStats_limitsBlock' }, + h('h3', { className: 'dshStats_limitsTitle' }, t('stats.manualTitle')), + h('p', { className: 'dshStats_hint' }, t('stats.manualHint', { symbol })), + h( + 'div', + { className: 'dshStats_manualRow' }, + h( + 'label', + { className: 'dshStats_limitField' }, + h('span', { className: 'dshStats_limitLabel' }, t('stats.manualDay')), + h( + 'span', + { className: 'dshStats_inputWrap' }, + h('input', { + type: 'date', + className: 'dshStats_input dshStats_date', + value: manualDate, + max: dateInputValue(Date.now()), + onChange: (event) => setManualDate(event.target.value), + }), + ), + ), + h( + 'label', + { className: 'dshStats_limitField' }, + h('span', { className: 'dshStats_limitLabel' }, t('stats.manualTotal')), + h( + 'span', + { className: 'dshStats_inputWrap' }, + h('input', { + type: 'number', + min: '0', + step: '10', + inputMode: 'decimal', + className: 'dshStats_input', + value: manualAmount, + placeholder: t('stats.notSet'), + onChange: (event) => setManualAmount(event.target.value), + }), + h('span', { className: 'dshStats_symbol' }, symbol), + ), + ), + h('button', { type: 'button', className: 'dshStats_button', onClick: applyManualDay }, t('stats.manualApply')), + ), + h( + 'div', + { className: 'dshStats_actions' }, + h('button', { type: 'button', className: 'dshStats_button', onClick: resetHistory }, t('stats.resetHistory')), + h('span', { className: 'dshStats_hint' }, t('stats.resetHint')), + ), + ), + ]; + + return h( + 'div', + { + ref: rootRef, + className: 'dshStats_root', + style: view === 'spend' || reservedHeight === 0 ? undefined : { minHeight: `${reservedHeight}px` }, + }, + h( + 'div', + { className: 'dshStats_header' }, + h( + 'div', + { className: 'dshStats_titles' }, + h('h2', { className: 'dshStats_title' }, t('stats.title')), + h( + 'p', + { className: 'dshStats_subtitle' }, + view === 'spend' + ? t('stats.subtitle', { symbol }) + : view === 'tokens' + ? t('stats.tokens.subtitle') + : view === 'cache' + ? t('stats.cache.subtitle') + : t('stats.history.subtitle'), + ), + ), + onClose === undefined + ? null + : h( + 'button', + { + type: 'button', + className: 'dshStats_close', + onClick: onClose, + 'aria-label': t('stats.close'), + title: t('stats.close'), + }, + '×', + ), + ), + h( + 'div', + { className: 'dshStats_periods' }, + LIMIT_PERIODS.map((key) => + h( + 'button', + { + key, + type: 'button', + className: ['dshStats_period', period === key ? 'dshStats_periodActive' : ''].filter(Boolean).join(' '), + onClick: () => { + setPeriod(key); + setSelectedDay(null); + }, + }, + periodName(key), + ), + ), + ), + h( + 'div', + { className: 'dshStats_views' }, + [ + ['spend', 'stats.view.spend'], + ['tokens', 'stats.view.tokens'], + ['cache', 'stats.view.cache'], + ['history', 'stats.view.history'], + ].map(([id, key]) => + h( + 'button', + { + key: id, + type: 'button', + className: ['dshStats_view', view === id ? 'dshStats_viewActive' : ''].filter(Boolean).join(' '), + onClick: () => { + setView(id); + setSelectedDay(null); + }, + }, + t(key), + ), + ), + ), + view === 'spend' + ? [ + cards, + summary, + fxNotes, + h( + 'div', + { className: 'dshStats_chartBlock' }, + h( + 'div', + { className: 'dshStats_chartTitle' }, + period === 'day' ? t('stats.byHour') : t('stats.byDay'), + ), + chart, + period === 'day' + ? null + : [ + h('p', { key: 'click', className: 'dshStats_hint' }, t('stats.clickHint')), + limits.day > 0 + ? h('p', { key: 'over', className: 'dshStats_hint' }, t('stats.overDaysHint')) + : null, + ], + ), + detail, + h( + 'div', + { className: 'dshStats_limitsBlock' }, + h('h3', { className: 'dshStats_limitsTitle' }, t('stats.limitsTitle')), + h( + 'p', + { className: 'dshStats_hint' }, + t('stats.limitsOwnerHint', { provider: limitOwnerLabel(limitOwnerId), symbol }), + ), + h( + 'div', + { className: 'dshStats_limitRow' }, + LIMIT_PERIODS.map((key) => + h( + 'label', + { key, className: 'dshStats_limitField' }, + h('span', { className: 'dshStats_limitLabel' }, t(`stats.limit.${key}`)), + h( + 'span', + { className: 'dshStats_inputWrap' }, + h('input', { + type: 'number', + min: '0', + step: '10', + inputMode: 'decimal', + className: 'dshStats_input', + value: draft[key], + placeholder: t('stats.notSet'), + onChange: (event) => { + applyLimits({ ...draft, [key]: event.target.value }); + }, + }), + h('span', { className: 'dshStats_symbol' }, symbol), + ), + ), + ), + ), + h( + 'div', + { className: 'dshStats_actions' }, + h('button', { type: 'button', className: 'dshStats_button', onClick: deriveFromMonth }, t('stats.derive')), + h('span', { className: 'dshStats_hint' }, t('stats.deriveHint')), + ), + ), + ] + : view === 'tokens' + ? tokensContent + : view === 'cache' + ? cacheContent + : historyContent, + ); + } + + /** + * Reload action in the sidebar footer, beside the settings and profile + * rows. A page reload re-fetches the shell and every client plugin bundle; + * running agents live in the Host process, so the sessions keep working and + * the page simply reconnects to them. + */ + function ReloadButton({ wide, t }) { + return h( + 'div', + { className: 'dshReload_wrap', 'data-wide': wide === false ? 'false' : 'true' }, + h( + 'button', + { + type: 'button', + className: 'dshReload_button', + title: t('quickReload.title'), + 'aria-label': t('quickReload.title'), + 'data-composer-stat': 'reload', + onClick: () => { + try { + window.location.reload(); + } catch { + /* A test rig without a location cannot reload. */ + } + }, + }, + h( + 'svg', + { + viewBox: '0 0 16 16', + width: 16, + height: 16, + fill: 'none', + stroke: 'currentColor', + strokeWidth: 1.4, + strokeLinecap: 'round', + strokeLinejoin: 'round', + 'aria-hidden': true, + }, + h('path', { d: 'M12.6 8a4.6 4.6 0 1 1-1.35-3.25' }), + h('path', { d: 'M12.6 2.55v2.5h-2.5' }), + ), + /* The rail has no room for a caption; the pill shows it when wide. */ + wide === false ? null : h('span', { className: 'dshReload_label' }, t('quickReload.label')), + ), + ); + } + + /** + * Clock: today's remaining budget. Same 16x16 viewBox, stroke width, and + * circle radius as the balance and spend icons, so the three glyphs share + * one optical size and baseline in the dock row. + */ + function DayIcon() { + return h( + 'svg', + { + viewBox: '0 0 16 16', + width: 16, + height: 16, + 'aria-hidden': true, + style: { display: 'block', flex: 'none' }, + }, + h('circle', { + cx: 8, + cy: 8, + r: 6, + fill: 'none', + stroke: 'currentColor', + strokeWidth: 1.2, + }), + h('path', { + d: 'M8 4.9V8l2.3 1.4', + fill: 'none', + stroke: 'currentColor', + strokeWidth: 1.2, + strokeLinecap: 'round', + strokeLinejoin: 'round', + }), + ); + } + + // #endregion + + // #region component + + function sumWallets(wallets, currency) { + let total = 0; + for (const wallet of wallets ?? []) { + if (wallet === null || typeof wallet !== 'object') continue; + if (wallet.currency !== currency) continue; + const amount = Number(wallet.balance); + if (Number.isFinite(amount)) total += amount; + } + return total; + } + + function pickCurrency(wallets, bonusWallets) { + for (const wallet of wallets ?? []) { + if (wallet && (wallet.currency === 'CNY' || wallet.currency === 'USD')) return wallet.currency; + } + for (const wallet of bonusWallets ?? []) { + if (wallet && (wallet.currency === 'CNY' || wallet.currency === 'USD')) return wallet.currency; + } + return DEFAULT_CURRENCY; + } + + function CostBalanceDock({ useProjection, sessionId, t, fetchBalance }) { + const usage = useProjection('tokenUsage'); + const selection = useProjection('modelSelection'); + const model = + selection?.pending?.model ?? selection?.lastUsed?.model ?? DEFAULT_MODEL; + /* DeepSeek rates only describe DeepSeek routes; another provider's + * requests are not priced with them. */ + const provider = selection?.pending?.provider ?? selection?.lastUsed?.provider; + const pricedProvider = + provider === undefined || + provider === 'deepseek-account' || + provider === 'deepseek-official'; + const usageKey = + usage === undefined || usage === null + ? 'none' + : `${usage.uncachedInputTokens}/${usage.cacheReadTokens}/${usage.cacheWriteTokens}/${usage.outputTokens}`; + + const ledgerRef = React.useRef(null); + if (ledgerRef.current === null || ledgerRef.current.sessionId !== sessionId) { + ledgerRef.current = createLedger(sessionId); + } + const ledger = ledgerRef.current; + const [, bump] = React.useReducer((value) => value + 1, 0); + React.useEffect(() => { + if (usage === undefined || usage === null) return; + const delta = ledger.observe(usage, model, pricedProvider); + /* Tokens are real for every route, priced or not: the history keeps + * them so the token and cache tabs are not limited to DeepSeek. */ + if (delta !== undefined) recordTokenSample(model, delta, Date.now()); + bump(); + }, [usageKey, model, pricedProvider, ledger]); + + /* Current DeepSeek tariff band: idle (cheaper) or peak (full price). */ + const [band, setBand] = React.useState(() => bandAt(Date.now())); + React.useEffect(() => { + const timer = window.setInterval(() => setBand(bandAt(Date.now())), TARIFF_POLL_MS); + return () => window.clearInterval(timer); + }, []); + + const [balance, setBalance] = React.useState({ status: 'loading' }); + /* Read inside the fetch callback, which outlives a route change. */ + const pricedRef = React.useRef(pricedProvider); + pricedRef.current = pricedProvider; + const mounted = React.useRef(true); + const inFlight = React.useRef(false); + const lastRead = React.useRef(0); + React.useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + + const refresh = React.useCallback( + (force) => { + if (inFlight.current) return; + if (!force && Date.now() - lastRead.current < BALANCE_MIN_INTERVAL_MS) return; + inFlight.current = true; + lastRead.current = Date.now(); + Promise.resolve() + .then(fetchBalance) + .then( + (value) => { + inFlight.current = false; + if (!mounted.current) return; + if (value !== null && pricedRef.current) { + /* Every reading is one spend sample. The DeepSeek wallet has + * no separate usage counter, so the whole wallet is the meter + * and a top-up simply rebases it. A third-party route hands + * over its own counter below. */ + const walletCurrency = pickCurrency(value.wallets, value.bonusWallets); + const remaining = + sumWallets(value.wallets, walletCurrency) + sumWallets(value.bonusWallets, walletCurrency); + recordBalanceSample( + 'deepseek', + { amount: remaining, wallet: remaining }, + walletCurrency, + Date.now(), + ); + } + setBalance( + value === null + ? { status: 'unavailable' } + : { status: 'ready', wallets: value.wallets, bonusWallets: value.bonusWallets }, + ); + }, + () => { + inFlight.current = false; + if (mounted.current) setBalance({ status: 'unavailable' }); + }, + ); + }, + [fetchBalance], + ); + + React.useEffect(() => { + refresh(true); + }, [refresh]); + React.useEffect(() => { + refresh(false); + }, [usageKey, refresh]); + React.useEffect(() => { + const timer = window.setInterval(() => { + if (document.visibilityState === 'visible') refresh(false); + }, BALANCE_POLL_MS); + return () => window.clearInterval(timer); + }, [refresh]); + + /* A model from a third-party route shows that operator's wallet instead + * of the DeepSeek account wallet. The Host half owns the API key and + * answers this same-origin route. */ + const operatorProvider = pricedProvider ? null : provider ?? null; + const [operator, setOperator] = React.useState({ status: 'idle' }); + const operatorGeneration = React.useRef(0); + const refreshOperator = React.useCallback(() => { + if (operatorProvider === null) { + setOperator({ status: 'idle' }); + return; + } + const generation = ++operatorGeneration.current; + setOperator({ status: 'loading', provider: operatorProvider }); + fetch( + `/api/cost-balance/operator-balance?provider=${encodeURIComponent(operatorProvider)}`, + { cache: 'no-store', credentials: 'same-origin' }, + ) + /* Every miss carries a short code so the tooltip can say why the + * reading is a dash: a missing Host route, an unreachable gateway, + * or a credential the Host could not resolve. */ + .then((response) => { + if (!response.ok) return { ok: false, reason: `http-${String(response.status)}` }; + return response.json().catch(() => ({ ok: false, reason: 'bad-payload' })); + }) + .then( + (payload) => { + if (generation !== operatorGeneration.current) return; + if (payload !== null && payload.ok === true && Number.isFinite(Number(payload.amount))) { + const amount = Number(payload.amount); + const operatorSymbol = + typeof payload.symbol === 'string' && payload.symbol !== '' ? payload.symbol : '$'; + const operatorCurrency = SYMBOL_TO_CURRENCY[operatorSymbol] ?? 'RUB'; + setOperator({ + status: 'ready', + provider: operatorProvider, + label: typeof payload.displayName === 'string' && payload.displayName !== '' + ? payload.displayName + : operatorProvider, + amount, + symbol: operatorSymbol, + currency: operatorCurrency, + /* The key's own spending cap; the pill shows what is left + * under it in parentheses, the way the cabinet describes it. */ + limit: finite(payload.limit), + used: finite(payload.used), + }); + /* The displayed operator remainder is capped by the key's own + * limit, so it is never the spend meter: the gateway's usage + * counter (or, failing that, the whole wallet) is. */ + recordBalanceSample( + operatorProvider, + { + amount, + wallet: finite(payload.wallet), + used: finite(payload.used), + cap: finite(payload.limit), + window: typeof payload.window === 'string' ? payload.window : undefined, + resetsAt: typeof payload.resetsAt === 'string' ? payload.resetsAt : undefined, + }, + operatorCurrency, + Date.now(), + ); + } else if (payload !== null && payload.reason === 'unknown-provider') { + setOperator({ status: 'unknown', provider: operatorProvider }); + } else { + setOperator({ + status: 'unavailable', + provider: operatorProvider, + reason: typeof payload?.reason === 'string' ? payload.reason : 'unknown', + }); + } + }, + () => { + if (generation === operatorGeneration.current) { + setOperator({ status: 'unavailable', provider: operatorProvider, reason: 'network' }); + } + }, + ); + }, [operatorProvider]); + React.useEffect(() => { + refreshOperator(); + }, [refreshOperator]); + React.useEffect(() => { + if (operatorProvider === null) return undefined; + const timer = window.setInterval(() => { + if (document.visibilityState === 'visible') refreshOperator(); + }, BALANCE_POLL_MS); + return () => window.clearInterval(timer); + }, [operatorProvider, refreshOperator]); + + const spend = useSpendLedger(); + const [statsOpen, setStatsOpen] = React.useState(false); + React.useEffect(() => { + if (!statsOpen) return undefined; + const onKeyDown = (event) => { + if (event.key === 'Escape') setStatsOpen(false); + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, [statsOpen]); + + const wallets = balance.status === 'ready' ? balance.wallets : null; + const bonusWallets = balance.status === 'ready' ? balance.bonusWallets : null; + const currency = pickCurrency(wallets, bonusWallets); + const symbol = CURRENCY_SYMBOL[currency] ?? ''; + const price = priceOf(model, currency); + const billedTokens = + usage === undefined || usage === null + ? 0 + : count(usage.uncachedInputTokens) + + count(usage.cacheReadTokens) + + count(usage.cacheWriteTokens) + + count(usage.outputTokens); + const hasUsage = billedTokens > 0 && pricedProvider; + + /* Limits are kept per wallet currency; the reading colours follow the + * money the current model is actually billed in. */ + const displayCurrency = + operator.status === 'ready' && operator.provider === operatorProvider + ? operator.currency ?? 'RUB' + : currency; + /* Whole minutes: the total stays stable across streaming re-renders and + * only moves when the ledger changes or a minute passes. */ + const nowMs = Math.floor(Date.now() / 60_000) * 60_000; + const dayStartMs = startOfDay(nowMs); + /* Limits belong to the provider that bills the selected model: the + * operator wallet is in rubles, the DeepSeek account in its own wallet + * currency. A fallback keeps a compatible reading when the current + * provider has no limit set but another one does. */ + useFxRates(); + const dayOwner = limitOwner(provider); + const ownerLimits = limitsOf(spend, dayOwner); + const ownerCurrency = limitCurrency(spend, dayOwner, displayCurrency); + const limitedOwners = Object.keys(spend.limits ?? {}).filter( + (owner) => limitsOf(spend, owner).day > 0, + ); + const fallbackOwner = + limitedOwners.find( + (owner) => sumMoney(spend, limitCurrency(spend, owner, displayCurrency), dayStartMs, nowMs) > 0, + ) ?? limitedOwners[0]; + const dayCurrency = + ownerLimits.day > 0 + ? ownerCurrency + : fallbackOwner === undefined + ? displayCurrency + : limitCurrency(spend, fallbackOwner, displayCurrency); + const daySymbol = CURRENCY_TO_SYMBOL[dayCurrency] ?? symbol; + const spendLimits = ownerLimits.day > 0 ? ownerLimits : limitsOf(spend, fallbackOwner); + const spentDay = React.useMemo( + () => sumMoney(spend, dayCurrency, dayStartMs, nowMs), + [spend, dayCurrency, nowMs], + ); + const dayLevel = limitLevel(spentDay, spendLimits.day); + /* The reading is the remaining daily budget; past the limit it goes + * negative, so the overrun reads as "-200 ₽" in the error colour + * instead of a clamped "0 ₽". */ + const dayRemaining = spendLimits.day - spentDay; + const dayOver = spentDay > spendLimits.day; + + const readings = []; + if (hasUsage) { + const spent = ledger.cost(currency); + const amount = formatMoney(spent, currency); + const rates = t('cost.rates', { + input: symbol + formatRate(price.miss), + cache: symbol + formatRate(price.hit), + output: symbol + formatRate(price.output), + }); + const detail = t('cost.title', { rates, model: pricedModel(model) }); + readings.push( + h( + 'span', + { key: 'cost', className: 'dshCostBalance_anchor', 'data-composer-stat': 'cost' }, + h( + 'span', + { className: 'dshCostBalance_pill', title: detail }, + h(CostIcon), + h('span', { className: 'dshCostBalance_label' }, t('cost', { amount })), + ), + ), + ); + } + + let balanceText; + let balanceDetail; + let balanceProvider; + const operatorReading = + operatorProvider !== null && operator.provider === operatorProvider && operator.status === 'ready'; + const operatorPending = + operatorProvider !== null && + operator.provider === operatorProvider && + (operator.status === 'loading' || operator.status === 'unavailable'); + /* The key-limited remainder shown in parentheses, when the operator + * reports both its cap and the window's spend; the account wallet stays + * the reading itself, so a limit edit can never look like money. */ + const operatorRemaining = + operatorReading && Number.isFinite(operator.limit) && Number.isFinite(operator.used) + ? Math.max(0, operator.limit - operator.used) + : undefined; + if (operatorReading) { + const amount = formatMoneySymbol(operator.amount, operator.symbol); + balanceText = amount; + balanceProvider = operator.label ?? providerLabel(operator.provider); + balanceDetail = + operatorRemaining === undefined + ? t('balance.operator.title', { provider: balanceProvider, amount }) + : t('balance.operator.titleKey', { + provider: balanceProvider, + amount, + remaining: formatMoneySymbol(operatorRemaining, operator.symbol), + }); + } else if (operatorPending) { + balanceText = operator.status === 'loading' ? '…' : '—'; + balanceProvider = providerLabel(operator.provider); + balanceDetail = + operator.status === 'unavailable' && typeof operator.reason === 'string' + ? t('balance.operator.unavailableReason', { + provider: balanceProvider, + reason: operator.reason, + }) + : t('balance.operator.unavailable', { provider: balanceProvider }); + } else if (balance.status === 'ready') { + balanceProvider = providerLabel(provider); + const recharge = sumWallets(wallets, currency); + const bonus = sumWallets(bonusWallets, currency); + balanceText = formatMoney(recharge + bonus, currency); + balanceDetail = + bonus > 0 + ? t('balance.title', { + recharge: formatMoney(recharge, currency), + bonus: formatMoney(bonus, currency), + }) + : t('balance.title.plain', { recharge: formatMoney(recharge, currency) }); + } else if (balance.status === 'loading') { + balanceText = '…'; + balanceProvider = providerLabel(provider); + balanceDetail = t('balance.title.unavailable'); + } else { + balanceText = '—'; + balanceProvider = providerLabel(provider); + balanceDetail = t('balance.title.unavailable'); + } + const balanceReading = h( + 'span', + { className: 'dshCostBalance_anchor', 'data-composer-stat': 'balance' }, + h( + 'button', + { + type: 'button', + className: 'dshCostBalance_pill', + title: balanceDetail, + 'aria-label': t('refresh'), + onClick: () => { + if (operatorProvider !== null) refreshOperator(); + else refresh(true); + }, + }, + h(BalanceIcon), + h('span', { className: 'dshCostBalance_label' }, balanceText), + h( + 'span', + { className: 'dshCostBalance_provider' }, + operatorRemaining === undefined + ? t('balance.provider', { provider: balanceProvider }) + : t('balance.keyLimit', { + amount: formatMoneySymbol(operatorRemaining, operator.symbol), + }), + ), + ), + ); + readings.push( + h( + 'span', + { key: 'balance', className: 'dshCostBalance_pair' }, + pricedProvider + ? h( + 'span', + { + key: 'tariff', + className: 'dshCostBalance_lampAnchor', + 'data-band': band, + 'data-composer-stat': 'tariff', + title: t(band === 'peak' ? 'tariff.peak' : 'tariff.idle'), + }, + h('span', { className: 'dshCostBalance_lamp', 'aria-hidden': true }), + ) + : null, + balanceReading, + ), + ); + + /* The day budget sits right after the balance, in the same type, coloured + * by how much of today's limit is already used; clicking opens the + * statistics. Without a daily limit there is nothing to colour, so the + * same seat stays as the plain entry point to the section. */ + const dayReading = + spendLimits.day > 0 + ? h( + 'span', + { key: 'limits', className: 'dshCostBalance_anchor' }, + h( + 'button', + { + type: 'button', + className: 'dshCostBalance_pill dshCostBalance_chip', + 'data-level': dayLevel, + 'data-composer-stat': 'limit-day', + title: dayOver + ? t('limits.dayOverTitle', { + spent: formatShortMoney(spentDay, daySymbol), + limit: formatShortMoney(spendLimits.day, daySymbol), + over: formatShortMoney(spentDay - spendLimits.day, daySymbol), + }) + : t('limits.dayTitle', { + spent: formatShortMoney(spentDay, daySymbol), + limit: formatShortMoney(spendLimits.day, daySymbol), + }), + onClick: () => setStatsOpen(true), + }, + h(DayIcon), + formatShortMoney(dayRemaining, daySymbol), + ), + ) + : h( + 'span', + { key: 'limits', className: 'dshCostBalance_anchor' }, + h( + 'button', + { + type: 'button', + className: 'dshCostBalance_pill dshCostBalance_chip dshCostBalance_chipMuted', + title: t('stats.openTitle'), + onClick: () => setStatsOpen(true), + }, + h(DayIcon), + t('stats.open'), + ), + ); + readings.push(dayReading); + + return h( + 'span', + { className: 'dshCostBalance_row' }, + readings, + statsOpen + ? ReactDOM.createPortal( + h( + 'div', + { className: 'dshStats_overlay', role: 'presentation' }, + h('div', { + className: 'dshStats_mask', + 'aria-hidden': true, + onClick: () => setStatsOpen(false), + }), + h( + 'div', + { + className: 'dshStats_modal', + role: 'dialog', + 'aria-modal': 'true', + 'aria-label': t('stats.title'), + }, + h(StatsPanel, { t, provider, onClose: () => setStatsOpen(false) }), + ), + ), + document.body, + ) + : null, + ); + } + + /** Settings page wrapper: the shell passes the session-less props and `t`. */ + function StatsSection(props) { + return h(StatsPanel, { t: props.t }); + } + + /** Bar-chart glyph for the settings navigation row. */ + function SectionIcon({ size }) { + const pixels = typeof size === 'number' && size > 0 ? size : 16; + return h( + 'svg', + { + viewBox: '0 0 16 16', + width: pixels, + height: pixels, + 'aria-hidden': true, + style: { display: 'block', flex: 'none' }, + }, + h('rect', { x: 2, y: 8, width: 3, height: 6, rx: 1, fill: 'currentColor' }), + h('rect', { x: 6.5, y: 5, width: 3, height: 9, rx: 1, fill: 'currentColor' }), + h('rect', { x: 11, y: 2, width: 3, height: 12, rx: 1, fill: 'currentColor' }), + ); + } + + /** + * The shipped usage pill spells the cache-hit reading out ("Cache hit 87%", + * "Попадание в кэш: 87%"). The dock is a row of compact numbers, so this + * plugin rewrites that one label in place and keeps the percentage. + * + * A locale override is not available: the locale service rejects a second + * dictionary for a namespace and locale that already registered, and the + * shipped dictionary belongs to the installation. The observer is limited + * to `[data-composer-stat="usage"]` and does nothing when the text already + * lost its label. + */ + const CACHE_LABELS = [ + /Попадание в кэш:\s*/u, + /Cache hit\s+/u, + /缓存命中\s*/u, + /キャッシュヒット\s*/u, + /Aciertos de caché:\s*/u, + /Taux de réussite du cache\s*:\s*/u, + /Cache-Treffer:\s*/u, + /Acertos no cache:\s*/u, + ]; + + function shortenCacheText(text) { + for (const pattern of CACHE_LABELS) { + if (pattern.test(text)) return text.replace(pattern, ''); + } + return text; + } + + function shortenUsagePills(root) { + const anchors = root.querySelectorAll?.('[data-composer-stat="usage"]') ?? []; + for (const anchor of anchors) { + const walker = document.createTreeWalker(anchor, NodeFilter.SHOW_TEXT); + const nodes = []; + while (walker.nextNode()) nodes.push(walker.currentNode); + for (const node of nodes) { + const current = node.nodeValue ?? ''; + const next = shortenCacheText(current); + if (next !== current) node.nodeValue = next; + } + } + } + + /** Keep the shipped usage pill compact for as long as the plugin is mounted. */ + function installCacheLabelSquash() { + let queued = false; + const apply = () => { + queued = false; + shortenUsagePills(document); + }; + const schedule = () => { + if (queued) return; + queued = true; + window.requestAnimationFrame(apply); + }; + const observer = new MutationObserver(schedule); + observer.observe(document.body, { subtree: true, childList: true, characterData: true }); + schedule(); + return () => observer.disconnect(); + } + + // #endregion + + // #region dictionaries + + const en = { + 'cost': 'Spent ≈ {amount}', + 'cost.title': + 'Estimated session spend at DeepSeek list prices ({rates} per 1M at peak; off-peak is half). Model: {model}.', + 'cost.rates': 'input {input}/1M · cache {cache}/1M · output {output}/1M', + 'balance': 'Balance {amount}', + 'balance.loading': 'Balance …', + 'balance.unavailable': 'Balance —', + 'balance.title': 'Top-up {recharge} · Granted {bonus}. Click to refresh.', + 'balance.title.plain': 'Top-up {recharge}. Click to refresh.', + 'balance.title.unavailable': 'The account balance is unavailable. Sign in to see the remaining balance.', + 'tariff.peak': 'Peak tariff now: DeepSeek full prices (peak is Mon-Fri 9:00-12:00 and 14:00-18:00 Beijing time).', + 'tariff.idle': 'Idle tariff now: DeepSeek prices are half (idle is all other hours and weekends, Beijing time).', + 'balance.operator.title': '{provider}: remaining {amount}. Click to refresh.', + 'balance.operator.titleKey': + '{provider}: balance {amount}, {remaining} left under the key limit. Click to refresh.', + 'balance.keyLimit': '({amount})', + 'balance.operator.unavailable': '{provider}: balance is unavailable.', + 'balance.operator.unavailableReason': '{provider}: balance is unavailable ({reason}).', + 'balance.provider': '({provider})', + 'refresh': 'Refresh balance', + 'section.title': 'Usage', + 'stats.title': 'Spending', + 'stats.subtitle': 'Money spent from the balance, in {symbol}.', + 'stats.view.spend': 'Spending', + 'stats.view.tokens': 'Tokens', + 'stats.view.cache': 'Cache', + 'stats.view.history': 'History', + 'stats.history.subtitle': 'Enter a day total by hand, or clear the recorded history.', + 'stats.tokens.subtitle': 'Tokens used in the selected period: input, cache, and output.', + 'stats.cache.subtitle': 'How much of the input traffic was served from the cache.', + 'stats.tokens.input': 'Input', + 'stats.tokens.cached': 'From cache', + 'stats.tokens.output': 'Output', + 'stats.tokens.writeNote': 'cache write {amount}', + 'stats.tokens.totalNote': 'total {amount}', + 'stats.tokens.unit': 'tokens', + 'stats.tokens.byModel': 'By model', + 'stats.tokens.model': 'Model', + 'stats.tokens.empty': 'No tokens recorded in this period yet.', + 'stats.tokens.hourTitle': '{hour}:00 — {amount} tokens', + 'stats.tokens.dayTitle': '{date} — {amount} tokens', + 'stats.cache.ratio': 'Cache share', + 'stats.cache.hit': 'From cache', + 'stats.cache.miss': 'Missed cache', + 'stats.cache.shareNote': '{percent} of input', + 'stats.cache.summaryNote': '{hit} of {total} input tokens', + 'stats.cache.hourTitle': '{hour}:00 — {percent} from cache', + 'stats.cache.dayTitle': '{date} — {percent} from cache', + 'stats.period.day': 'Day', + 'stats.period.week': 'Week', + 'stats.period.month': 'Month', + 'stats.ofLimit': 'of {limit}', + 'stats.noLimit': 'no limit', + 'stats.leftOfLimit': '{left} left of {limit}', + 'stats.overLimit': 'over by {over} of {limit}', + 'stats.hourTitle': '{hour}:00 — {amount}', + 'stats.dayTitle': '{date} — {amount}', + 'stats.hourlyFor': '{date}, by hour', + 'stats.back': 'Back to days', + 'stats.byHour': 'By hour', + 'stats.byDay': 'By day', + 'stats.clickHint': 'Click a bar to see that day by hour.', + 'stats.overDaysHint': 'Red in a bar is the part above the daily limit.', + 'stats.dayOverTitle': '{date} — {amount}, over by {over}', + 'stats.limitsTitle': 'Soft limits', + 'stats.limitsOwnerHint': 'For {provider} in {symbol}; saved as you type.', + 'quickReload.title': 'Reload the interface. Running agents keep working on the host.', + 'quickReload.label': 'reload', + 'stats.fxNote': 'Central Bank rates: {rates}.', + 'stats.fxMissing': 'No rate for {codes} yet — the totals leave that currency out.', + 'stats.limit.day': 'Per day', + 'stats.limit.week': 'Per week', + 'stats.limit.month': 'Per month', + 'stats.notSet': 'not set', + 'stats.derive': 'Fill from monthly', + 'stats.deriveHint': 'Day = month / 30, week = month × 7 / 30.', + 'stats.resetHistory': 'Clear history', + 'stats.resetHint': 'Deletes the recorded spending and token history; the limits stay.', + 'stats.resetConfirm': 'Clear the recorded spending history?', + 'stats.manualTitle': 'History entry', + 'stats.manualHint': + 'The day total in {symbol}; replaces the recorded hours of that day and is spread over the hours already passed. 0 clears the day.', + 'stats.manualDay': 'Day', + 'stats.manualTotal': 'Total', + 'stats.manualApply': 'Save', + 'stats.close': 'Close', + 'stats.open': 'Statistics', + 'stats.openTitle': 'Spending and limits', + 'limits.dayTitle': 'Today: spent {spent} of {limit}', + 'limits.dayOverTitle': 'Today: spent {spent} of {limit}, over by {over}', + }; + + const zh = { + 'cost': '花费 ≈ {amount}', + 'cost.title': '按 DeepSeek 价格估算的本次会话花费(高峰时段 {rates} / 1M;空闲时段减半)。模型:{model}。', + 'cost.rates': '输入 {input}/1M · 缓存 {cache}/1M · 输出 {output}/1M', + 'balance': '余额 {amount}', + 'balance.loading': '余额 …', + 'balance.unavailable': '余额 —', + 'balance.title': '充值余额 {recharge} · 赠送余额 {bonus}。点击刷新。', + 'balance.title.plain': '充值余额 {recharge}。点击刷新。', + 'balance.title.unavailable': '账户余额不可用。登录后可查看剩余余额。', + 'tariff.peak': '当前为高峰时段:按 DeepSeek 完整价格计费(高峰为北京时间周一至周五 9:00–12:00、14:00–18:00)。', + 'tariff.idle': '当前为空闲时段:DeepSeek 价格减半(其余时间及周末,北京时间)。', + 'balance.operator.title': '{provider}:剩余 {amount}。点击刷新。', + 'balance.operator.unavailable': '{provider}:余额不可用。', + 'balance.provider': '({provider})', + 'refresh': '刷新余额', + }; + + const ru = { + 'cost': 'Расход ≈ {amount}', + 'cost.title': + 'Оценка расхода сессии по прайсу DeepSeek ({rates} за 1M в пиковые часы; вне пика вдвое дешевле). Модель: {model}.', + 'cost.rates': 'вход {input}/1M · кэш {cache}/1M · выход {output}/1M', + 'balance': 'Баланс {amount}', + 'balance.loading': 'Баланс …', + 'balance.unavailable': 'Баланс —', + 'balance.title': 'Пополненный {recharge} · Бонусный {bonus}. Нажмите, чтобы обновить.', + 'balance.title.plain': 'Пополненный {recharge}. Нажмите, чтобы обновить.', + 'balance.title.unavailable': 'Баланс аккаунта недоступен. Войдите в аккаунт, чтобы видеть остаток.', + 'tariff.peak': 'Сейчас пиковый тариф DeepSeek: полные цены (пик — пн–пт 9:00–12:00 и 14:00–18:00 по Пекину).', + 'tariff.idle': 'Сейчас непиковой тариф DeepSeek: цены вдвое ниже (непик — остальное время и выходные по Пекину).', + 'balance.operator.title': '{provider}: остаток {amount}. Нажмите, чтобы обновить.', + 'balance.operator.titleKey': + '{provider}: баланс {amount}, под лимитом ключа осталось {remaining}. Нажмите, чтобы обновить.', + 'balance.keyLimit': '({amount})', + 'balance.operator.unavailable': '{provider}: баланс недоступен.', + 'balance.operator.unavailableReason': '{provider}: баланс недоступен ({reason}).', + 'balance.provider': '({provider})', + 'refresh': 'Обновить баланс', + 'section.title': 'Статистика', + 'stats.title': 'Потребление', + 'stats.subtitle': 'Сколько списано с баланса, в {symbol}.', + 'stats.view.spend': 'Потребление', + 'stats.view.tokens': 'Токены', + 'stats.view.cache': 'Кеш', + 'stats.view.history': 'Правка истории', + 'stats.history.subtitle': 'Ручная запись итога за день и сброс записанной истории.', + 'stats.tokens.subtitle': 'Токены за выбранный период: вход, кеш и выход.', + 'stats.cache.subtitle': 'Какая часть входного трафика обслужена из кеша.', + 'stats.tokens.input': 'Вход', + 'stats.tokens.cached': 'Из кеша', + 'stats.tokens.output': 'Выход', + 'stats.tokens.writeNote': 'кеш-запись {amount}', + 'stats.tokens.totalNote': 'всего {amount}', + 'stats.tokens.unit': 'токенов', + 'stats.tokens.byModel': 'По моделям', + 'stats.tokens.model': 'Модель', + 'stats.tokens.empty': 'За этот период токенов пока нет.', + 'stats.tokens.hourTitle': '{hour}:00 — {amount} токенов', + 'stats.tokens.dayTitle': '{date} — {amount} токенов', + 'stats.cache.ratio': 'Доля кеша', + 'stats.cache.hit': 'Из кеша', + 'stats.cache.miss': 'Мимо кеша', + 'stats.cache.shareNote': '{percent} от входа', + 'stats.cache.summaryNote': '{hit} из {total} входных токенов', + 'stats.cache.hourTitle': '{hour}:00 — {percent} из кеша', + 'stats.cache.dayTitle': '{date} — {percent} из кеша', + 'stats.period.day': 'День', + 'stats.period.week': 'Неделя', + 'stats.period.month': 'Месяц', + 'stats.ofLimit': 'из {limit}', + 'stats.noLimit': 'лимит не задан', + 'stats.leftOfLimit': 'осталось {left} из {limit}', + 'stats.overLimit': 'перерасход {over} из {limit}', + 'stats.hourTitle': '{hour}:00 — {amount}', + 'stats.dayTitle': '{date} — {amount}', + 'stats.hourlyFor': '{date}, по часам', + 'stats.back': 'К дням', + 'stats.byHour': 'По часам', + 'stats.byDay': 'По дням', + 'stats.clickHint': 'Нажмите на столбик, чтобы увидеть этот день по часам.', + 'stats.overDaysHint': 'Красное в столбике — часть выше дневного лимита.', + 'stats.dayOverTitle': '{date} — {amount}, перерасход {over}', + 'stats.limitsTitle': 'Условные лимиты', + 'stats.limitsOwnerHint': 'Для {provider} в {symbol}; сохраняется сразу.', + 'quickReload.title': 'Перезагрузить интерфейс. Запущенные агенты продолжают работу на хосте.', + 'quickReload.label': 'reload', + 'stats.fxNote': 'Курс ЦБ: {rates}.', + 'stats.fxMissing': 'Курса {codes} пока нет — в суммах эта валюта не учтена.', + 'stats.limit.day': 'В день', + 'stats.limit.week': 'В неделю', + 'stats.limit.month': 'В месяц', + 'stats.notSet': 'не задан', + 'stats.derive': 'Заполнить из месячного', + 'stats.deriveHint': 'День = месяц / 30, неделя = месяц × 7 / 30.', + 'stats.resetHistory': 'Сбросить историю', + 'stats.resetHint': 'Удаляет записанную историю расходов и токенов; лимиты сохраняются.', + 'stats.resetConfirm': 'Сбросить записанную историю расходов?', + 'stats.manualTitle': 'Правка истории', + 'stats.manualHint': + 'Итог за день в {symbol}; заменяет записанные часы этого дня и распределяется по уже прошедшим часам. 0 очищает день.', + 'stats.manualDay': 'День', + 'stats.manualTotal': 'Итог', + 'stats.manualApply': 'Записать', + 'stats.close': 'Закрыть', + 'stats.open': 'Статистика', + 'stats.openTitle': 'Расход и лимиты', + 'limits.dayTitle': 'День: потрачено {spent} из {limit}', + 'limits.dayOverTitle': 'День: потрачено {spent} из {limit}, перерасход {over}', + }; + + const ja = { + 'cost': '消費 ≈ {amount}', + 'cost.title': + 'DeepSeek の料金(ピーク時 {rates} / 1M、アイドル時は半額)で見積もったこのセッションの消費額です。モデル: {model}。', + 'cost.rates': '入力 {input}/1M · キャッシュ {cache}/1M · 出力 {output}/1M', + 'balance': '残高 {amount}', + 'balance.loading': '残高 …', + 'balance.unavailable': '残高 —', + 'balance.title': 'チャージ残高 {recharge} · 付与残高 {bonus}。クリックで更新。', + 'balance.title.plain': 'チャージ残高 {recharge}。クリックで更新。', + 'balance.title.unavailable': 'アカウント残高を取得できません。ログインすると残高を確認できます。', + 'tariff.peak': '現在はピーク時間帯: DeepSeek の通常料金です(ピークは北京時間の平日 9:00–12:00、14:00–18:00)。', + 'tariff.idle': '現在はアイドル時間帯: DeepSeek の料金は半額です(それ以外の時間と週末、北京時間)。', + 'balance.operator.title': '{provider}: 残高 {amount}。クリックで更新。', + 'balance.operator.unavailable': '{provider}: 残高を取得できません。', + 'balance.provider': '({provider})', + 'refresh': '残高を更新', + }; + + const es = { + 'cost': 'Gasto ≈ {amount}', + 'cost.title': + 'Gasto estimado de la sesión con las tarifas de DeepSeek ({rates} por 1M en hora punta; en hora valle cuesta la mitad). Modelo: {model}.', + 'cost.rates': 'entrada {input}/1M · caché {cache}/1M · salida {output}/1M', + 'balance': 'Saldo {amount}', + 'balance.loading': 'Saldo …', + 'balance.unavailable': 'Saldo —', + 'balance.title': 'Recargado {recharge} · Bonificado {bonus}. Haz clic para actualizar.', + 'balance.title.plain': 'Recargado {recharge}. Haz clic para actualizar.', + 'balance.title.unavailable': 'El saldo de la cuenta no está disponible. Inicia sesión para verlo.', + 'tariff.peak': 'Ahora es hora punta: precios completos de DeepSeek (la punta es de lunes a viernes, 9:00-12:00 y 14:00-18:00, hora de Pekín).', + 'tariff.idle': 'Ahora es hora valle: los precios de DeepSeek son la mitad (el resto del día y los fines de semana, hora de Pekín).', + 'balance.operator.title': '{provider}: saldo {amount}. Haz clic para actualizar.', + 'balance.operator.unavailable': '{provider}: el saldo no está disponible.', + 'balance.provider': '({provider})', + 'refresh': 'Actualizar saldo', + }; + + const fr = { + 'cost': 'Dépense ≈ {amount}', + 'cost.title': + 'Dépense estimée de la session aux tarifs DeepSeek ({rates} par 1M en heures pleines ; heures creuses moitié prix). Modèle : {model}.', + 'cost.rates': 'entrée {input}/1M · cache {cache}/1M · sortie {output}/1M', + 'balance': 'Solde {amount}', + 'balance.loading': 'Solde …', + 'balance.unavailable': 'Solde —', + 'balance.title': 'Rechargé {recharge} · Offert {bonus}. Cliquez pour actualiser.', + 'balance.title.plain': 'Rechargé {recharge}. Cliquez pour actualiser.', + 'balance.title.unavailable': 'Le solde du compte est indisponible. Connectez-vous pour le voir.', + 'tariff.peak': 'Heure de pointe en cours : tarifs DeepSeek pleins (pointe du lundi au vendredi, 9h00-12h00 et 14h00-18h00, heure de Pékin).', + 'tariff.idle': 'Heures creuses en cours : les tarifs DeepSeek sont divisés par deux (le reste du temps et les week-ends, heure de Pékin).', + 'balance.operator.title': '{provider} : solde {amount}. Cliquez pour actualiser.', + 'balance.operator.unavailable': '{provider} : le solde est indisponible.', + 'balance.provider': '({provider})', + 'refresh': 'Actualiser le solde', + }; + + const de = { + 'cost': 'Ausgaben ≈ {amount}', + 'cost.title': + 'Geschätzte Ausgaben der Sitzung zu DeepSeek-Preisen ({rates} pro 1M zur Spitzenzeit; außerhalb der Spitzenzeiten halb so viel). Modell: {model}.', + 'cost.rates': 'Eingabe {input}/1M · Cache {cache}/1M · Ausgabe {output}/1M', + 'balance': 'Guthaben {amount}', + 'balance.loading': 'Guthaben …', + 'balance.unavailable': 'Guthaben —', + 'balance.title': 'Aufgeladen {recharge} · Geschenkt {bonus}. Klicken zum Aktualisieren.', + 'balance.title.plain': 'Aufgeladen {recharge}. Klicken zum Aktualisieren.', + 'balance.title.unavailable': 'Das Kontoguthaben ist nicht verfügbar. Melden Sie sich an, um es zu sehen.', + 'tariff.peak': 'Jetzt Spitzenzeit: volle DeepSeek-Preise (Spitzenzeit ist Mo-Fr 9:00-12:00 und 14:00-18:00 Pekinger Zeit).', + 'tariff.idle': 'Jetzt Nebenzeit: DeepSeek-Preise sind halb so hoch (alle anderen Zeiten und Wochenenden, Pekinger Zeit).', + 'balance.operator.title': '{provider}: Guthaben {amount}. Klicken zum Aktualisieren.', + 'balance.operator.unavailable': '{provider}: Guthaben nicht verfügbar.', + 'balance.provider': '({provider})', + 'refresh': 'Guthaben aktualisieren', + }; + + const pt = { + 'cost': 'Gasto ≈ {amount}', + 'cost.title': + 'Estimativa de gasto da sessão com os preços da DeepSeek ({rates} por 1M no pico; fora de pico custa metade). Modelo: {model}.', + 'cost.rates': 'entrada {input}/1M · cache {cache}/1M · saída {output}/1M', + 'balance': 'Saldo {amount}', + 'balance.loading': 'Saldo …', + 'balance.unavailable': 'Saldo —', + 'balance.title': 'Recarregado {recharge} · Bônus {bonus}. Clique para atualizar.', + 'balance.title.plain': 'Recarregado {recharge}. Clique para atualizar.', + 'balance.title.unavailable': 'O saldo da conta não está disponível. Entre na conta para vê-lo.', + 'tariff.peak': 'Agora é horário de pico: preços integrais da DeepSeek (pico é de segunda a sexta, 9:00-12:00 e 14:00-18:00, horário de Pequim).', + 'tariff.idle': 'Agora é horário fora de pico: os preços da DeepSeek custam metade (demais horários e fins de semana, horário de Pequim).', + 'balance.operator.title': '{provider}: saldo {amount}. Clique para atualizar.', + 'balance.operator.unavailable': '{provider}: o saldo não está disponível.', + 'balance.provider': '({provider})', + 'refresh': 'Atualizar saldo', + }; + + /* The statistics panel copy ships in Russian and English; every other + * language keeps its translated dock strings and falls back to English for + * the newer keys instead of showing raw keys. */ + const DICTIONARIES = { + en, + zh: { ...en, ...zh }, + ru: { ...en, ...ru }, + ja: { ...en, ...ja }, + es: { ...en, ...es }, + fr: { ...en, ...fr }, + de: { ...en, ...de }, + pt: { ...en, ...pt }, + }; + + // #endregion + + // #region styles + + /** Host pill geometry, copied from the shipped statistics pills. */ + const CSS = [ + '.dshCostBalance_row{display:inline-flex;align-items:center;gap:12px;min-width:0}', + '.dshCostBalance_anchor{min-width:0;', + 'font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);', + 'line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));', + 'display:inline-flex}', + '.dshCostBalance_pill{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;', + 'color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;', + 'line-height:inherit;white-space:nowrap;background:0 0;border:none;align-items:center;', + 'gap:6px;padding:1px 8px;display:inline-flex}', + 'button.dshCostBalance_pill{cursor:pointer}', + 'button.dshCostBalance_pill:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid ', + 'var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}', + '.dshCostBalance_label{text-overflow:ellipsis;min-width:0;overflow:hidden}', + '.dshCostBalance_provider{flex:none;opacity:.7}', + '.dshCostBalance_pair{display:inline-flex;align-items:center;gap:6px;min-width:0}', + '.dshCostBalance_lampAnchor{display:inline-flex;align-items:center;justify-content:center;', + 'flex:none;padding:0 1px}', + '.dshCostBalance_lampAnchor[data-band="idle"]{color:var(--dsw-alias-state-success-primary)}', + '.dshCostBalance_lampAnchor[data-band="peak"]{color:var(--dsw-alias-state-warn-primary)}', + '.dshCostBalance_lamp{width:7px;height:7px;border-radius:50%;flex:none;display:block;', + 'background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 20%,transparent)}', + '.dshCostBalance_pill[data-level="ok"]{color:var(--dsw-alias-state-success-primary)}', + '.dshCostBalance_pill[data-level="warn"]{color:var(--dsw-alias-state-warn-primary)}', + '.dshCostBalance_pill[data-level="over"]{color:var(--dsw-alias-state-error-primary)}', + '.dshCostBalance_chipMuted{color:var(--dsw-alias-label-tertiary)}', + '.dshStats_overlay{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;', + 'justify-content:center}', + '.dshStats_mask{position:absolute;inset:0;background:var(--dsw-alias-bg-mask-1);', + 'backdrop-filter:var(--dsw-mask-blur)}', + '.dshStats_modal{position:relative;z-index:1;box-sizing:border-box;width:720px;', + 'max-width:calc(100vw - 48px);max-height:min(780px,calc(100vh - 48px));overflow:auto;', + 'border-radius:var(--dsw-radius-panel,16px);background:var(--dsw-alias-bg-layer-2);', + 'box-shadow:var(--dsw-elevation-prominent)}', + '.dshStats_root{box-sizing:border-box;display:flex;flex-direction:column;gap:14px;', + 'padding:20px 24px 24px;color:var(--dsw-alias-label-primary);font-size:14px;line-height:20px;', + 'min-width:0}', + '.dshStats_header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}', + '.dshStats_titles{min-width:0}', + '.dshStats_title{margin:0;font-size:16px;font-weight:500;line-height:24px}', + '.dshStats_subtitle{margin:2px 0 0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:18px}', + '.dshStats_close{flex:none;width:28px;height:28px;border:none;border-radius:var(--dsw-radius-sm);', + 'background:0 0;color:var(--dsw-alias-label-secondary);font-size:20px;line-height:1;cursor:pointer}', + '.dshStats_close:hover{background:var(--dsw-alias-interactive-bg-hover)}', + '.dshStats_views{display:inline-flex;gap:2px;align-self:flex-start;', + 'border-bottom:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}', + '.dshStats_view{border:none;background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;', + 'padding:6px 12px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px}', + '.dshStats_viewActive{color:var(--dsw-alias-label-primary);', + 'border-bottom-color:var(--dsw-alias-state-business-primary)}', + '.dshStats_tableBlock{display:flex;flex-direction:column;gap:6px}', + '.dshStats_table{display:flex;flex-direction:column}', + '.dshStats_tableRow{display:grid;grid-template-columns:minmax(0,2fr) repeat(3,minmax(0,1fr));', + 'gap:8px;padding:5px 0;border-top:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);', + 'font-variant-numeric:tabular-nums}', + '.dshStats_tableHead{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px;border-top:none}', + '.dshStats_modelCell{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;', + 'color:var(--dsw-alias-label-secondary)}', + '.dshStats_num{text-align:right}', + '.dshStats_periods{display:inline-flex;gap:4px;padding:3px;border-radius:var(--dsw-radius-md);', + 'background:color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);align-self:flex-start}', + '.dshStats_period{border:none;background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;', + 'padding:4px 12px;border-radius:calc(var(--dsw-radius-md) - 3px);cursor:pointer}', + '.dshStats_periodActive{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);', + 'box-shadow:0 1px 2px rgba(0,0,0,.12)}', + '.dshStats_cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}', + '.dshStats_card{display:flex;flex-direction:column;gap:2px;text-align:left;', + 'border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent);background:0 0;', + 'border-radius:var(--dsw-radius-md);padding:10px 12px;color:var(--dsw-alias-label-primary);', + 'font:inherit;cursor:pointer;min-width:0}', + '.dshStats_cardActive{border-color:var(--dsw-alias-state-business-primary)}', + '.dshStats_cardStatic{cursor:default}', + '.dshStats_cardLabel{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}', + '.dshStats_cardValue{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}', + '.dshStats_cardLimit{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px;', + 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}', + '.dshStats_card[data-level="ok"] .dshStats_cardValue{color:var(--dsw-alias-state-success-primary)}', + '.dshStats_card[data-level="warn"] .dshStats_cardValue{color:var(--dsw-alias-state-warn-primary)}', + '.dshStats_card[data-level="over"] .dshStats_cardValue{color:var(--dsw-alias-state-error-primary)}', + /* Two-segment track: blue up to the limit, red for the excess. */ + /* The segments are flex siblings, so the split point is exact. */ + '.dshStats_progress{display:flex;height:4px;border-radius:2px;margin-top:6px;overflow:hidden;', + 'background:color-mix(in srgb,var(--dsw-alias-label-primary) 10%,transparent)}', + '.dshStats_progressFill{display:block;height:100%;flex:none;', + 'background:var(--dsw-alias-state-business-primary)}', + '.dshStats_progressOver{display:block;height:100%;flex:none;', + 'background:var(--dsw-alias-state-error-primary)}', + '.dshStats_summary{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}', + '.dshStats_summaryAmount{font-size:22px;font-weight:600;font-variant-numeric:tabular-nums}', + '.dshStats_summaryAmount[data-level="ok"]{color:var(--dsw-alias-state-success-primary)}', + '.dshStats_summaryAmount[data-level="warn"]{color:var(--dsw-alias-state-warn-primary)}', + '.dshStats_summaryAmount[data-level="over"]{color:var(--dsw-alias-state-error-primary)}', + '.dshStats_summaryNote{color:var(--dsw-alias-label-tertiary);font-size:13px}', + '.dshStats_summaryNote[data-level="over"]{color:var(--dsw-alias-state-error-primary)}', + '.dshStats_chartBlock{display:flex;flex-direction:column;gap:6px}', + '.dshStats_chartTitle{font-size:13px;color:var(--dsw-alias-label-secondary)}', + '.dshStats_chart{display:flex;flex-direction:column;gap:4px}', + '.dshStats_bars{display:flex;align-items:flex-end;gap:2px;height:132px;padding:28px 0 0;', + 'border-bottom:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 10%,transparent)}', + '.dshStats_barSlot{flex:1 1 0;display:flex;align-items:flex-end;height:100%;min-width:0;', + 'position:relative}', + '.dshStats_barValue{position:absolute;left:50%;transform:translateX(-50%);z-index:1;', + 'font-size:9px;line-height:11px;color:var(--dsw-alias-label-secondary);white-space:nowrap;', + 'pointer-events:none;font-variant-numeric:tabular-nums}', + '.dshStats_bar{width:100%;border-radius:2px 2px 0 0;background:var(--dsw-alias-state-business-primary);', + 'opacity:.55;transition:opacity .12s}', + '.dshStats_barClickable{cursor:pointer}', + '.dshStats_barClickable:hover{opacity:.9}', + '.dshStats_barCurrent{opacity:.95}', + '.dshStats_barSelected{opacity:1;outline:1px solid var(--dsw-alias-state-business-primary)}', + '.dshStats_axis{display:flex;gap:2px}', + '.dshStats_axisLabel{flex:1 1 0;min-width:0;text-align:center;font-size:10px;line-height:14px;', + 'color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden}', + '.dshStats_detail{display:flex;flex-direction:column;gap:8px;padding-top:4px}', + '.dshStats_detailHeader{display:flex;align-items:center;justify-content:space-between;gap:8px}', + '.dshStats_detailTitle{font-size:13px;color:var(--dsw-alias-label-secondary)}', + '.dshStats_linkButton{border:none;background:0 0;color:var(--dsw-alias-state-business-primary);', + 'font:inherit;cursor:pointer;padding:0}', + '.dshStats_limitsBlock{display:flex;flex-direction:column;gap:8px;padding-top:6px;', + 'border-top:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}', + '.dshStats_limitsTitle{margin:0;font-size:14px;font-weight:500}', + '.dshStats_hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}', + '.dshStats_limitRow{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}', + '.dshStats_manualRow{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}', + '.dshStats_fxNotes{display:flex;flex-direction:column;gap:2px}', + '.dshReload_wrap{display:flex;justify-content:flex-start;align-items:center;flex:1 1 auto;', + 'min-width:0;padding-inline-start:var(--dsh-sidebar-row-padding,8px)}', + '.dshReload_wrap[data-wide="false"]{flex:none;padding-inline-start:0}', + '.dshReload_button{height:28px;border:none;border-radius:999px;background:0 0;', + 'color:var(--dsw-alias-label-tertiary);cursor:pointer;padding:0 12px;display:inline-flex;', + 'align-items:center;justify-content:center;gap:6px;flex:none;font:inherit;font-size:13px;line-height:1}', + '.dshReload_wrap[data-wide="false"] .dshReload_button{width:28px;padding:0}', + '.dshReload_label{white-space:nowrap}', + '.dshReload_button svg{flex:none}', + '.dshReload_button:hover{background:var(--dsw-alias-interactive-bg-hover);', + 'color:var(--dsw-alias-label-secondary)}', + '.dshReload_button:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid ', + 'var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}', + '.dshStats_date{width:auto;min-width:8.5em;color-scheme:inherit}', + '.dshStats_limitField{display:flex;flex-direction:column;gap:4px;min-width:0}', + '.dshStats_limitLabel{font-size:12px;color:var(--dsw-alias-label-secondary)}', + '.dshStats_inputWrap{display:flex;align-items:center;gap:6px;padding:4px 8px;', + 'border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 14%,transparent);', + 'border-radius:var(--dsw-radius-sm)}', + '.dshStats_input{border:none;background:0 0;color:var(--dsw-alias-label-primary);font:inherit;', + 'font-variant-numeric:tabular-nums;width:100%;min-width:0;outline:none;padding:0}', + '.dshStats_symbol{color:var(--dsw-alias-label-tertiary);flex:none}', + '.dshStats_actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}', + '.dshStats_button{border:1px solid color-mix(in srgb,var(--dsw-alias-label-primary) 14%,transparent);', + 'border-radius:var(--dsw-radius-sm);background:0 0;color:var(--dsw-alias-label-primary);', + 'font:inherit;padding:4px 12px;cursor:pointer}', + '.dshStats_button:hover{background:var(--dsw-alias-interactive-bg-hover)}', + ].join(''); + + // #endregion + + /** Services required by this Client half. */ + const inject = ['slots', 'locale', 'remote', 'remote.account']; + + /** + * Register the readings and their resources. + * @param ctx - Client plugin context. + */ + function apply(ctx) { + ctx.effect( + () => + ctx.locale.register(NS, DICTIONARIES), + 'cost-balance-footer: dictionaries', + ); + + ctx.effect(() => { + const tag = document.createElement('style'); + tag.dataset.plugin = PLUGIN_ID; + tag.dataset.pluginCss = CSS_ID; + tag.textContent = CSS; + document.head.appendChild(tag); + return () => { + tag.remove(); + }; + }, 'cost-balance-footer: styles'); + + /** Identity for one account call, read at call time. */ + const clientMetadata = () => { + const release = globalThis.__DSH_BOOT__?.release; + return { + version: typeof release?.version === 'string' ? release.version : '0.0.0', + locale: ctx.locale.getSnapshot().active, + timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60, + }; + }; + + /** Read the account's wallets; null means signed out or unavailable. */ + const fetchBalance = async () => { + try { + const result = await ctx.remote.account.getBalance(clientMetadata()); + if (!result || !result.ok) return null; + const balance = result.value; + if (!balance || balance.status !== 'ready') return null; + return { + wallets: Array.isArray(balance.value) ? balance.value : [], + bonusWallets: Array.isArray(balance.bonusWallets) ? balance.bonusWallets : [], + }; + } catch { + return null; + } + }; + + /* Settings → Statistics: history, hourly view, and the soft limits. */ + const tSettings = ctx.locale.bind(NS); + const registerSlots = () => { + ctx.slots.inject('conversation.composer.dock', () => + ctx.slots.register( + { + name: 'conversation.composer.dock', + id: 'cost-balance', + order: 2, + locale: NS, + inject: () => ({ fetchBalance }), + }, + CostBalanceDock, + ), + ); + ctx.slots.inject('settings.section', () => + ctx.slots.register( + { + name: 'settings.section', + id: 'cost-balance', + order: 40, + label: () => tSettings('section.title'), + locale: NS, + }, + StatsSection, + ), + ); + ctx.slots.inject('settings.section.icon', () => + ctx.slots.register({ name: 'settings.section.icon', id: 'cost-balance', locale: NS }, SectionIcon), + ); + }; + + /* Hydrate the ledger before the readings mount, so the first paint shows + * the stored history instead of an empty one. The route answers locally; + * its timeout still lets the plugin mount against an older Host. */ + ctx.effect(() => { + let active = true; + void hydrateSpend().finally(() => { + if (active) registerSlots(); + }); + return () => { + active = false; + }; + }, 'cost-balance: spending ledger'); + + /* Rates are published once a business day; refresh on start and every + * few hours so a long-running window picks the new one up. */ + ctx.effect(() => { + void refreshFxRates(); + const timer = window.setInterval(() => { + if (document.visibilityState === 'visible') void refreshFxRates(); + }, FX_REFRESH_MS); + return () => window.clearInterval(timer); + }, 'cost-balance: daily exchange rates'); + + /* One click applies fresh client bundles and settings without digging + * into the profile menu; agents are unaffected. */ + ctx.slots.inject('sidebar.footer.action', () => + ctx.slots.register( + { name: 'sidebar.footer.action', id: 'quick-reload', order: 100, locale: NS }, + ReloadButton, + ), + ); + + ctx.effect(() => installCacheLabelSquash(), 'cost-balance: compact cache label'); + } + + return { inject, apply }; + }, +}); diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..bbabe31 --- /dev/null +++ b/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: cost-balance-footer + name: '@local/dsh-cost-balance-footer' diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..d2711f6 --- /dev/null +++ b/icon.svg @@ -0,0 +1,6 @@ + + + + diff --git a/index.js b/index.js new file mode 100644 index 0000000..cf4981c --- /dev/null +++ b/index.js @@ -0,0 +1,1086 @@ +import { chmod, mkdir } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; + +/** Host half of the cost/balance footer bundle. + * + * Serves the connected third-party operator's wallet balance and the spend + * counter it reports to the Client half over a same-origin route. The operator + * API key is resolved here, on the Host, through the credentials seam, so no + * secret ever reaches the browser. + */ +const PROVIDERS = { + openrusrouter: { + balanceUrl: 'https://openrusrouter.ru/v1/auth/key', + apiKeyEnv: 'OPENRUSROUTER_API_KEY', + /* OpenRusRouter bills this wallet in rubles, whatever currency field the + * gateway echoes (or omits); the configured symbol is authoritative. */ + symbol: '₽', + displayName: 'OpenRusRouter', + }, +}; + +/** + * Daily central-bank rates, cached in the database. + * + * DeepSeek wallets bill in dollars or yuan while the operator wallet and the + * user's budgets are in rubles, so the statistics need a ruble value for the + * foreign spend. The Central Bank publishes once per business day; the cache + * is refreshed at most once a day, and a network failure keeps the last known + * rates instead of blanking the totals. + */ +const FX_URL = 'https://www.cbr-xml-daily.ru/daily_json.js'; +const FX_TTL_MS = 24 * 3_600_000; +const FX_CODES = ['USD', 'CNY', 'EUR']; +const FX_TIMEOUT_MS = 10_000; + +/** One JSON response with no caching. */ +function json(status, body) { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, + }); +} + +/** Resolve one credential reference to its secret, or undefined. */ +async function resolveCredential(ctx, name) { + try { + const credentials = ctx.get('credentials'); + const hit = await credentials?.resolve(name); + const value = hit?.value; + if (typeof value === 'string' && value.length > 0) return value; + } catch { + /* fall through to the launch environment */ + } + const fromEnv = process.env[name]; + return typeof fromEnv === 'string' && fromEnv.length > 0 ? fromEnv : undefined; +} + +function numeric(value) { + if (typeof value === 'number' && Number.isFinite(value)) return value; + if (typeof value === 'string' && value.trim() !== '') { + const parsed = Number(value); + if (Number.isFinite(parsed)) return parsed; + } + return undefined; +} + +function atPath(value, path) { + let current = value; + for (const key of path.split('.')) { + if (current === null || typeof current !== 'object') return undefined; + current = current[key]; + } + return current; +} + +/** First finite number among the given payload paths. */ +function firstNumber(payload, paths) { + for (const path of paths) { + const amount = numeric(atPath(payload, path)); + if (amount !== undefined) return amount; + } + return undefined; +} + +/** + * Remainder and spend counters of one balance payload. + * + * OpenRouter-compatible gateways (OpenRusRouter among them) answer with every + * amount as a string and separate three numbers that are easy to mistake for + * one another: + * + * - `account_balance` — the whole wallet. It moves only when money is really + * spent or added, so it is the remainder a "Balance" reading should show; + * - `balance` / `limit_remaining` — what the key may still spend, i.e. the + * minimum of the wallet and the key's remaining limit. Editing the key's + * limit in the billing cabinet changes it without a single request being + * billed, which is why measuring spending by its fall booked the limit edit + * as a purchase; + * - `usage` — what the key has already spent in the current window, reported + * as measured. Only billed requests move it. + * + * The reading therefore shows the wallet as `amount` and hands `used` plus the + * identity of its window to the Client half, whose ledger books spending from + * that counter. Gateways without a wallet field keep the older shapes, and the + * counter stays absent so the ledger falls back to a whole-balance delta + * instead of the capped one. + */ +function extractReading(payload) { + const wallet = firstNumber(payload, ['data.account_balance', 'account_balance']); + const limit = firstNumber(payload, ['data.limit', 'limit']); + const limitRemaining = firstNumber(payload, ['data.limit_remaining', 'limit_remaining']); + const usage = firstNumber(payload, ['data.usage', 'usage']); + + let amount; + let source; + if (wallet !== undefined) { + amount = wallet; + source = 'account-balance'; + } else if (limitRemaining !== undefined) { + amount = limitRemaining; + source = 'limit-remaining'; + } else { + amount = firstNumber(payload, [ + 'data.remaining', + 'remaining', + 'data.total_remaining', + 'data.balance', + 'balance', + 'data.credits_remaining', + 'credits_remaining', + 'data.credits', + 'credits', + ]); + source = 'balance'; + } + if (amount === undefined) { + if (limit === undefined || usage === undefined) return undefined; + amount = limit - usage; + source = 'limit-usage'; + } + + /* `usage` counts money only on a payload that reports money for this key; a + * bare token counter must not become a spend meter. */ + const moneyShaped = wallet !== undefined || limitRemaining !== undefined || limit !== undefined; + const window = atPath(payload, 'data.limit_window') ?? atPath(payload, 'limit_window'); + const resetsAt = atPath(payload, 'data.limit_resets_at') ?? atPath(payload, 'limit_resets_at'); + return { + amount, + source, + wallet, + limit, + used: moneyShaped ? usage : undefined, + window: typeof window === 'string' ? window : undefined, + resetsAt: typeof resetsAt === 'string' ? resetsAt : undefined, + }; +} + +/** Currency symbol announced by the payload, else the configured one. */ +function extractSymbol(payload, fallback) { + const currency = + atPath(payload, 'data.currency') ?? + atPath(payload, 'currency') ?? + atPath(payload, 'data.wallet.currency'); + if (typeof currency === 'string') { + const upper = currency.toUpperCase(); + if (upper === 'USD') return '$'; + if (upper === 'CNY') return '¥'; + if (upper === 'RUB') return '₽'; + } + return fallback; +} + +async function handleBalance(ctx, request) { + const provider = new URL(request.url).searchParams.get('provider') ?? ''; + const target = PROVIDERS[provider]; + if (target === undefined) return json(200, { ok: false, reason: 'unknown-provider' }); + const key = await resolveCredential(ctx, target.apiKeyEnv); + if (key === undefined) { + return json(200, { ok: false, reason: 'missing-credential', provider }); + } + let response; + try { + response = await fetch(target.balanceUrl, { + headers: { authorization: `Bearer ${key}`, accept: 'application/json' }, + signal: AbortSignal.timeout(15000), + }); + } catch { + return json(200, { ok: false, reason: 'network', provider }); + } + if (!response.ok) { + return json(200, { ok: false, reason: 'http-error', provider, status: response.status }); + } + let payload; + try { + payload = await response.json(); + } catch { + return json(200, { ok: false, reason: 'bad-payload', provider }); + } + const extracted = extractReading(payload); + if (extracted === undefined) { + const data = payload !== null && typeof payload === 'object' ? payload.data : undefined; + const fields = + data !== null && typeof data === 'object' + ? Object.keys(data) + : payload !== null && typeof payload === 'object' + ? Object.keys(payload) + : []; + return json(200, { ok: false, reason: 'unknown-shape', provider, fields }); + } + return json(200, { + ok: true, + provider, + displayName: target.displayName ?? provider, + amount: extracted.amount, + symbol: target.symbol ?? extractSymbol(payload, '$'), + source: extracted.source, + /* The spend meter the Client half books from, with the identity of the + * window it belongs to; all absent for a gateway that reports none. */ + wallet: extracted.wallet, + used: extracted.used, + limit: extracted.limit, + window: extracted.window, + resetsAt: extracted.resetsAt, + }); +} + +/* ------------------------------------------------------------------------- */ +/* Spending history: SQLite */ +/* ------------------------------------------------------------------------- */ + +/** + * The Client half keeps its spending ledger here instead of the browser's + * `localStorage`: the history then survives a cache wipe, belongs to the + * machine rather than to one browser profile, and is shared by every window. + * + * The schema is normalized and versioned with `PRAGMA user_version`; the file + * carries `PRAGMA application_id`, so an unrelated database that happens to sit + * at the same path is refused instead of adopted. + */ +const DB_ENV = 'DSH_COST_BALANCE_DB'; +const DB_FILE_NAME = 'cost-balance.sqlite'; +const DB_APPLICATION_ID = 0x43425350; /* "CBSP" */ +const DB_SCHEMA_VERSION = 4; +const STATE_VERSION = 1; +const MAX_HOUR_BUCKETS = 10_000; +const MAX_SAMPLES = 64; +const MAX_LIMIT_OWNERS = 8; +const MAX_TOKEN_MODELS = 16; +const MAX_BODY_BYTES = 4 * 1024 * 1024; +const CURRENCY_PATTERN = /^[A-Z]{3}$/; +/** Limit owners are provider ids: `openrusrouter`, `deepseek`. */ +const LIMIT_OWNER_PATTERN = /^[a-z0-9-]{1,32}$/; + +const DB_SCHEMA = ` +CREATE TABLE IF NOT EXISTS spend_meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS spend_hours ( + hour INTEGER NOT NULL, + currency TEXT NOT NULL, + amount REAL NOT NULL, + PRIMARY KEY (hour, currency) +); +CREATE TABLE IF NOT EXISTS spend_samples ( + provider TEXT PRIMARY KEY, + currency TEXT NOT NULL, + observed_at INTEGER NOT NULL, + amount REAL, + wallet REAL, + used REAL, + cap REAL, + reset_window TEXT, + reset_at TEXT +); +CREATE TABLE IF NOT EXISTS spend_limits ( + owner TEXT PRIMARY KEY, + currency TEXT NOT NULL, + day REAL NOT NULL DEFAULT 0, + week REAL NOT NULL DEFAULT 0, + month REAL NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS usage_hours ( + hour INTEGER NOT NULL, + model TEXT NOT NULL, + miss REAL NOT NULL DEFAULT 0, + cache_write REAL NOT NULL DEFAULT 0, + cache_read REAL NOT NULL DEFAULT 0, + output REAL NOT NULL DEFAULT 0, + PRIMARY KEY (hour, model) +); +CREATE TABLE IF NOT EXISTS fx_rates ( + code TEXT PRIMARY KEY, + rate REAL NOT NULL, + rate_date TEXT NOT NULL, + fetched_at INTEGER NOT NULL +); +`; + +/** Ledger document shape shared with the Client half. */ +function emptyState() { + return { version: STATE_VERSION, currency: 'RUB', hours: {}, samples: {}, limits: {}, tokens: {} }; +} + +/** Token counts are non-negative integers; anything else reads as zero. */ +function tokenCount(value) { + const parsed = numeric(value); + return parsed !== undefined && parsed > 0 ? parsed : 0; +} + +/** + * Clamp one ledger document to the shape the database stores. + * + * The route is loopback and same-origin, but the Client half is replaceable, so + * the Host never trusts the document: unknown fields are dropped, sizes are + * bounded, and only finite numbers reach SQLite. + */ +function normalizeState(value) { + const state = emptyState(); + if (value === null || typeof value !== 'object') return state; + if (typeof value.currency === 'string' && CURRENCY_PATTERN.test(value.currency)) { + state.currency = value.currency; + } + if (value.hours !== null && typeof value.hours === 'object') { + let buckets = 0; + for (const [key, bucket] of Object.entries(value.hours)) { + if (buckets >= MAX_HOUR_BUCKETS) break; + const hour = numeric(key); + if (hour === undefined || !Number.isSafeInteger(hour) || hour < 0) continue; + if (bucket === null || typeof bucket !== 'object') continue; + const amounts = {}; + for (const [currency, amount] of Object.entries(bucket)) { + const parsed = numeric(amount); + if (!CURRENCY_PATTERN.test(currency) || parsed === undefined || parsed === 0) continue; + amounts[currency] = parsed; + } + if (Object.keys(amounts).length === 0) continue; + state.hours[String(hour)] = amounts; + buckets += 1; + } + } + if (value.samples !== null && typeof value.samples === 'object') { + let count = 0; + for (const [provider, sample] of Object.entries(value.samples)) { + if (count >= MAX_SAMPLES) break; + if (typeof provider !== 'string' || provider === '' || provider.length > 64) continue; + if (sample === null || typeof sample !== 'object') continue; + const at = numeric(sample.at); + if (at === undefined) continue; + const entry = { currency: state.currency, at }; + if (typeof sample.currency === 'string' && CURRENCY_PATTERN.test(sample.currency)) { + entry.currency = sample.currency; + } + for (const key of ['amount', 'wallet', 'used', 'cap']) { + const parsed = numeric(sample[key]); + if (parsed !== undefined) entry[key] = parsed; + } + if (typeof sample.window === 'string' && sample.window !== '' && sample.window.length <= 16) { + entry.window = sample.window; + } + if (typeof sample.resetsAt === 'string' && sample.resetsAt !== '' && sample.resetsAt.length <= 64) { + entry.resetsAt = sample.resetsAt; + } + state.samples[provider] = entry; + count += 1; + } + } + if (value.limits !== null && typeof value.limits === 'object') { + let owners = 0; + for (const [key, limits] of Object.entries(value.limits)) { + if (owners >= MAX_LIMIT_OWNERS) break; + if (limits === null || typeof limits !== 'object') continue; + /* Older clients still key limits by wallet currency; map those onto the + * provider that owns the wallet instead of dropping them. */ + const legacy = CURRENCY_PATTERN.test(key); + const owner = legacy ? (key === 'RUB' ? 'openrusrouter' : 'deepseek') : key; + if (!LIMIT_OWNER_PATTERN.test(owner)) continue; + const read = (raw) => { + const parsed = numeric(raw); + return parsed !== undefined && parsed > 0 ? parsed : 0; + }; + state.limits[owner] = { + currency: + typeof limits.currency === 'string' && CURRENCY_PATTERN.test(limits.currency) + ? limits.currency + : legacy + ? key + : state.currency, + day: read(limits.day), + week: read(limits.week), + month: read(limits.month), + }; + owners += 1; + } + } + if (value.tokens !== null && typeof value.tokens === 'object') { + let buckets = 0; + for (const [key, models] of Object.entries(value.tokens)) { + if (buckets >= MAX_HOUR_BUCKETS) break; + const hour = numeric(key); + if (hour === undefined || !Number.isSafeInteger(hour) || hour < 0) continue; + if (models === null || typeof models !== 'object') continue; + const entries = {}; + let count = 0; + for (const [model, entry] of Object.entries(models)) { + if (count >= MAX_TOKEN_MODELS) break; + if (typeof model !== 'string' || model === '' || model.length > 64) continue; + if (entry === null || typeof entry !== 'object') continue; + const miss = tokenCount(entry.miss); + const write = tokenCount(entry.write); + const hit = tokenCount(entry.hit); + const out = tokenCount(entry.out); + if (miss + write + hit + out <= 0) continue; + entries[model] = { miss, write, hit, out }; + count += 1; + } + if (count === 0) continue; + state.tokens[String(hour)] = entries; + buckets += 1; + } + } + return state; +} + +/** Whether a ledger document carries no history, samples, or limits. */ +function isEmptyState(state) { + return ( + Object.keys(state.hours).length === 0 && + Object.keys(state.samples).length === 0 && + Object.keys(state.limits).length === 0 && + Object.keys(state.tokens).length === 0 + ); +} + +/** Harness home: `$DSH_HOME`, else `~/.dsh` — the rule the harness itself uses. */ +function dshHome() { + const value = process.env.DSH_HOME; + if (typeof value === 'string' && value.trim() !== '') { + const trimmed = value.trim(); + if (trimmed === '~') return homedir(); + if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) return join(homedir(), trimmed.slice(2)); + return resolve(trimmed); + } + return join(homedir(), '.dsh'); +} + +/** Absolute path of the ledger database; `$DSH_COST_BALANCE_DB` overrides it. */ +function databasePath() { + const override = process.env[DB_ENV]; + if (typeof override === 'string' && override.trim() !== '') return resolve(override.trim()); + return join(dshHome(), 'storages', DB_FILE_NAME); +} + +let databasePromise; + +/** One open handle per process; a failed open is retried by the next request. */ +function database() { + if (databasePromise === undefined) { + databasePromise = openDatabase().catch((error) => { + databasePromise = undefined; + throw error; + }); + } + return databasePromise; +} + +/** Open (or create) the ledger database and bring its schema up to date. */ +async function openDatabase() { + /* `node:sqlite` ships with the runtime, but importing it lazily keeps the + * balance reading working on a runtime that lacks it. */ + const { DatabaseSync } = await import('node:sqlite'); + const file = databasePath(); + await mkdir(dirname(file), { recursive: true, mode: 0o700 }); + const db = new DatabaseSync(file); + try { + /* The file may have been created by another tool or a wider umask: the + * spending history stays owner-only either way. */ + await chmod(file, 0o600).catch(() => undefined); + db.exec('PRAGMA journal_mode = WAL'); + db.exec('PRAGMA busy_timeout = 5000'); + const applicationId = db.prepare('PRAGMA application_id').get().application_id; + const version = db.prepare('PRAGMA user_version').get().user_version; + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'") + .all(); + if (applicationId !== 0 && applicationId !== DB_APPLICATION_ID) { + throw new Error('cost-balance: the database belongs to another application'); + } + if (applicationId === 0 && tables.length > 0) { + throw new Error('cost-balance: the database has an unrecognized schema'); + } + db.exec(`PRAGMA application_id = ${DB_APPLICATION_ID}`); + if (version > DB_SCHEMA_VERSION) { + throw new Error(`cost-balance: unsupported database schema version ${version}`); + } + /* Every statement is CREATE TABLE IF NOT EXISTS, so applying the current + * schema upgrades an older file in place (v1 -> v2 adds usage_hours and + * keeps the spending history) without a destructive rebuild. */ + db.exec(DB_SCHEMA); + migrateLimitOwners(db); + if (version !== DB_SCHEMA_VERSION) { + db.exec(`PRAGMA user_version = ${DB_SCHEMA_VERSION}`); + } + return db; + } catch (error) { + db.close(); + throw error; + } +} + +/** + * v3: soft limits moved from the wallet currency to the provider that owns + * the wallet. Rebuild the table in place and remap the legacy rows (ruble + * limits belong to the operator, the account's own currency to DeepSeek); + * the yuan row wins when a legacy file carries both account currencies. + */ +function migrateLimitOwners(db) { + const columns = db.prepare("PRAGMA table_info('spend_limits')").all().map((row) => row.name); + if (columns.includes('owner')) return; + db.exec('BEGIN IMMEDIATE'); + try { + db.exec('ALTER TABLE spend_limits RENAME TO spend_limits_legacy'); + db.exec('CREATE TABLE spend_limits (owner TEXT PRIMARY KEY, currency TEXT NOT NULL, day REAL NOT NULL DEFAULT 0, week REAL NOT NULL DEFAULT 0, month REAL NOT NULL DEFAULT 0)'); + db.exec('INSERT OR REPLACE INTO spend_limits (owner, currency, day, week, month) SELECT CASE WHEN currency = \'RUB\' THEN \'openrusrouter\' ELSE \'deepseek\' END, currency, day, week, month FROM spend_limits_legacy ORDER BY CASE WHEN currency = \'CNY\' THEN 1 ELSE 0 END'); + db.exec('DROP TABLE spend_limits_legacy'); + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** Read the whole ledger document out of the database. */ +function readState(db) { + const state = emptyState(); + const currency = db.prepare("SELECT value FROM spend_meta WHERE key = 'currency'").get(); + if (currency !== undefined && typeof currency.value === 'string' && CURRENCY_PATTERN.test(currency.value)) { + state.currency = currency.value; + } + for (const row of db.prepare('SELECT hour, currency, amount FROM spend_hours').all()) { + const key = String(row.hour); + const bucket = state.hours[key] ?? (state.hours[key] = {}); + bucket[row.currency] = row.amount; + } + for (const row of db.prepare('SELECT * FROM spend_samples').all()) { + const sample = { currency: row.currency, at: row.observed_at }; + if (row.amount !== null) sample.amount = row.amount; + if (row.wallet !== null) sample.wallet = row.wallet; + if (row.used !== null) sample.used = row.used; + if (row.cap !== null) sample.cap = row.cap; + if (row.reset_window !== null) sample.window = row.reset_window; + if (row.reset_at !== null) sample.resetsAt = row.reset_at; + state.samples[row.provider] = sample; + } + for (const row of db.prepare('SELECT owner, currency, day, week, month FROM spend_limits').all()) { + state.limits[row.owner] = { + currency: row.currency, + day: row.day, + week: row.week, + month: row.month, + }; + } + for (const row of db.prepare('SELECT hour, model, miss, cache_write, cache_read, output FROM usage_hours').all()) { + const key = String(row.hour); + const bucket = state.tokens[key] ?? (state.tokens[key] = {}); + bucket[row.model] = { + miss: row.miss, + write: row.cache_write, + hit: row.cache_read, + out: row.output, + }; + } + return state; +} + +/** Replace every row of the ledger with one document; caller owns the transaction. */ +function replaceRows(db, state) { + db.exec('DELETE FROM spend_hours'); + db.exec('DELETE FROM spend_samples'); + db.exec('DELETE FROM spend_limits'); + db.exec('DELETE FROM usage_hours'); + db.exec("DELETE FROM spend_meta WHERE key = 'currency'"); + db.prepare("INSERT INTO spend_meta (key, value) VALUES ('currency', ?)").run(state.currency); + const insertHour = db.prepare('INSERT INTO spend_hours (hour, currency, amount) VALUES (?, ?, ?)'); + for (const [key, bucket] of Object.entries(state.hours)) { + for (const [currency, amount] of Object.entries(bucket)) { + insertHour.run(Number(key), currency, amount); + } + } + const insertSample = db.prepare( + 'INSERT INTO spend_samples (provider, currency, observed_at, amount, wallet, used, cap, reset_window, reset_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', + ); + for (const [provider, sample] of Object.entries(state.samples)) { + insertSample.run( + provider, + sample.currency, + sample.at, + sample.amount ?? null, + sample.wallet ?? null, + sample.used ?? null, + sample.cap ?? null, + sample.window ?? null, + sample.resetsAt ?? null, + ); + } + const insertLimits = db.prepare( + 'INSERT INTO spend_limits (owner, currency, day, week, month) VALUES (?, ?, ?, ?, ?)', + ); + for (const [owner, limits] of Object.entries(state.limits)) { + insertLimits.run(owner, limits.currency ?? state.currency, limits.day, limits.week, limits.month); + } + const insertTokens = db.prepare( + 'INSERT INTO usage_hours (hour, model, miss, cache_write, cache_read, output) VALUES (?, ?, ?, ?, ?, ?)', + ); + for (const [key, models] of Object.entries(state.tokens)) { + for (const [model, entry] of Object.entries(models)) { + insertTokens.run(Number(key), model, entry.miss, entry.write, entry.hit, entry.out); + } + } +} + +/** Replace the ledger atomically. */ +function writeState(db, state) { + db.exec('BEGIN IMMEDIATE'); + try { + replaceRows(db, state); + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* The transaction may already have been rolled back by SQLite. */ + } + throw error; + } +} + +/** + * Import a legacy document, but only into a database that has no history yet. + * The emptiness check runs inside the write transaction, so two windows + * importing at once still produce one copy. + */ +function importState(db, state) { + db.exec('BEGIN IMMEDIATE'); + try { + const rows = db + .prepare( + 'SELECT (SELECT COUNT(*) FROM spend_hours) + (SELECT COUNT(*) FROM spend_samples) + (SELECT COUNT(*) FROM spend_limits) + (SELECT COUNT(*) FROM usage_hours) AS total', + ) + .get(); + if (rows.total > 0) { + db.exec('ROLLBACK'); + return false; + } + replaceRows(db, state); + db.exec('COMMIT'); + return true; + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** + * Fold one document into the stored one without double counting. + * + * Several windows poll the same wallet and observe the same spending, so the + * larger value per hour (and per model for tokens) wins; samples take the newer + * reading. Limits are authoritative in the shared ledger: the browser copy only + * fills owners it does not cover, so a stale window cannot reset a budget. + */ +function mergeState(current, incoming) { + const merged = { + version: STATE_VERSION, + currency: incoming.currency ?? current.currency, + hours: { ...current.hours }, + samples: { ...current.samples }, + limits: { ...current.limits }, + tokens: { ...current.tokens }, + }; + for (const [hour, bucket] of Object.entries(incoming.hours)) { + const target = merged.hours[hour] ?? (merged.hours[hour] = {}); + for (const [currency, amount] of Object.entries(bucket)) { + const previous = target[currency]; + if (typeof previous !== 'number' || amount > previous) target[currency] = amount; + } + } + for (const [hour, models] of Object.entries(incoming.tokens)) { + const target = merged.tokens[hour] ?? (merged.tokens[hour] = {}); + for (const [model, entry] of Object.entries(models)) { + const previous = target[model]; + if (previous === undefined) { + target[model] = { ...entry }; + continue; + } + target[model] = { + miss: Math.max(previous.miss, entry.miss), + write: Math.max(previous.write, entry.write), + hit: Math.max(previous.hit, entry.hit), + out: Math.max(previous.out, entry.out), + }; + } + } + for (const [provider, sample] of Object.entries(incoming.samples)) { + const previous = merged.samples[provider]; + if (previous === undefined || (sample.at ?? 0) > (previous.at ?? 0)) { + merged.samples[provider] = { ...sample }; + } + } + for (const [owner, limits] of Object.entries(incoming.limits)) { + if (merged.limits[owner] === undefined) merged.limits[owner] = { ...limits }; + } + return merged; +} + +/** Replace every soft limit with the document's, keeping the history. */ +function replaceLimits(db, state) { + db.exec('BEGIN IMMEDIATE'); + try { + db.exec('DELETE FROM spend_limits'); + db.exec("DELETE FROM spend_meta WHERE key = 'currency'"); + db.prepare("INSERT INTO spend_meta (key, value) VALUES ('currency', ?)").run(state.currency); + const insert = db.prepare( + 'INSERT INTO spend_limits (owner, currency, day, week, month) VALUES (?, ?, ?, ?, ?)', + ); + for (const [owner, limits] of Object.entries(state.limits)) { + insert.run(owner, limits.currency ?? state.currency, limits.day, limits.week, limits.month); + } + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** Drop the recorded spending and tokens; the soft limits stay. */ +function clearHistory(db) { + db.exec('BEGIN IMMEDIATE'); + try { + db.exec('DELETE FROM spend_hours'); + db.exec('DELETE FROM spend_samples'); + db.exec('DELETE FROM usage_hours'); + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** Replace one local day's money buckets for one currency. */ +function replaceDay(db, day) { + db.exec('BEGIN IMMEDIATE'); + try { + db.prepare('DELETE FROM spend_hours WHERE hour >= ? AND hour < ? AND currency = ?').run( + day.start, + day.start + 24 * 3_600_000, + day.currency, + ); + const insert = db.prepare( + 'INSERT INTO spend_hours (hour, currency, amount) VALUES (?, ?, ?) ON CONFLICT(hour, currency) DO UPDATE SET amount = excluded.amount', + ); + for (const [hour, amount] of Object.entries(day.buckets ?? {})) { + const at = numeric(hour); + const value = numeric(amount); + if (at === undefined || value === undefined || value === 0) continue; + insert.run(at, day.currency, value); + } + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** Write one JSON answer to a raw HTTP response. */ +function sendJson(res, status, body, allow) { + const headers = { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }; + if (allow !== undefined) headers.allow = allow; + res.writeHead(status, headers); + res.end(JSON.stringify(body)); +} + +/** Read a bounded request body from a raw HTTP request. */ +function readRawBody(req) { + return new Promise((resolve) => { + let size = 0; + let settled = false; + const chunks = []; + const finish = (value) => { + if (settled) return; + settled = true; + resolve(value); + }; + req.on('data', (chunk) => { + if (settled) return; + size += chunk.length; + if (size > MAX_BODY_BYTES) { + finish(undefined); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => finish(Buffer.concat(chunks))); + req.on('error', () => finish(undefined)); + req.on('aborted', () => finish(undefined)); + }); +} + +/** Parse a bounded JSON request body; undefined when it is missing or invalid. */ +async function readJsonBody(req) { + const buffer = await readRawBody(req); + if (buffer === undefined || buffer.length === 0) return undefined; + try { + const parsed = JSON.parse(buffer.toString('utf8')); + return parsed !== null && typeof parsed === 'object' ? parsed : undefined; + } catch { + return undefined; + } +} + +/** + * GET returns the ledger, PUT replaces it. + * + * Registered as a raw handler rather than a `resource`: the web server answers + * resource routes for GET/HEAD only and returns 405 for anything else before + * matching, which silently dropped every save (and the one-time import) while + * the ledger moved into SQLite. A handler owns the response, so PUT reaches it. + */ +async function serveSpend(req, res) { + if (req.method === 'GET' || req.method === 'HEAD') { + try { + sendJson(res, 200, { ok: true, state: readState(await database()) }); + } catch { + sendJson(res, 500, { ok: false, reason: 'database' }); + } + return; + } + if (req.method === 'PUT') { + const body = await readJsonBody(req); + if (body === undefined || body.state === undefined) { + sendJson(res, 400, { ok: false, reason: 'bad-body' }); + return; + } + const mode = typeof body.mode === 'string' ? body.mode : 'merge'; + try { + const db = await database(); + const incoming = normalizeState(body.state); + if (mode === 'merge') { + writeState(db, mergeState(readState(db), incoming)); + } else if (mode === 'replace') { + writeState(db, incoming); + } else if (mode === 'limits') { + replaceLimits(db, incoming); + } else if (mode === 'clear') { + clearHistory(db); + } else if (mode === 'day') { + const day = body.day; + if ( + day === null || + typeof day !== 'object' || + !Number.isSafeInteger(day.start) || + typeof day.currency !== 'string' || + !CURRENCY_PATTERN.test(day.currency) + ) { + sendJson(res, 400, { ok: false, reason: 'bad-day' }); + return; + } + replaceDay(db, { + start: day.start, + currency: day.currency, + buckets: day.buckets !== null && typeof day.buckets === 'object' ? day.buckets : {}, + }); + } else { + sendJson(res, 400, { ok: false, reason: 'bad-mode' }); + return; + } + sendJson(res, 200, { ok: true }); + } catch { + sendJson(res, 500, { ok: false, reason: 'database' }); + } + return; + } + sendJson(res, 405, { ok: false, reason: 'method' }, 'GET, HEAD, PUT'); +} + +/** One-time migration of the browser ledger into an empty database. */ +async function serveSpendImport(req, res) { + if (req.method !== 'POST') { + sendJson(res, 405, { ok: false, reason: 'method' }, 'POST'); + return; + } + const body = await readJsonBody(req); + if (body === undefined || body.state === undefined) { + sendJson(res, 400, { ok: false, reason: 'bad-body' }); + return; + } + try { + const db = await database(); + const imported = importState(db, normalizeState(body.state)); + sendJson(res, 200, { ok: true, imported, state: readState(db) }); + } catch { + sendJson(res, 500, { ok: false, reason: 'database' }); + } +} + +/** Last cached central-bank rates, or undefined when none were stored yet. */ +function readFxRates(db) { + const rows = db.prepare('SELECT code, rate, rate_date, fetched_at FROM fx_rates').all(); + if (rows.length === 0) return undefined; + const rates = {}; + let date = ''; + let fetchedAt = 0; + for (const row of rows) { + rates[row.code] = row.rate; + if (row.rate_date > date) date = row.rate_date; + if (row.fetched_at > fetchedAt) fetchedAt = row.fetched_at; + } + return { rates, date, fetchedAt }; +} + +function writeFxRates(db, rates, date, fetchedAt) { + db.exec('BEGIN IMMEDIATE'); + try { + db.exec('DELETE FROM fx_rates'); + const insert = db.prepare('INSERT INTO fx_rates (code, rate, rate_date, fetched_at) VALUES (?, ?, ?, ?)'); + for (const [code, rate] of Object.entries(rates)) insert.run(code, rate, date, fetchedAt); + db.exec('COMMIT'); + } catch (error) { + try { + db.exec('ROLLBACK'); + } catch { + /* Ignore a transaction SQLite already ended. */ + } + throw error; + } +} + +/** Rubles per one unit of each quoted currency, from the central-bank payload. */ +function parseFxPayload(payload) { + const valute = payload !== null && typeof payload === 'object' ? payload.Valute : undefined; + if (valute === null || typeof valute !== 'object') return undefined; + const rates = {}; + for (const code of FX_CODES) { + const entry = valute[code]; + if (entry === null || typeof entry !== 'object') continue; + const nominal = numeric(entry.Nominal) ?? 1; + const value = numeric(entry.Value); + if (value === undefined || !(nominal > 0)) continue; + rates[code] = value / nominal; + } + return Object.keys(rates).length > 0 ? rates : undefined; +} + +/** + * Rates for today: the cached copy while it is fresh, a fresh one otherwise. + * A failed fetch returns the stale copy rather than losing the conversion. + */ +async function currentFxRates(db) { + const cached = readFxRates(db); + if (cached !== undefined && Date.now() - cached.fetchedAt < FX_TTL_MS) return cached; + try { + const response = await fetch(FX_URL, { + headers: { accept: 'application/json' }, + signal: AbortSignal.timeout(FX_TIMEOUT_MS), + }); + if (!response.ok) throw new Error(`http-${response.status}`); + const payload = await response.json(); + const rates = parseFxPayload(payload); + if (rates === undefined) throw new Error('bad-payload'); + const date = typeof payload.Date === 'string' ? payload.Date : new Date().toISOString(); + const fetchedAt = Date.now(); + writeFxRates(db, rates, date, fetchedAt); + return { rates, date, fetchedAt }; + } catch { + return cached; + } +} + +/** GET the cached daily rates; the Client half converts foreign spend to rubles. */ +async function handleRates() { + try { + const result = await currentFxRates(await database()); + if (result === undefined) return json(200, { ok: false, reason: 'unavailable' }); + return json(200, { + ok: true, + base: 'RUB', + date: result.date, + fetchedAt: result.fetchedAt, + rates: result.rates, + }); + } catch { + return json(200, { ok: false, reason: 'database' }); + } +} + +/** + * Services this Host half needs. Declaring `webServer` here is what makes the + * route appear: without it the plugin can apply before the web server has + * provided the service, a one-shot `ctx.get` then returned undefined, and the + * reading fell back to "Balance —" because the browser called a 404. The order + * of that race depends on the rest of the composition, so it changed between + * launches. + */ +export const inject = ['webServer']; + +/** + * Register the operator-balance route. `ctx.inject` keeps the registration + * bound to the live service, so a later (re)appearance of `webServer` registers + * again instead of leaving a stale disposer behind. + */ +export function apply(ctx) { + const mount = (target) => { + const webServer = target.get('webServer'); + if (webServer === undefined) return; + target.effect( + () => + webServer.register({ + kind: 'exact', + path: '/api/cost-balance/operator-balance', + resource: (request) => handleBalance(ctx, request), + }), + 'cost-balance: operator balance route', + ); + target.effect( + () => + webServer.register({ + kind: 'exact', + path: '/api/cost-balance/rates', + resource: () => handleRates(), + }), + 'cost-balance: exchange rates route', + ); + target.effect( + () => + webServer.register({ + kind: 'exact', + path: '/api/cost-balance/spend', + handler: (req, res) => { + void serveSpend(req, res).catch(() => sendJson(res, 500, { ok: false, reason: 'database' })); + }, + }), + 'cost-balance: spending ledger route', + ); + target.effect( + () => + webServer.register({ + kind: 'exact', + path: '/api/cost-balance/spend/import', + handler: (req, res) => { + void serveSpendImport(req, res).catch(() => sendJson(res, 500, { ok: false, reason: 'database' })); + }, + }), + 'cost-balance: spending ledger import route', + ); + }; + /* `inject` above already delays apply until the service exists; the injected + * scope additionally re-mounts the route if the service is ever replaced, + * and the direct call covers a context without `inject`. */ + if (typeof ctx.inject === 'function') ctx.inject(['webServer'], mount); + else mount(ctx); +} diff --git a/locale/de.json b/locale/de.json new file mode 100644 index 0000000..17934ee --- /dev/null +++ b/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ausgaben und Guthaben in der Fußzeile", + "description": "Zeigt eine Schätzung der Ausgaben der aktuellen Sitzung und das verbleibende Kontoguthaben unter dem Eingabefeld." + } +} diff --git a/locale/en.json b/locale/en.json new file mode 100644 index 0000000..9763d4c --- /dev/null +++ b/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Spend, balance and usage statistics", + "description": "Shows the session's spend estimate and the remaining balance under the message composer, and a settings page with daily/hourly usage charts and soft limits." + } +} diff --git a/locale/es.json b/locale/es.json new file mode 100644 index 0000000..7d26960 --- /dev/null +++ b/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Gasto y saldo en el pie", + "description": "Muestra una estimación del gasto de la sesión actual y el saldo restante de la cuenta bajo el compositor de mensajes." + } +} diff --git a/locale/fr.json b/locale/fr.json new file mode 100644 index 0000000..86c2073 --- /dev/null +++ b/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Dépense et solde sous le compositeur", + "description": "Affiche une estimation de la dépense de la session en cours et le solde restant du compte sous le champ de saisie." + } +} diff --git a/locale/ja.json b/locale/ja.json new file mode 100644 index 0000000..86ca42a --- /dev/null +++ b/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "消費額と残高のフッター", + "description": "メッセージ入力欄の下に、現在のセッションの消費額の見積もりとアカウントの残高を表示します。" + } +} diff --git a/locale/pt.json b/locale/pt.json new file mode 100644 index 0000000..1194578 --- /dev/null +++ b/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Gasto e saldo no rodapé", + "description": "Mostra uma estimativa do gasto da sessão atual e o saldo restante da conta abaixo do campo de mensagem." + } +} diff --git a/locale/ru.json b/locale/ru.json new file mode 100644 index 0000000..522d87e --- /dev/null +++ b/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Расход, баланс и статистика", + "description": "Показывает оценку расхода и остаток баланса в строке под полем ввода, а в Settings — статистику потребления с графиками по дням и часам и условными лимитами." + } +} diff --git a/locale/zh.json b/locale/zh.json new file mode 100644 index 0000000..901f424 --- /dev/null +++ b/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "花费与余额", + "description": "在消息输入框下方的状态行显示当前会话的花费估算与账户剩余余额。" + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..7ae150c --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "@local/dsh-cost-balance-footer", + "version": "1.10.7", + "private": true, + "type": "module", + "description": "Session spend estimate and account balance under the Harness composer.", + "repository": { + "type": "git", + "url": "ssh://git@git.realmanual.ru:2022/pub/cost-balance-footer.git" + }, + "exports": { + ".": "./index.js", + "./client": "./client.js", + "./locale/*.json": "./locale/*.json", + "./icon": "./icon.svg" + }, + "files": [ + "index.js", + "client.js", + "cordis.patch.yml", + "locale/*.json", + "icon.svg" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "immediately": true, + "inject": [ + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-api-remotes" + ] + } + } +} \ No newline at end of file