@goodandready/dsh-cost-meter 0.7.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,11 @@
22
22
  - Документация:
23
23
  - README.md, index.md, docs/testing/public-route.md, docs/testing/projection-lifecycle.md, docs/deployment/public-release.md.
24
24
 
25
- ## Visual Direction
25
+ ## Visual Direction (Unified with dsh-clinebot)
26
+ - Атмосфера: Строгий утилитарный нативный интерфейс DSH, высокая информационная плотность без визуального шума.
27
+ - Утверждённые референсы: Эталонный плагин `@goodandready/dsh-clinebot`, дизайн-система DeepSeek Harness (`--dsw-alias-*`), карточки секций `.dcm-section-card`, бейджи статуса `.dcm-badge`, адаптивная сетка параметров `.dcm-grid-2`, чипы в шапке сессии.
28
+ - Отказоустойчивость: Обязательный `ErrorBoundary` вокруг карточки настроек и поповера шапки (предотвращает исчезновение слотов ядра при исключениях рендеринга).
29
+ - Синхронизация зеркал: `refreshMirrorUntilVisible(ctx)` для надёжного доступа к зеркалу `settingsScope`.
26
30
  - Атмосфера: Строгий утилитарный нативный интерфейс DSH, высокая информационная плотность без визуального шума.
27
31
  - Утверждённые референсы: Дизайн-система DeepSeek Harness (`--dsw-alias-*`), чипы в шапке сессии (`dsh-key-rotation`, `dsh-context-lens`), стандарт карточек настроек DSH.
28
32
  - Не копировать: Избыточные градиенты, внешние модальные окна, тяжелые тени, кастомные несогласованные шрифты.
@@ -41,7 +45,7 @@
41
45
  - Сетка и отступы:
42
46
  - Чип: высота 22px, padding: 0 8px, gap: 6px, border-radius: 6px.
43
47
  - Панель: padding: 12px 14px, border-radius: 10px, ширина 320px.
44
- - Карточка настроек: нативный складной контейнер (`.dcm-settings-card`), отступы полей, бейдж статуса снимка (`ready`, `loading`, `unavailable`).
48
+ - Карточка настроек: нативный складной контейнер (`.dcm-card`) с шапкой, статусами-бейджами (`dcm-badge-ok`, `dcm-badge-warn`, `dcm-badge-bad`), 3 структурированными секциями (`Основные параметры`, `Каталог OpenRouter`, `Диагностика и статус`), защитой ввода и кнопкой сохранения (`dcm-btn-primary`).
45
49
 
46
50
  ## Components & States
47
51
  - Чип:
@@ -1,22 +1,13 @@
1
- # Technical Findings (Issue #21)
1
+ # Findings: Issue #23
2
2
 
3
- ## 1. Config Fields Breakdown
4
- The plugin `Config` defines 10 fields:
5
- 1. `currency` (string, default '$') -> Present in UI
6
- 2. `usdRate` (number, default 1) -> Present in UI
7
- 3. `displayTimeZone` (string, default 'Europe/Moscow') -> Present in UI
8
- 4. `useOpenRouter` (boolean, default true) -> Missing in UI -> To be added as a checkbox in `CostMeterCard`
9
- 5. `refreshHours` (number, default 24) -> Missing in UI -> To be added as a numeric input in `CostMeterCard`
10
- 6. `modelMap` (dict of string -> string) -> Advanced JSON/YAML route mapping
11
- 7. `prices` (dict of PriceRow) -> Advanced manual pricing rules
12
- 8. `deepseekPeakPrices` (dict of PriceRow) -> Advanced DeepSeek peak overrides
13
- 9. `manualPeakWindowsUtc` (array of string) -> Advanced manual time windows
14
- 10. `manualOffPeakMultiplier` (number) -> Advanced discount multiplier for manual rates
3
+ ## Архитектурные паттерны dsh-clinebot
4
+ - Изолированный тег `<style id="dsh-cost-meter-unified-css" data-dsh-plugin="dsh-cost-meter">` с переменными `--dsw-alias-...`.
5
+ - `createErrorBoundary()` защищает слоты от падений при сбоях рендеринга.
6
+ - `refreshMirrorUntilVisible(ctx)` обеспечивает доступность зеркала настроек в `settingsScope`.
7
+ - Бейджи статуса (`cb-badge-ok`, `cb-badge-warn`, `cb-badge-bad`) позволяют пользователю моментально оценить состояние плагина.
15
8
 
