From 0443949574a44d5c237a5a680c973415b419c9bd Mon Sep 17 00:00:00 2001 From: Vladimir Kochnev Date: Wed, 18 Nov 2026 17:55:05 +0300 Subject: [PATCH] =?UTF-8?q?fix(panel):=20=D1=87=D0=B8=D1=81=D0=BB=D0=BE=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=BE=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20=E2=80=94?= =?UTF-8?q?=20=D0=B8=D0=B7=20=D0=BA=D0=B0=D1=82=D0=B0=D0=BB=D0=BE=D0=B3?= =?UTF-8?q?=D0=B0=20=D0=BD=D0=B0=D0=B1=D0=BE=D1=80=D0=B0,=20=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D1=82=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Колонка TOOLS в таблице серверов набора и на странице всех серверов стояла прочерком у всех, пока каждую строку не проверят кнопкой «Проверить»: число бралось только из пробы, а проба — действие человека. Теперь у сервера работающего набора число берётся из каталога этого набора (`GET /api/sets//tools` — дескрипторы, которые помнит `tools.lock.json`): один запрос на открытие набора, счёт по серверам в `st.setTools`, чтение через `toolCount()`. Проба по-прежнему сильнее каталога и заменяет число живым счётом; у остановленного набора и у сервера, которого каталог не знает, остаётся `—`. Подсказка колонки говорит, откуда число. Приёмка панели: шаг W4 открывает страницу с чистой памятью и требует число без проверки — на прежнем коде шаг красный («колонка tools пуста до проверки»), теперь зелёный; шагов 38 с `ACC_DAP`, 26 без него. --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 7 +++++- CHANGELOG.ru.md | 8 ++++++- docs/en/dev/development.md | 2 +- docs/en/panel.md | 16 ++++++++----- docs/ru/dev/development.md | 2 +- docs/ru/panel.md | 16 ++++++++----- scripts/acceptance/panel.cjs | 23 +++++++++++++++++- web/app.js | 46 ++++++++++++++++++++++++++++++++---- web/codemap.md | 10 ++++++++ 10 files changed, 110 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ed175c..1c8cc9e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -161,7 +161,7 @@ jobs: fi node --check web/app.js - # Приёмка панели: 26 шагов без ACC_DAP (37 с ним — но stdio-сервера в CI нет). + # Приёмка панели: 26 шагов без ACC_DAP (38 с ним — но stdio-сервера в CI нет). # Ловит то, чего не видит `node --check`: маршруты, формы, темы, ключи, пустые # состояния. Панель поднимается на чистом каталоге, без пароля, на loopback. acceptance: diff --git a/CHANGELOG.md b/CHANGELOG.md index 016125c..bb1af4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,12 @@ repository the project is built in. ## [Unreleased] -Nothing yet. +### Fixed + +- The **Tools** column of a set's servers and of the all-servers page takes the + count from the catalog of a running set (`GET /api/sets//tools`) instead + of waiting for **Check** on every row; a probe still replaces it with a live + count, and a stopped set keeps `—`. ## [0.6.6] diff --git a/CHANGELOG.ru.md b/CHANGELOG.ru.md index 39b5b94..035d1dc 100644 --- a/CHANGELOG.ru.md +++ b/CHANGELOG.ru.md @@ -10,7 +10,13 @@ ## [Unreleased] -Новых изменений пока нет. +### Исправлено + +- Колонка **Инструментов** в таблице серверов набора и на странице всех + серверов берёт число из каталога работающего набора + (`GET /api/sets//tools`), а не ждёт **Проверить** у каждой строки; + проверка по-прежнему заменяет его живым счётом, у остановленного набора + остаётся `—`. ## [0.6.6] diff --git a/docs/en/dev/development.md b/docs/en/dev/development.md index f4cda87..2e7e40d 100644 --- a/docs/en/dev/development.md +++ b/docs/en/dev/development.md @@ -79,7 +79,7 @@ skipped run cannot read as a passed gate. ## Panel acceptance `scripts/acceptance/panel.cjs` walks the panel from an empty data directory and -checks 37 things a person would do by hand — the rail, themes, navigation, sets, +checks 38 things a person would do by hand — the rail, themes, navigation, sets, servers, keys, tools, statistics, the log, variables, import. 11 of them attach a stdio MCP server and therefore need `ACC_DAP`; without it those steps are skipped with a line each and the rest still run. It needs Playwright, and the diff --git a/docs/en/panel.md b/docs/en/panel.md index b700f78..2b1aaeb 100644 --- a/docs/en/panel.md +++ b/docs/en/panel.md @@ -25,7 +25,7 @@ CSP: no inline scripts or styles. | tabs | **Overview**, **Servers**, **Keys**, **Tools**, **Calls** and **Logs** of the open set, at `#/set/`, `#/set//servers`, `…/keys`, `…/tools`, `…/calls` and `…/logs`; an unknown tab opens **Overview**, a tab click adds a history entry, and the back and forward buttons walk through the tabs | | KPIs | calls, error rate, p50 and p95 of the selected set over the last 7 days, under the tiles of the set **Overview** | | servers of the set, on the **Servers** tab | name with a second line (daemon error, isolation, description), type, health, tool count, last request, **Check**, **Log**, **Tools**, **Edit** and the **×** that detaches the server from the set; under the table sit the registry picker and **add to set** | -| all servers page | the whole registry of the host: name with the daemon's reason on the second line, type, health, tool count from the last **Check**, the sets the server belongs to, and **Check**, **Authorize**, **Log**, **Edit** and the **×** that deletes it from the registry; **Add server** sits in the head | +| all servers page | the whole registry of the host: name with the daemon's reason on the second line, type, health, tool count from the set catalog or the last **Check**, the sets the server belongs to, and **Check**, **Authorize**, **Log**, **Edit** and the **×** that deletes it from the registry; **Add server** sits in the head | | import and export | the **Import / Export** dialog: the whole registry or one set as JSON, with **Download JSON** and **Copy**; import from a JSON file or a pasted `mcpServers` object — the preview names the servers that will be added, sets found in the file are skipped with a note (sets are made in the panel), and `env` and `headers` go out and come in as written | | calls table | time, server, tool, client, milliseconds, status; search box and **errors only**. Meta-tools (`list_servers`, `list_commands`, `describe_commands`) appear here too, as server `mcprig`; a failure shows its reason next to the status, the full text in a tooltip | | statistics page | the period (today, 7 days, 30 days, archive), the server, tool and client filters and **reset**, totals and the series. The first answer arrives as soon as the sets are known, so a direct `#/stats/` link is filled at once instead of waiting for the 15 s tick. The three filters are kept in the browser (`localStorage`, `mcprig.stats.*`) and survive a reload; the set of the view still follows the rail | @@ -39,9 +39,12 @@ health answer is on its way the cell keeps a skeleton bar instead of guessing. The badge of the all-servers page uses the same component and the same three states; a server outside the open set stays **Not checked** until **Check** probes it there, and a server of a stopped set says that the set is off. -The tool count of one server is not part of the health answer, so the **Tools** -column shows `—` until **Check** probes that server; the head of the set shows -the total for the whole set. +The tool count of one server is not part of the health answer. A server of a +running set takes it from that set's catalog (`GET /api/sets//tools`, the +descriptors `tools.lock.json` remembers), so the **Tools** column shows the +number as soon as the set has listed its tools; **Check** replaces it with a +live count of the same server. A server of a stopped set, and one no catalog +knows, keeps `—`; the head of the set shows the total for the whole set. The browser title names what is open: `mcprig — Overview`, `mcprig — Sets` and the like for other pages, `mcprig — set ` on a set, and with ` · ` @@ -149,8 +152,9 @@ key stops the set; revoking one of several leaves it running. The **All servers** page lists the whole registry of the host, not the composition of one set. A row carries the name with the daemon's reason of a -failure below it, the transport, the health badge, the tool count the last -**Check** found, the sets the server belongs to and the actions: **Check** +failure below it, the transport, the health badge, the tool count of the set +catalog or of the last **Check**, the sets the server belongs to and the +actions: **Check** (`POST /api/servers//probe`), **Authorize** for a remote server that answered `401`, **Log** of the open set, **Edit** and the **×** that deletes the server from the registry — the dialog names the sets it leaves first. Deleting diff --git a/docs/ru/dev/development.md b/docs/ru/dev/development.md index 10d1f79..2fa9e0b 100644 --- a/docs/ru/dev/development.md +++ b/docs/ru/dev/development.md @@ -80,7 +80,7 @@ E2E_BASE=http://127.0.0.1:9091 ./scripts/contract-e2e.sh ## Приёмка панели `scripts/acceptance/panel.cjs` проходит панель с пустого каталога данных и -проверяет 37 вещей, которые человек делает руками: рейл, темы, навигацию, +проверяет 38 вещей, которые человек делает руками: рейл, темы, навигацию, наборы, серверы, ключи, инструменты, статистику, журнал, переменные, импорт. 11 из них привязывают stdio MCP-сервер и потому требуют `ACC_DAP`; без него эти шаги пропускаются со строкой в выводе, остальные выполняются. Нужен diff --git a/docs/ru/panel.md b/docs/ru/panel.md index a62ecd8..3657019 100644 --- a/docs/ru/panel.md +++ b/docs/ru/panel.md @@ -25,7 +25,7 @@ | вкладки | **Обзор**, **Серверы**, **Ключи**, **Инструменты**, **Вызовы** и **Журнал** открытого набора — по адресам `#/set/`, `#/set//servers`, `…/keys`, `…/tools`, `…/calls` и `…/logs`; неизвестная вкладка открывает **Обзор**, клик по вкладке добавляет запись в историю, а кнопки «назад» и «вперёд» ходят по вкладкам | | KPI | вызовы, доля ошибок, p50 и p95 выбранного набора за последние 7 дней — под плитками **Обзора** набора | | серверы набора, вкладка **Серверы** | имя со второй строкой (ошибка демона, изоляция, описание), тип, здоровье, число инструментов, последний вызов, **Проверить**, **Лог**, **Инструменты**, **Изменить** и **×**, которая убирает сервер из набора; под таблицей — выбор сервера из реестра и **добавить в набор** | -| страница всех серверов | весь реестр хоста: имя с причиной от демона второй строкой, тип, здоровье, число инструментов из последней **проверки**, наборы, куда сервер входит, и действия **Проверить**, **Авторизовать**, **Лог**, **Изменить** и **×**, которая удаляет сервер из реестра; **Добавить сервер** — в шапке блока | +| страница всех серверов | весь реестр хоста: имя с причиной от демона второй строкой, тип, здоровье, число инструментов из каталога набора или последней **проверки**, наборы, куда сервер входит, и действия **Проверить**, **Авторизовать**, **Лог**, **Изменить** и **×**, которая удаляет сервер из реестра; **Добавить сервер** — в шапке блока | | импорт и экспорт | диалог **Импорт / Экспорт**: весь реестр или один набор как JSON, с **Скачать JSON** и **Копировать**; импорт из файла или вставленного объекта `mcpServers` — предпросмотр называет серверы, которые добавятся, наборы из файла пропускаются с пояснением (наборы делают в панели), а `env` и `headers` уходят и приходят как записаны | | таблица вызовов | время, сервер, инструмент, клиент, миллисекунды, статус; поиск и **только ошибки**. Сюда попадают и мета-инструменты (`list_servers`, `list_commands`, `describe_commands`) — с сервером `mcprig`; у провала рядом со статусом видна причина, полный текст — во всплывающей подсказке | | страница статистики | период (сегодня, 7 дней, 30 дней, архив), фильтры по серверу, инструменту и клиенту и **сброс**, итоги и ряд. Первый ответ приходит, как только известны наборы, поэтому прямая ссылка `#/stats/<период>` заполняется сразу, а не ждёт пятнадцатисекундного тика. Три фильтра хранятся в браузере (`localStorage`, `mcprig.stats.*`) и переживают перезагрузку; набор вида по-прежнему следует за рельсом | @@ -43,9 +43,13 @@ страницы всех серверов — тот же компонент и те же три состояния: сервер вне открытого набора остаётся **Без проверки**, пока его не проверит **Проверить** здесь, а сервер остановленного набора так и говорит, что набор выключен. Число -инструментов одного сервера в ответе о здоровье не приходит, поэтому в колонке -**Инструментов** стоит `—`, пока сервер не проверен кнопкой **Проверить**; -итог по всему набору показывает шапка набора. +инструментов одного сервера в ответе о здоровье не приходит. У сервера +работающего набора число берётся из каталога этого набора +(`GET /api/sets//tools` — дескрипторы, которые помнит `tools.lock.json`), +поэтому колонка **Инструментов** показывает число сразу, как набор перечислил +свои инструменты; **Проверить** заменяет его живым счётом того же сервера. У +сервера остановленного набора и у сервера, которого каталог не знает, остаётся +`—`; итог по всему набору показывает шапка набора. Всё на странице приходит из API панели ниже плюс `GET /stats` работающих наборов. В браузере не хранится ничего, кроме выбранной темы, её цветовой схемы @@ -206,8 +210,8 @@ MCP видит у этого сервера только инструменты. Страница **Все серверы** перечисляет весь реестр хоста, а не состав одного набора. В строке — имя с причиной отказа от демона второй строкой, транспорт, -бейдж здоровья, число инструментов из последней **проверки**, наборы, куда -сервер входит, и действия: **Проверить** +бейдж здоровья, число инструментов из каталога набора или последней +**проверки**, наборы, куда сервер входит, и действия: **Проверить** (`POST /api/servers//probe`), **Авторизовать** у удалённого сервера, ответившего `401`, **Лог** открытого набора, **Изменить** и **×**, которая удаляет сервер из реестра — диалог сначала называет наборы, которые он diff --git a/scripts/acceptance/panel.cjs b/scripts/acceptance/panel.cjs index baf5b32..0ab2db8 100644 --- a/scripts/acceptance/panel.cjs +++ b/scripts/acceptance/panel.cjs @@ -1,4 +1,4 @@ -// Приёмка панели: 37 шагов от чистого каталога данных — рейл, темы, навигация, +// Приёмка панели: 38 шагов от чистого каталога данных — рейл, темы, навигация, // наборы, серверы, ключи, инструменты, статистика, журнал, переменные, импорт. // // Запуск (нужен playwright; панель поднимается на чистом каталоге, без пароля): @@ -418,6 +418,27 @@ page.on("pageerror", e => consoleErrors.push("pageerror@" + lastStep + ": " + (e return `${rows} строк, одобрять нечего`; }); + await stepDap("W4 колонка tools берёт число из каталога набора без проверки", async () => { + // чистая страница: проба и каталог в памяти панели пустеют только с + // перезагрузкой документа, и число обязано появиться само, из каталога + await page.evaluate(() => { location.hash = "#/set/alpha/servers"; }); + await page.reload(); + const cell = await waitFor(async () => { + const t = (await page.textContent('#set-srv-body tr[data-name="dap"] td.num')).trim(); + return t && t !== "—" ? t : null; + }, 20000); + if (!cell) throw new Error("колонка tools пуста до проверки"); + // реестр хоста живёт тем же числом: сервер из работающего набора известен + await page.evaluate(() => { location.hash = "#/host"; }); + await page.reload(); + const reg = await waitFor(async () => { + const t = (await page.textContent('#servers tr[data-name="dap"] td.num')).trim(); + return t && t !== "—" ? t : null; + }, 20000); + if (!reg) throw new Error("в реестре хоста tools пуст до проверки"); + return `набор ${cell}, реестр ${reg}`; + }); + await step("X1 выдача ключа с подписью", async () => { await go("#/set/alpha/keys"); // Ждём по имени, а не по количеству: выдача ключа перезапускает набор, diff --git a/web/app.js b/web/app.js index 552b713..60d886f 100644 --- a/web/app.js +++ b/web/app.js @@ -148,7 +148,7 @@ 'setSrv.thTools': 'Tools', 'setSrv.thLast': 'Last call', 'setSrv.thAct': 'Actions', - 'setSrv.toolsTip': 'tool count comes from a probe of this server', + 'setSrv.toolsTip': 'tool count comes from the set catalog; a check confirms it live', 'setSrv.lastTip': 'from the last 100 calls', 'setSrv.emptyTitle': 'This set has no servers', 'setSrv.emptyText': 'Servers live in the host registry; attach one to give this set tools to serve.', @@ -531,7 +531,7 @@ 'setSrv.thTools': 'Инструментов', 'setSrv.thLast': 'Последний вызов', 'setSrv.thAct': 'Действия', - 'setSrv.toolsTip': 'число инструментов — из проверки этого сервера', + 'setSrv.toolsTip': 'число инструментов — из каталога набора, проверка уточняет вживую', 'setSrv.lastTip': 'по последним 100 вызовам', 'setSrv.emptyTitle': 'В наборе нет серверов', 'setSrv.emptyText': 'Серверы живут в реестре хоста; подключите один, чтобы у набора появились инструменты.', @@ -889,6 +889,8 @@ version: '', // probe — доказательства строки «Проверить»: они свежее кэша health (15 с) probeTools: {}, probeHealth: {}, healthBusy: false, + // setTools — каталог набора по серверам (id → {сервер: сколько инструментов}) + setTools: {}, tab: link.tab || 'overview', page: link.page, railPref: '', // list — страница «Наборы» без набора в адресе: показывается список, а не обзор list: link.page === 'sets' && !link.set, @@ -1915,7 +1917,7 @@ } // у остановленного набора инструментов нет, до проверки число // неизвестно: прочерк приглушённым — он не равен нулю и не загадка - var tc = st.probeTools[row.name]; + var tc = toolCount(row.name); var tcell = tr.children[3]; tcell.textContent = !running || tc == null ? '—' : fmtN(tc); tcell.classList.toggle('is-muted', tcell.textContent === '—'); @@ -1992,6 +1994,40 @@ .then(function () { st.busy = false; if (btn) { btn.disabled = false; } }); } + // Каталог набора помнит, сколько инструментов даёт каждый его сервер + // (tools.lock.json): счётчик строки берётся оттуда, а проверка уточняет его + // живым опросом. Впустую при недоступном каталоге не ходим: одна попытка на + // открытие набора, прочерк честнее нуля. + function ensureSetTools(id) { + if (st.setTools[id]) { return st.setTools[id]; } + st.setTools[id] = {}; + get('/api/sets/' + encodeURIComponent(id) + '/tools').then(function (data) { + if (!st.setTools[id]) { return; } + var counts = {}; + ((data && data.tools) || []).forEach(function (row) { + counts[row.server] = (counts[row.server] || 0) + 1; + }); + st.setTools[id] = counts; + renderSetServers(); + renderHost(); + }).catch(function () { st.setTools[id] = {}; }); + return st.setTools[id]; + } + + // Число инструментов сервера: свежая проба сильнее каталога, каталог — + // любого запущенного набора, где сервер стоит. + function toolCount(name) { + if (st.probeTools[name] != null) { return st.probeTools[name]; } + var sets = st.sets || []; + for (var i = 0; i < sets.length; i++) { + var s = sets[i]; + if (!(s.runtime && s.runtime.running) || (s.servers || []).indexOf(name) < 0) { continue; } + var counts = ensureSetTools(s.id); + if (counts[name] != null) { return counts[name]; } + } + return null; + } + // Одна проба на оба списка: из неё же берётся число инструментов строки. function probeServer(name, btn) { if (btn) { btn.disabled = true; } @@ -2038,6 +2074,7 @@ st.calls = null; st.probeTools = {}; st.probeHealth = {}; + st.setTools = {}; st.healthBusy = false; st.logKey = ''; // статистика идёт за рельсом: свой фильтр набора начинается с текущего, @@ -2524,7 +2561,8 @@ ? badgeState(probed, row.ownRunning, row.own, true) : badgeState(h, row.ownRunning, row.own)); badge.title = (probed && probed.error) || (h && h.error) || (probed ? t('srv.probeOkTip') : ''); - tr.children[3].textContent = st.probeTools[row.name] != null ? fmtN(st.probeTools[row.name]) : '—'; + var tc2 = toolCount(row.name); + tr.children[3].textContent = tc2 != null ? fmtN(tc2) : '—'; var setsCell = tr.querySelector('.cell-sets span'); setsCell.textContent = row.sets.length ? row.sets.map(function (s) { return s.name || s.id; }).join(', ') diff --git a/web/codemap.md b/web/codemap.md index 403d71c..32e4d8a 100644 --- a/web/codemap.md +++ b/web/codemap.md @@ -50,6 +50,16 @@ variables `#page-vars:667`. Five ``s: server editor `srv-dlg:711`, serve log `srvlog-dlg:833`, OAuth `auth-dlg:856`, import/export `io-dlg:881`, prompt `prompt-dlg:934`; keys and tools are tabs of the set, not dialogs. +**The tool count of a row has two sources, the fresh one wins.** A probe of the +row's own server fills `st.probeTools` (`probeServer`, `POST +/api/servers//probe`, `web/app.js:2032-2055`); without one, `toolCount()` +(`web/app.js:2019-2030`) reads the catalog of a running set that holds the +server — `GET /api/sets//tools` (`tools.lock.json`), counted per `server` +and fetched once per set open by `ensureSetTools()` into `st.setTools` +(`web/app.js:2001-2017`). A stopped set, and a server no catalog knows, keeps +`—`. The count is not part of the health answer, which is why the column has a +source of its own. + **Rendering is manual DOM with keyed reconciliation.** `el()` builds nodes (`web/app.js:919-924`); `sync(box, items, key, make, fill)` keeps a `Map` on the container, patches existing rows in place, inserts new ones, drops