16
- By adding `useOpenRouter` and `refreshHours` to `CostMeterCard`, all 5 primary scalar/control settings are directly configurable in the DSH Settings GUI. The 5 advanced structured override rules (`prices`, `modelMap`, `deepseekPeakPrices`, `manualPeakWindowsUtc`, `manualOffPeakMultiplier`) are explicitly documented in README.md and DESIGN.md as YAML configuration rows.
17
-
18
- ## 2. Service Access Pattern
19
- In `lib/index.js`, we have:
20
- `const settings = ctx.get('settings')` (canonical).
21
- In `lib/client.js`, `ctx.settingsScope` is accessed directly. We should safely check `(ctx.get && ctx.get('settingsScope')) || ctx.settingsScope || (ctx.services && ctx.services.settingsScope)`.
22
- Same for `ctx.locale` and `ctx.slots`.
9
+ ## Найденные баги в dsh-cost-meter
10
+ 1. Строка 427 `lib/index.js`: `catalog = { index: { byId: {}, bySuffix: {} }, fetchedAt: 0, error: null }` не содержала `byLowerId`. При обращении к `matchModel` до первой загрузки каталога вызывался `index.byLowerId[lower]`, что приводило к `TypeError`.
11
+ 2. `slotOf(event.time)`: при `undefined` возвращал `NaN`, повреждая ключи слотов в проекции.
12
+ 3. `fetch(CATALOG_URL)`: без таймаута мог блокировать цикл обновлений при сетевых лагах.
13
+ 4. `splitRoute`: отбрасывал модели без слэша.
@@ -1,17 +1,25 @@
1
- # Progress Log (Issue #21 / v0.7.9)
1
+ <!-- id: issue-23-progress -->
2
+ # Progress: Issue #23 — Стабилизация кода и редизайн UI по стандарту dsh-clinebot
2
3
 
3
- - [x] Analyze Issue #21
4
- - [x] Create worktree `.worktrees/issue-21`
5
- - [x] Initialize plans (`task_plan.md`, `findings.md`, `progress.md`)
6
- - [x] Bump version to 0.7.9 in `package.json`
7
- - [x] Implement settings card additions (`useOpenRouter`, `refreshHours`) in `lib/client.js`
8
- - [x] Safe service resolution with `ctx.get('...')` in `lib/client.js`
9
- - [x] Update documentation with full 10-field matrix (`README.md`, `docs/README.ru.md`, `docs/design/DESIGN.md`)
10
- - [x] Add regression test `test/settings-card-fields.test.mjs` (12/12 passing)
11
- - [ ] Commit changes with conventional commits (`git-antigravity`)
12
- - [ ] Create Pull Request and merge into `main`
13
- - [ ] Test package on MiniPC isolated test server (`192.168.1.123:3082`)
14
- - [ ] Smoke-test package on production candidate (`192.168.1.111:3080`)
15
- - [ ] Publish v0.7.9 to npm and GitHub Release
16
- - [ ] Install v0.7.9 from npm on MiniAI and verify live health
17
- - [ ] Close Gitea Issue #21 and clean up worktree
4
+ - [x] Создана Issue #23 в Gitea
5
+ - [x] Создан worktree `.worktrees/issue-23` на ветке `feat/stability-and-ui-clinebot`
6
+ - [x] Инициализированы файлы планирования (`task_plan.md`, `findings.md`, `progress.md`)
7
+ - [x] Применены серверные исправления (`lib/index.js`):
8
+ - [x] Инициализация `byLowerId` в начальном состоянии `catalog.index` (устранён крах холодного старта)
9
+ - [x] Защита `slotOf(timeMs)` от `NaN` при невалидных временных метках
10
+ - [x] Добавлен таймаут (15с) для внешних запросов к OpenRouter
11
+ - [x] Расширен `splitRoute` для поддержки моделей без слэша (`deepseek-chat`)
12
+ - [x] Экспорт `catalogModelsCount` в ответе `/dsh-cost-meter/state`
13
+ - [x] Применён визуальный редизайн по стандарту `dsh-clinebot` (`lib/client.js`):
14
+ - [x] Внедрён `createErrorBoundary()` для защиты слотов от падений
15
+ - [x] Внедрён `refreshMirrorUntilVisible(ctx)` для синхронизации настроек
16
+ - [x] Внедрена нативная CSS-система дизайн-токенов (`--dsw-alias-*`)
17
+ - [x] Шапка карточки снабжена бейджами статуса каталога, тарифа и таймзоны
18
+ - [x] Настройки структурированы по 3 секциям (`Основные параметры`, `Каталог OpenRouter`, `Диагностика`)
19
+ - [x] Модернизирован поповер шапки сессии
20
+ - [x] Обновлена документация (`DESIGN.md`, `README.md`, `docs/README.ru.md`)
21
+ - [x] Поднята версия до `0.7.10` в `package.json`
22
+ - [x] Написаны и успешно пройдены 16 тестов в `test/stability-and-visual.test.mjs` (`npm test` 16/16 pass)
23
+ - [ ] Оформление коммита, push ветки и создание PR #24
24
+ - [ ] Merge PR в `main` и сборка тарбола
25
+ - [ ] Тестирование на проде, публикация релиза v0.7.10 и закрытие Issue #23
@@ -1,32 +1,25 @@
1
- # Task Plan: Address Issue #21 (Settings Card Schema Fields & Service Access)
1
+ # Task Plan: Issue #23 — Стабилизация кода и редизайн UI карточки настроек по стандарту dsh-clinebot
2
2
 
3
- ## 1. Goal
4
- Fulfill Gitea Issue #21 requirements:
5
- 1. **Schema Fields Availability in Settings Card**:
6
- - Audit all 10 fields of `Config`:
7
- - UI fields: `currency`, `usdRate`, `displayTimeZone`.
8
- - Boolean toggle: `useOpenRouter` (checkbox / toggle in settings card).
9
- - Numeric: `refreshHours` (catalog refresh frequency, e.g. 24 hours).
10
- - Complex structured overrides: `prices` (dict), `modelMap` (dict), `deepseekPeakPrices` (dict), `manualPeakWindowsUtc` (array), `manualOffPeakMultiplier` (number).
11
- - Add `useOpenRouter` and `refreshHours` directly to the `CostMeterCard` form so all scalar/toggle configuration is editable in GUI.
12
- - Document structured dict/array fields (`prices`, `modelMap`, `deepseekPeakPrices`, `manualPeakWindowsUtc`, `manualOffPeakMultiplier`) in documentation, READMEs and DESIGN.md as YAML-only/advanced configuration rows.
13
- 2. **Context Service Access Hygiene**:
14
- - Inspect all `ctx.settings` / `ctx.settingsScope` / `ctx.locale` / `ctx.webServer` calls.
15
- - Use `ctx.get('...')` or inject where appropriate, or guard against undefined proxiable properties.
16
- 3. **Locale & Translations**:
17
- - Provide clean English locale strings as canonical with ru dictionaries, and hint descriptions for all new fields.
3
+ ## Цель
4
+ Устранить дефекты стабильности (холодный старт, event.time, таймаут OpenRouter, модели без слэша) и обновить UI плагина до единого стандарта dsh-clinebot (ErrorBoundary, дизайн-токены, бейджи, секции, адаптивная сетка, поповер).
18
5
 
19
- ## 2. Checklist
20
- - [ ] Bump version to 0.7.9 in `package.json`
21
- - [ ] Add `useOpenRouter` and `refreshHours` fields to `CostMeterCard` in `lib/client.js`
22
- - [ ] Update `en` and `ru` dictionaries for new fields
23
- - [ ] Audit and refine service accesses in `lib/index.js` and `lib/client.js`
24
- - [ ] Update `README.md`, `docs/README.ru.md`, `docs/README.zh.md`, and `docs/design/DESIGN.md`
25
- - [ ] Add unit test verifying settings card field contract
26
- - [ ] Run `npm test` (all tests passing)
27
- - [ ] Conventional commit & push
28
- - [ ] Gitea PR & merge
29
- - [ ] Test on MiniPC test server (`192.168.1.123`)
30
- - [ ] Install on production MiniAI (`192.168.1.111`) & verify
31
- - [ ] Release v0.7.9 on GitHub & npm
32
- - [ ] Close Issue #21 & cleanup worktree
6
+ ## Задачи
7
+ - [ ] 1. Исправление серверной части (`lib/index.js`):
8
+ - [ ] Инициализация `byLowerId` в начальном состоянии каталога
9
+ - [ ] Валидация `timeMs` в `slotOf(timeMs)`
10
+ - [ ] Добавление таймаута (15с) для запросов к `openrouter.ai`
11
+ - [ ] Поддержка моделей без префикса в `splitRoute`
12
+ - [ ] Экспорт диагностических метаданных (`catalogModelsCount`, `fetchedAt`, `error`) в `/dsh-cost-meter/state`
13
+ - [ ] 2. Обновление клиентской части (`lib/client.js`):
14
+ - [ ] Внедрение `createErrorBoundary()` и обёртка карточки и поповера
15
+ - [ ] Внедрение `refreshMirrorUntilVisible(ctx)`
16
+ - [ ] Единая CSS-система дизайн-токенов (`.dcm-section-card`, `.dcm-badge`, `.dcm-grid-2`, `.dcm-btn`, `.dcm-alert-*`)
17
+ - [ ] Структурирование настроек по 3 логическим секциям с бейджами статуса в шапке
18
+ - [ ] Модернизация поповера шапки на классы дизайн-системы
19
+ - [ ] Локализация новых ключей (`ru`, `en`)
20
+ - [ ] 3. Обновление документации:
21
+ - [ ] Актуализация `docs/design/DESIGN.md`, `README.md`, `docs/README.ru.md`
22
+ - [ ] 4. Тестирование:
23
+ - [ ] Написание юнит-тестов `test/stability-and-visual.test.mjs`
24
+ - [ ] Прогон всех тестов (`npm test`)
25
+ - [ ] 5. Сборка, PR, релиз v0.7.10, верификация на MiniAI и закрытие Issue #23