diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index 4a974da..b9fde0c 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -29,6 +29,9 @@ jobs: REGISTRY: ${{ secrets.REGISTRY }} REGISTRY_USER: ${{ secrets.REGISTRY_USER }} REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + # Имя ref — только через env: подстановка ${{ }} в текст shell + # исполняет метасимволы имени как код в job с паролем реестра. + REF: ${{ gitea.ref_name }} run: | set -euo pipefail if [ -z "${REGISTRY:-}" ] || [ -z "${REGISTRY_USER:-}" ] || [ -z "${REGISTRY_PASSWORD:-}" ]; then @@ -42,7 +45,7 @@ jobs: exit 0 fi # Версия без v — та же форма, что у goreleaser и в main.version. - ref="${{ gitea.ref_name }}" + ref="$REF" ver=$(printf '%s' "${ref:-dev}" | sed 's/^v//') revision=$(git rev-parse --short HEAD) repo="$REGISTRY/sintez/mcprig" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6cfc80e..1ed175c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -161,6 +161,46 @@ jobs: fi node --check web/app.js + # Приёмка панели: 26 шагов без ACC_DAP (37 с ним — но stdio-сервера в CI нет). + # Ловит то, чего не видит `node --check`: маршруты, формы, темы, ключи, пустые + # состояния. Панель поднимается на чистом каталоге, без пароля, на loopback. + acceptance: + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + # Версия playwright прибита: браузеры качаются под конкретную сборку. + - name: Playwright и Chromium + run: | + npm i --no-save --no-package-lock playwright@1.65.0 + npx playwright install --with-deps chromium + - name: Сборка панели + run: go build -o mcprig ./cmd/mcprig + - name: Приёмка панели + run: | + set -euo pipefail + DATA=$(mktemp -d) + # Панель не должна занять 9190: скрипт приёмки ждёт его свободным для + # набора beta (R7–R9 проверяют отказ и приём порта). + PORT=$(for p in $(seq 9100 9189); do + (exec 3<>"/dev/tcp/127.0.0.1/$p") 2>/dev/null || { echo "$p"; break; } + done) + MCPRIG_DATA_DIR="$DATA" MCPRIG_AUTH=off MCPRIG_PORT="$PORT" ./mcprig panel >panel.log 2>&1 & + PANEL=$! + trap 'kill $PANEL 2>/dev/null || true' EXIT + for _ in $(seq 60); do + curl -fsS "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1 && break + sleep 0.5 + done + curl -fsS "http://127.0.0.1:$PORT/healthz" >/dev/null || { echo "панель не ответила на /healthz"; cat panel.log; exit 1; } + ACC_BASE="http://127.0.0.1:$PORT" node scripts/acceptance/panel.cjs || { cat panel.log; exit 1; } + # Образ собирается только там, где его могут сломать: на PR и только если # тронуты Dockerfile, .dockerignore или зависимости. На push в master тесты # уже прошли, а тег всё равно собирает образы заново (release.yml). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1c6b3be..4ac6254 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,11 +28,16 @@ jobs: release: runs-on: ubuntu-latest timeout-minutes: 20 + # Тег приходит выражением, поэтому в run-блоки он попадает только через + # env: подстановка ${{ }} в текст shell превращает имя тега в код. + env: + TAG: ${{ inputs.tag || github.ref_name }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} fetch-depth: 0 + persist-credentials: false - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: ${{ env.GO_VERSION }} @@ -77,7 +82,7 @@ jobs: - name: Собрать архивы run: | set -euo pipefail - tag="${{ inputs.tag || github.ref_name }}" + tag="$TAG" notes="${RUNNER_TEMP:-/tmp}/release-notes.md" bash scripts/release-notes.sh "$tag" > "$notes" "$GORELEASER_BIN" release --clean --skip=publish --release-notes "$notes" @@ -88,7 +93,7 @@ jobs: IMAGE: ghcr.io/akrhin/mcprig run: | set -euo pipefail - ver=$(printf '%s' "${{ inputs.tag || github.ref_name }}" | sed 's/^v//') + ver=$(printf '%s' "$TAG" | sed 's/^v//') revision=$(git rev-parse --short HEAD) printf '%s' "${{ github.token }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin for target in slim full; do @@ -106,7 +111,7 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - tag="${{ inputs.tag || github.ref_name }}" + tag="$TAG" notes="${RUNNER_TEMP:-/tmp}/release-notes.md" if gh release view "$tag" >/dev/null 2>&1; then gh release upload "$tag" dist/*.tar.gz dist/checksums.txt --clobber diff --git a/.slim/codemap.json b/.slim/codemap.json index 30b52d5..ad132a0 100644 --- a/.slim/codemap.json +++ b/.slim/codemap.json @@ -1,7 +1,7 @@ { "metadata": { "version": "1.0.0", - "last_run": "2026-11-17T01:06:59.759Z", + "last_run": "2026-11-18T00:51:09.239Z", "root": "/home/sintez/git/mcprig", "include_patterns": [ "cmd/**/*.go", @@ -35,99 +35,104 @@ "Dockerfile": "698b9ed00cd45c9908af01a10418752c", "cmd/mcprig/approve.go": "475e27679cbe861102b4bfbafb557d1d", "cmd/mcprig/auth.go": "21a5aad507963d7878c7bf7ac41cf877", - "cmd/mcprig/doctor.go": "31fd2564a7fca62cd1b0cea38bafaf9a", + "cmd/mcprig/doctor.go": "0801e9b2348a8dd7fddc78147437c961", "cmd/mcprig/init.go": "2937bc79f0c85a59e0b4ac88083c7d55", - "cmd/mcprig/logs.go": "be33cdbdded0d3e6e68ed80552583d2d", - "cmd/mcprig/main.go": "f47bcb99fd86ecd49d7f80766b3ebba7", - "cmd/mcprig/panel.go": "072165bfd227e1a9ba2fccb10a8c33c3", + "cmd/mcprig/logs.go": "8fe53d75f25318252850403ec0d91e2e", + "cmd/mcprig/main.go": "7fd48df5a8b679cae658ffc21a848763", + "cmd/mcprig/panel.go": "2010dec46c2f62d2f0943c252711bc48", "cmd/mcprig/status.go": "d324f4770932aeebb1c7bf602fdd80c8", "cmd/mcprig/warm.go": "f9303aa9ae00763c77832d2a01027081", - "cmd/testmcp/main.go": "23dbc41af6732734b1b4d4fb5debd3a8", + "cmd/testmcp/main.go": "7c44976e05ec58c1a18c698fb9945538", "go.mod": "39b85794e8f75c2415bbc79b3d521ffe", "go.sum": "687535badb045779bfab21470ae037fa", "internal/atomicfile/atomicfile.go": "e489514c7fed15ba50680e50de37b930", - "internal/config/config.go": "1b11febf474228619468edd080a3b694", + "internal/config/config.go": "4a309d4af0af93c8adfe480eced83d98", "internal/config/permissions.go": "1a3b3496cdcb5d8e982f475945b608bd", "internal/config/profiles.go": "6e61da4909da61b902608d2bb8a26076", "internal/config/ratelimit.go": "4bd493b659e770be46d6bbd36b1a9132", "internal/config/secrets.go": "b9c055b1924fe3bc4120fba6b1d11d3f", - "internal/downstream/connect.go": "672cd6287dd08925641f4589c3a8a77f", + "internal/downstream/connect.go": "5849e461a5f8cf9c7a0d350391a9b8f8", "internal/downstream/env.go": "6e6cf2937acb065e0b5550c6c7b727df", "internal/downstream/guard.go": "e58a3693fab31ab1ad1f032032c3610f", "internal/downstream/procattr_linux.go": "b03eb21354a492eeb69192bf5a21090a", "internal/downstream/procattr_other.go": "7c8553a2937d4765af6daf3f93d7e683", "internal/downstream/procgroup.go": "d94ce47e903726f483d75801beb75a99", + "internal/downstream/serverlog.go": "a53f294d4c5b29eb16036fe7094a92c8", "internal/healthconst/healthconst.go": "b777f427aff61322d827c5d8e82eb038", - "internal/httplisten/httplisten.go": "13ab284206f17130398f614aa6083453", - "internal/manager/api.go": "5efe027381f3a527f6f93c41c3bd28ff", - "internal/manager/auth.go": "b3d9b2fbb6bec32a7117f5e3a3463f13", + "internal/httplisten/httplisten.go": "37fb94045fa29b03e82626754a48378b", + "internal/manager/api.go": "7bc9754c9186a81515625a0b82a7d076", + "internal/manager/auth.go": "b5d8fb58140d81cbfd99a857a33f7039", "internal/manager/browse.go": "d1ada39f0395a86270a3682e76f190a7", "internal/manager/calls.go": "cc4a0987e4764e84ca13cc6b89d18be8", "internal/manager/health.go": "c1c51f7a1fef63b6422635cfc0febc6b", - "internal/manager/notify.go": "5e2bb88aacc67d9ccf28b5d80c019bff", + "internal/manager/notify.go": "7e5708ddd82ff84dffe6c4659575fea3", "internal/manager/oauth.go": "997828deafd366c97da7c8dad96bdf6e", "internal/manager/panel.go": "ebf33858ab73e9109f75cf7b4ab4e964", "internal/manager/probe.go": "532ac0743950e7dbd4877ae33ca01dde", "internal/manager/prompt.go": "697b00f2331ad1798556a19f5c3659e9", - "internal/manager/runtime.go": "01e63a6dd5d651416661f6ad7671478d", + "internal/manager/runtime.go": "31b9337f40008a8e9aa4c56dce7b9c0f", "internal/manager/scrypt.go": "69ffa737b4b37aed3db8371614bc8b37", "internal/manager/secrets.go": "cc913e7121e1b5f9c31b59a5b90280e7", - "internal/manager/setconfig.go": "bfc25afca3812f5d9ac9aacf32b8f546", - "internal/manager/stats.go": "871e71a4f492b25705571a7b0d69ab8e", + "internal/manager/setconfig.go": "90e39b57456aca2ad6e450192f6a806f", + "internal/manager/stats.go": "71e25f43ca5c495a546ab329485cb2eb", "internal/manager/tools.go": "de26da0ef753c64b18cf0302829b4380", "internal/manager/ui.go": "264c6085e35a9510940fe8b9712029bf", - "internal/mcpserver/hints.go": "fa5bbced17518764f80cccb89ee3836d", - "internal/mcpserver/invokemany.go": "ed89a3db344bfd67c4c7c2c7c7a6a15c", + "internal/mcpserver/hints.go": "c95295210e17d9c20af1fd049688fa8b", + "internal/mcpserver/invokemany.go": "ae882eac20a75b91625219f7c63e111c", "internal/mcpserver/manager.go": "5cd2dd865b82f36511e326357fd76e73", "internal/mcpserver/permissions.go": "5b99ec1b585870e1e54763aed38ee554", "internal/mcpserver/quarantine.go": "5990f8a5e9f59429ecc28c00bb86e5f2", - "internal/mcpserver/ratelimit.go": "ad8a1fedc86c0620f1e00cb368e3b507", + "internal/mcpserver/ratelimit.go": "64d608fa677727f2d871868c67cc9d6b", "internal/mcpserver/redact.go": "9b31cd15e95489d2a9ab82728caeebba", "internal/mcpserver/resources.go": "2c1be2459f26d88eefeab26c81b3b4db", - "internal/mcpserver/toolout.go": "fb41e09e2002d499d597475e7e696498", + "internal/mcpserver/toolout.go": "9ad8ba2e0057727d593f26ebe80d6ab5", "internal/mcpserver/trace.go": "f5950dc934f37a97b38ed48e6f184bfd", "internal/oauth/callback.go": "edbe0ce3f1826c7a3d94334d94f18c10", - "internal/oauth/handler.go": "cfb49dbd517c2c1be5c4508004042c0e", + "internal/oauth/handler.go": "73e57e0ea539d27a494d951708971a28", "internal/oauth/store.go": "458b73ad770d7bbd015773893754bcde", "internal/registry/importexport.go": "5a8adee005867ba0962f2d96b2867813", "internal/registry/keys.go": "efdfafe3e1a1c03e5fd15b48f7659794", - "internal/registry/store.go": "807c18c244c3c48d62d8237f7b8a9b13", + "internal/registry/store.go": "3a115357e22972d04884f0d3ff667997", "internal/registry/types.go": "5109a939d94322e5d6a2ffbb1699b6a6", - "internal/registry/validate.go": "1286fd57470c0d1d95072d987c20e3d9", - "internal/sandbox/sandbox.go": "35cb0a887ffbe3472a80eb83c9ff2316", + "internal/registry/validate.go": "471040859299b9fd39ce14dee71a323d", + "internal/safelog/safelog.go": "cc7436f4179571ec9943cafc560bd7d1", + "internal/safepath/safepath.go": "b59dcf92710cada4cfd6a0a27e105842", + "internal/sandbox/sandbox.go": "b15566b51ed2a5b98f48c6d9b66da83f", "internal/stats/client.go": "9438b56e228f6dcfb3a0da2d5cac5acc", - "internal/stats/history.go": "ef52d8b7a87e2eb3c400a90f8d72de7e", - "internal/stats/history_query.go": "3996ea6019e5f94493119861b0994e22", - "internal/stats/stats.go": "9592741887a6421d5f8adaa1c2ee6b4b", + "internal/stats/history.go": "e44f86821d4116911dd9108a3b96d21f", + "internal/stats/history_query.go": "e6a17cf337560837f7f29bcce07431ca", + "internal/stats/stats.go": "fae47ef0a62e6d704e9c305498f00fd4", "internal/toollock/toollock.go": "b981314dd0624b37e3f9858f24104ab3", "internal/toolout/toolout.go": "ce1037a05b7004f89626fc1c4c162c96", - "web/app.css": "509bde7fcf8112c45b3404a80a1666d1", - "web/app.js": "ca9b5322acc4e59a62753107f1aa9362", + "web/app.css": "0a172e191ec9960feb0b40f95dcaa48b", + "web/app.js": "7e1a27bf7a20d1de7e8bc35bae17cc0c", "web/embed.go": "95e251fb8bc767a1ff5d152d9cd036dc", - "web/index.html": "e54d0883d76bbd9643e42303f08ee717", + "web/index.html": "0e60ecffc7980577937ff524ba8a37ea", "web/theme.js": "aa077af7e2ef195e0f8615eca74b388a", - "web/themes.css": "7e3cae02c2b5693cb76d15585cc44e6d", - "web/win98.css": "31841f08ffc4c6a18ee1add9173d18ae" + "web/themes.css": "2940c406626c78f8d563ac8ea3a15a68", + "web/win98.css": "34185960edc6e50847efca7f6a65a4cb" }, "folder_hashes": { ".": "f9a53356b6c5deefb28f2bc1db872bce", - "cmd": "0f450646fbceb131e6b3ad948b025d35", - "cmd/mcprig": "b781078328507c41c39c5573967d3273", - "cmd/testmcp": "3fffc5439dd510b4b0225fac1636576f", - "internal": "66a019809e3cc862d976268778d469bf", + "cmd": "d785ff7574758f31f18d24f11d4ed45f", + "cmd/mcprig": "29cc1565ed0f54283bb4a7beae7b37e5", + "cmd/testmcp": "c3cf52034ec0b8c0812c8c6ea7082e0c", + "internal": "b0fa7ae897323bf7e71d5444eb889f0e", "internal/atomicfile": "60e7434df17ad87bfe37282b42db5df6", - "internal/config": "70903cedde1489aabb2129ac3f72a410", - "internal/downstream": "766a13c38e786399eb5fb5ddf56beb3e", + "internal/config": "1357e91b8b70988f22fa37bd2cb889c7", + "internal/downstream": "607c5a0c10d3034d565794800d66b856", "internal/healthconst": "cb7d469210915bbae41ba5194238088c", - "internal/httplisten": "4d282958960cc1d79180600f7e12a613", - "internal/manager": "0c8be60bdfe24422cd3c80c77a41fe89", - "internal/mcpserver": "a0e9dd9bf983c8d67927bbc1046f2713", - "internal/oauth": "6eda091da4cbe38995aae2ada5bb60cf", - "internal/registry": "73a1a0cc0184d3520cd0fe1f1f950313", - "internal/sandbox": "e9017d826cf54e8a734c69ea32d30974", - "internal/stats": "47f5dcd3303589475ec473bed8ff5d57", + "internal/httplisten": "797c1f075b51cc6518b5f02536a43217", + "internal/manager": "e42802bba074717f689a88525304e802", + "internal/mcpserver": "98334cd0bf3954c8f0a3c9ab0a0fb0ca", + "internal/oauth": "dee683291b104f869fdbcb4281c986c6", + "internal/registry": "9d145a2aa2ab3c5a38161bf1d1083d5d", + "internal/safelog": "e3741dab57855ebc4b57077549a2484a", + "internal/safepath": "b0d0b0f7f2be3883b906e705bf477c0b", + "internal/sandbox": "1b85004f331d90bd74b0176ca7557885", + "internal/stats": "e658f2c41ff19673b349ba697d56f45d", "internal/toollock": "2464debc4ef0df9502c075ddf0307191", "internal/toolout": "f98527a76962f437bfe50ab9ae746082", - "web": "e8de7058fd06252a07ae9ec98e82395c" + "web": "7b19907a4dac2c7e10e72e227395207c" } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 7337a29..0c81c3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,130 @@ repository the project is built in. ## [Unreleased] +### Fixed + +- Reload applies profiles and keys as one generation: the listener receives the + new token list only when the reload needs no restart, so a key that arrived + together with a transport change is refused until the set restarts instead of + being accepted without its profile (D10). +- Upstream error text is masked like the payload: a server repeating its own + secret inside an error no longer leaks it into the tool answer, the counters + or `raw-*.jsonl`, meta-tools included (D12). +- Secrets are masked by value rather than by field name: every `env` or header + value of 8 bytes or more becomes `***` — `GITHUB_PAT` and `CF_ACCESS` + included — so a tool catalog may show `***` where a harmless path used to be + (D4). +- A panic inside the health probe no longer hangs every later request to that + set: the single-flight is released, the probe is retried and one `Warn` is + logged (D2). +- Deleting a set forgets its webhook transitions, so a new set created under the + same id warns again (D3). +- Failed logins: expired windows are dropped on every recorded failure and the + map is capped at 1024 entries, instead of being cleaned only when it had + already overflowed (D5). +- The tool-catalog throttle map sweeps marks older than its 5 s window instead + of growing for the lifetime of the process (D1). +- The statistics cache evicts the oldest quarter of its files by `mtime` instead + of dropping the whole map at 4096 entries (D7). +- CI: the `acceptance` job runs the 26-step panel acceptance on a freshly built + binary; `ACC_DAP` became optional and its 11 stdio steps are skipped with a + line in the output (D6). +- `GET /stats` of a set no longer hands the full snapshot to whoever holds the + set's key: a key now gets counters and latencies with client labels replaced + by `(аноним)` and upstream error texts emptied. The full snapshot goes to the + panel's own poll only (`X-MCPRig-Caller: panel`), so `/api/calls` keeps + showing labels and errors as before. +- Release pipeline: the tag name was expanded into the text of `run:` blocks in + jobs that hold a write token and the registry password, so a tag containing + shell metacharacters became code. The tag now arrives through `env:` and is + read as `"$TAG"`; the release checkout keeps no credentials in `.git/config` + (`persist-credentials: false`). The Gitea image workflow takes `gitea.ref_name` + the same way. Who may push `v*` tags is a hosting-side protection rule that + this repository cannot confirm. +- Server log: the **Log** dialog of a server showed only the access lines of the + set and was empty in practice. The child's stderr now goes to + `sets//serverlogs/.log`, capped at 256 KiB, kept after a stop so the + trace stays readable and cleared on the next start; an automatic restart + appends under a new marker instead of wiping the reason the server died. The + dialog appends that tail to the set lines. +- Server log: each run of the process opens with a `— запуск —` + marker, so a restart after a crash is told apart from the first start; a tail + that exists but cannot be read now comes with `error` in the answer and the + dialog prints it instead of showing "empty" as if the server were silent. +- Sets: `POST /api/sets` refused to say anything when the name was outside the + id pattern — it renamed the set silently. The id is now taken as typed and a + bad one is `400` with the rule in the message; the panel reduces the name to + that form in the form and shows the rule instead of sending something else. +- Panel: one refusal of the first `/api/state` stopped every timer for good — + the panel then sat frozen until a reload; the failure is reported and the + timers start anyway. +- Panel: a click that landed while the periodic sync held the panel showed + nothing; it now says an operation is in progress. +- Panel: the statistics page loaded its data only on the second tick when opened + by address; it now asks as soon as the sets are known. +- Server log: the mode of an existing tail file is brought back to `0600` when it + is opened, and a read failure answers with the file name inside the set rather + than the absolute data path. +- Test: `scripts/acceptance/panel.cjs` — the 37-step panel walk — now lives in + the repository instead of a scratch directory, and `web/ids_test.go` fails + when `app.js` asks for an id `index.html` does not have. +- Panel: the copy button of the endpoint moved the address out of the DOM for the + second it showed "copied" — switching the language in that window threw + `Cannot set properties of null`; the feedback now goes to the button label. +- Panel: deleting the open set returns to the list of sets; before, the next set + in the rail was opened, which read as "wrong set". +- Panel: on a narrow screen the copy feedback shrank the address button from 74 to + 45 px; it now shows a mark there and keeps its width. +- Panel: statistics opened by address stayed blank for up to 15 s — the load ran + before `/api/state` knew the sets and returned early; it now starts as soon as + the set is known. +- Panel: the statistics filters (server, tool, client) survive a reload. +- Panel: building a prompt with an empty task showed nothing and left the button + enabled; the "set has no servers" hint sat inside the field that is hidden in + exactly that case and was unreachable. Both are shown now. +- Panel: revoking the active key stops the set and takes a few seconds; the keys + tab now says so while it waits instead of going quiet. +- Panel: buttons and the key-note field were 27–31 px tall; the tap target + minimum is 32 px, and the Calls checkbox is pressed through its label. +- Panel: choosing a set in the rail opens that set from any page — from the host + overview, statistics, all servers; before, the click only changed the window + title, and on a fresh install the tabs of a set could not be reached at all. +- Panel: the state badge of a set (sets list, host overview, servers table) took + its colour from a class that does not exist and showed as a black dot — + `paintBadge` now accepts both spellings the callers use. +- Panel: a direct link to `#/set//` and a reload on it left the page + half-filled (health, calls and the tool catalogue arrived only with the 5 s + tick, the key profiles never); the first state now loads the set the address + names. +- Panel: the saved key label was silently dropped while the overview tick held + the busy flag, and a refused refresh after a revoke said nothing. +- Panel: the reason of a failed call and of a stopped set was cut to 80/60 + characters in the markup itself, so pressing it on a touch screen could not + reveal the rest; the DOM carries the whole text and only the line clamps it. +- Panel: deleting the open set jumped to the neighbour in the address bar before + returning to the list, leaving a foreign set in the history. +- CLI: `mcprig logs` printed the child's stderr as is, so escape sequences from a + server could rewrite the operator's terminal; control characters are stripped. +- Server log: a failed write, truncate or cleanup of the tail is now reported in + the set log instead of leaving "log is empty" for weeks, and one oversized + write can no longer push the file over its cap. +- Auth: `X-Forwarded-*` was trusted from any loopback peer once + `MCPRIG_PROXY_SECRET` was set, which let that peer skip the login limit by + naming a fresh client address; the request must now carry + `x-mcp-proxy-secret` as well. +- Panel: a deleted set left its rings, locks and nonces in memory, so a new set + with the same id appeared stopped, and a pending operation of a removed set + was never finished. +- Panel: a count the panel does not know yet (`tools to approve`, servers with an + error) printed `0`; it shows a dash instead of a wrong number. +- CLI: `mcprig logs --server` printed "log is empty" when the tail could not be + read; the answer carries `error` and the command prints the reason. +- Panel: the **Logs** tab of a set reported "log is empty" when `mcprig.log` existed + but could not be read; it now names the reason above the box. +- Panel: the **Log** dialog subtitle described the format wrongly (it said "set + log only"); it now says the set lines come first and the process tail after them, + and the same sentence is used by the tab. + ## [0.6.5] - 2026-11-17 ### Added diff --git a/CHANGELOG.ru.md b/CHANGELOG.ru.md index 2d5a261..c2712b8 100644 --- a/CHANGELOG.ru.md +++ b/CHANGELOG.ru.md @@ -10,6 +10,128 @@ ## [Unreleased] +### Исправлено + +- Перезагрузка применяет профили и ключи одним поколением: слушатель получает + новый список токенов только когда перезапуск не нужен, поэтому ключ, + приехавший вместе с транспортной правкой, отклоняется до перезапуска набора, + а не принимается без профиля (D10). +- Текст ошибки апстрима маскируется так же, как полезная нагрузка: сервер, + повторивший свой секрет в ошибке, больше не отдаёт его в ответ инструмента, + в счётчики и `raw-*.jsonl`, включая мета-инструменты (D12). +- Секреты маскируются по значению, а не по имени поля: любое значение `env` или + заголовка от 8 байт становится `***` — включая `GITHUB_PAT` и `CF_ACCESS`, — + поэтому в каталоге инструментов может появиться `***` там, где раньше был + безобидный путь (D4). +- Паника в пробе здоровья больше не вешает все последующие запросы к набору: + single-flight освобождается, проба повторяется, в лог идёт один `Warn` (D2). +- Удаление набора забывает его переходы webhook'а, поэтому новый набор с тем же + id снова предупреждает (D3). +- Неудачные входы: просроченные окна убираются при каждой записи, а карта + ограничена 1024 записями вместо чистки только после переполнения (D5). +- Карта троттлинга каталога инструментов (`refreshAt`) выметает метки старше + своего окна в 5 с, а не растёт всю жизнь процесса (D1). +- Кэш статистики вытесняет старейшую четверть файлов по `mtime`, а не сбрасывает + карту целиком на 4096 записях (D7). +- CI: job `acceptance` гоняет 26-шаговую приёмку панели на свежесобранном + бинаре; `ACC_DAP` стал необязательным, его 11 шагов со stdio-сервером + пропускаются со строкой в выводе (D6). +- `GET /stats` набора больше не отдаёт полный снимок всякому, у кого есть + ключ набора: ключ получает счётчики и задержки, метки клиентов заменены на + `(аноним)`, тексты ошибок апстрима пусты. Полный снимок получает только + опрос самой панели (`X-MCPRig-Caller: panel`), поэтому `/api/calls` + по-прежнему показывает метки и ошибки. +- Конвейер релиза: имя тега подставлялось в текст `run:`-блоков тех job, где + лежат write-токен и пароль реестра, поэтому тег с метасимволами shell + становился кодом. Теперь тег приходит через `env:` и читается как `"$TAG"`; + checkout релиза не оставляет учётных данных в `.git/config` + (`persist-credentials: false`). Образный воркфлоу Gitea получает + `gitea.ref_name` тем же путём. Кто вправе пушить теги `v*` — правило защиты + на хостинге, из репозитория этого не подтвердить. +- Журнал сервера: диалог **Журнал** у сервера показывал только строки доступа + набора и на практике был пустым. Теперь stderr дочернего процесса пишется в + `sets//serverlogs/<имя>.log`, ограничен 256 КиБ, переживает остановку, + чтобы след падения остался читаемым, и стирается при следующем запуске; + автоперезапуск дописывает под новой меткой, а не стирает причину падения. + Диалог добавляет этот хвост к строкам набора. +- Журнал сервера: каждый запуск процесса открывается меткой `— запуск <дата + время> —`, поэтому перезапуск после падения не спутать с первым стартом; + нечитаемый хвост приходит с полем `error`, и диалог печатает причину, а не + выдаёт тишину сервера за «журнал пуст». +- Наборы: `POST /api/sets` молча переименовывал набор, если имя не подходило под + шаблон id. Теперь id берётся как есть, а неподходящий — `400` с правилом в + тексте; панель приводит имя к этому виду прямо в форме и показывает правило. +- Панель: один отказ первого `/api/state` останавливал все таймеры — панель + замирала до перезагрузки; отказ показывается, а таймеры всё равно стартуют. +- Панель: клик, попавший в такт синхронизации, не давал ничего; теперь + показывается «идёт операция». +- Панель: статистика по прямому адресу подгружалась только со второго такта; + теперь запрос уходит, как только наборы известны. +- Журнал сервера: режим уже существующего файла хвоста возвращается к `0600` + при открытии, а отказ чтения отдаёт имя файла внутри набора, а не абсолютный + путь каталога данных. +- Тесты: `scripts/acceptance/panel.cjs` — обход панели на 37 шагов — теперь + лежит в репозитории, а `web/ids_test.go` падает, если `app.js` просит id, + которого нет в `index.html`. +- Панель: кнопка копирования адреса вынимала адрес из DOM на секунду показа + «скопировано» — смена языка в это окно падала на `Cannot set properties of + null`; теперь отклик пишется в подпись кнопки. +- Панель: на узком экране отклик копирования ужимал кнопку адреса с 74 до + 45 px; теперь там знак, а ширина держится. +- Панель: удаление открытого набора возвращает к списку наборов; раньше + открывался соседний, и это читалось как «не тот набор». +- Панель: статистика, открытая по адресу, до 15 секунд оставалась пустой: загрузка + шла раньше `/api/state`, не знала наборов и выходила; теперь стартует, как + только набор известен. +- Панель: фильтры статистики (сервер, инструмент, клиент) переживают перезагрузку. +- Панель: сборка промта с пустой задачей не показывала отказа и оставляла кнопку + нажимаемой; подсказка «в наборе нет серверов» лежала внутри поля, которое в этом + случае и скрывалось. Оба случая теперь видны. +- Панель: отзыв активного ключа останавливает набор и занимает несколько + секунд — вкладка «Ключи» говорит об этом, а не молчит. +- Панель: кнопки и поле подписи ключа были высотой 27–31 px; цель нажатия — 32 px, + а галочка Calls нажимается своей подписью. +- Панель: выбор набора в рейле открывает его с любой страницы — с обзора хоста, + со статистики, со списка серверов; раньше клик менял только заголовок окна, а + на чистой установке вкладки набора были недостижимы вовсе. +- Панель: бейдж состояния набора (список наборов, обзор хоста, таблица серверов) + брал цвет из несуществующего класса и рисовался чёрным кружком — `paintBadge` + теперь принимает оба варианта, которые передают вызывающие. +- Панель: прямая ссылка на `#/set//<вкладка>` и перезагрузка по ней + оставляли страницу полупустой (здоровье, вызовы и каталог инструментов + приходили только с пятисекундным тактом, профили ключей — никогда); теперь + первый ответ состояния сам открывает набор из адреса. +- Панель: сохранённая подпись ключа молча пропадала, пока такт обзора держал + флаг занятости, а отказ обновления после отзыва ключа ничего не сообщал. +- Панель: причина провала вызова и простоя набора обрезалась до 80/60 символов + прямо в разметке, поэтому нажатие на тач-экране не раскрывало ничего; полный + текст теперь в разметке, а строку укорачивает только оформление. +- Панель: удаление открытого набора сначала открывало соседа в адресной строке + и только потом возвращало к списку, оставляя чужой набор в истории. +- CLI: `mcprig logs` печатал stderr сервера как есть, и управляющие + последовательности сервера могли переписать терминал оператора; теперь + управляющие символы вырезаются. +- Журнал сервера: отказ записи, обрезки или очистки хвоста теперь виден в логе + набора, а не оставляет «журнал пуст» на недели; одна запись больше лимита + больше не выводит файл за потолок. +- Безопасность: `X-Forwarded-*` от loopback-пира принимались, как только задан + `MCPRIG_PROXY_SECRET`, — без сверки самого заголовка `x-mcp-proxy-secret`; + лимит входа можно было обойти с того же хоста. Теперь секрет сверяется в + постоянном времени до того, как учитывается адрес пира. +- Наборы: удаление набора не освобождало его кольца, замки и нонсы — новый + набор с тем же id наследовал сообщение прошлого; теперь они удаляются вместе + с набором, а файл `.owner` выгрузки создаётся эксклюзивно, чтобы заранее + подложенная ссылка в `/tmp/tool-out` не увела запись. +- Панель: неизвестное число (`tools to approve`, серверы с ошибкой) печаталось + как `0`; теперь прочерк. +- CLI: `mcprig logs --server` печатал «журнал пуст», когда хвост не читался; + ответ несёт `error`, и команда печатает причину. +- Панель: вкладка **Журнал** набора писала «лог пуст», когда `mcprig.log` есть, + но не читается; теперь причина видна над окном. +- Панель: подпись под диалогом **Журнал** описывала формат неверно («только лог + набора»); теперь там сказано, что строки набора идут первыми, а хвост процесса + после них, — той же фразой пользуется вкладка. + ## [0.6.5] - 2026-11-17 ### Добавлено diff --git a/README.md b/README.md index 3a3f08f..44fec94 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ umask 077; printf '%s' '' > demo.key ![mcprig panel](design/ui/panel.png) -*The panel: sets on their own ports and endpoints, and the servers of one set with transport and tool counts.* +*The panel: sets on their own ports and endpoints, the servers of one set, and its traffic for the last 7 days.* Docker works the same way, with no Go toolchain needed: `docker pull ghcr.io/akrhin/mcprig:latest` (`latest-full` adds node and python for diff --git a/README.ru.md b/README.ru.md index edb819a..f2f400a 100644 --- a/README.ru.md +++ b/README.ru.md @@ -46,7 +46,7 @@ umask 077; printf '%s' '' > demo.key ![mcprig panel](design/ui/panel.png) -*Панель: наборы со своими портами и точками входа и серверы одного набора — транспорт и число инструментов.* +*Панель: наборы со своими портами и точками входа, серверы одного набора и его трафик за 7 дней.* Docker работает так же и не требует Go: `docker pull ghcr.io/akrhin/mcprig:latest` (`latest-full` добавляет node и python для `npx`/`uvx`-серверов). Юниты systemd, diff --git a/cmd/mcprig/access_test.go b/cmd/mcprig/access_test.go index 3f717e3..2f3dab0 100644 --- a/cmd/mcprig/access_test.go +++ b/cmd/mcprig/access_test.go @@ -70,14 +70,16 @@ func (e *accessEnv) reload() { } } -// stats забирает снимок слушателя: без заголовка — как анонимный клиент. -func (e *accessEnv) stats(auth string) (int, stats.Snapshot) { +// statsPanel забирает снимок так, как это делает панель: набор отдаёт метки +// клиентов и тексты ошибок только служебному вызову. +func (e *accessEnv) statsPanel(auth string) (int, stats.Snapshot) { e.t.Helper() r := httptest.NewRequest(http.MethodGet, "/stats", nil) r.Host = "127.0.0.1" if auth != "" { r.Header.Set("Authorization", "Bearer "+auth) } + r.Header.Set(stats.ServiceCallHeader, stats.ServiceCallerPanel) w := httptest.NewRecorder() e.handler.ServeHTTP(w, r) var snap stats.Snapshot @@ -185,7 +187,7 @@ func TestIssuedLabelAppliesWithoutRestart(t *testing.T) { if code, body := e.call("k1"); code != http.StatusOK || body != label { t.Fatalf("метка ключа не применилась: %d %q", code, body) } - code, snap := e.stats("k1") + code, snap := e.statsPanel("k1") if code != http.StatusOK { t.Fatalf("stats: %d", code) } diff --git a/cmd/mcprig/codemap.md b/cmd/mcprig/codemap.md index d360b48..168cb9c 100644 --- a/cmd/mcprig/codemap.md +++ b/cmd/mcprig/codemap.md @@ -21,15 +21,15 @@ Top-level subcommands (dispatch: `main.go:179-247`): | command | flags (definition site) | | --- | --- | | `serve` (default) | `-config` main.go:98, `-version` main.go:99, `-addr` main.go:100 | -| `stdio` | `-config` main.go:106 | +| `stdio` | `-config` main.go:157 | | `auth` | `-set` auth.go:73, `-config` auth.go:74, `-timeout` (6m) auth.go:75; positional server name auth.go:82 | -| `approve` | `-set` approve.go:33, `-all` approve.go:34, `-panel` approve.go:35, `-password` approve.go:36, `-secret` approve.go:37, `-user` approve.go:38; positional `server/tool` approve.go:53 | +| `approve` | `-set` approve.go:31, `-all` approve.go:32, `-panel`/`-password`/`-secret`/`-user` from `panelFlags` (panel.go:34-39); positional `server/tool` approve.go:47 | | `panel` | `-h`/`--help` prints the environment table (`newPanelFlags` main.go:107-118, `panelEnv` main.go:125-153); any other argument is a `usageError` (main.go:170-171) | | `init` | `-client` init.go:27, `-set` init.go:28, `-remote` init.go:29, `-key` init.go:30, `-key-file` init.go:31, `-binary` init.go:32, `-config` init.go:33 | -| `doctor` | `-config` doctor.go:71, `-json` doctor.go:72 | -| `warm` | `-url` warm.go:62, `-panel` warm.go:63, `-set` warm.go:64, `-all` warm.go:65, `-timeout` (2m) warm.go:66, `-token` warm.go:67, `-token-file` warm.go:68, `-config` warm.go:69, `-json` warm.go:70, `-password` warm.go:71, `-secret` warm.go:72, `-user` warm.go:73 | -| `status` | `-panel` status.go:72, `-set` status.go:73, `-json` status.go:74, `-timeout` (10s) status.go:75, `-password` status.go:76, `-secret` status.go:77, `-user` status.go:78 | -| `logs` | `-panel` logs.go:47, `-set` logs.go:48, `-server` logs.go:49, `-n` (200) logs.go:50, `-f` logs.go:51, `-json` logs.go:52, `-password` logs.go:53, `-secret` logs.go:54, `-user` logs.go:55 | +| `doctor` | `-config` doctor.go:70, `-json` doctor.go:71 | +| `warm` | `-url` warm.go:61, `-set` warm.go:62, `-all` warm.go:63, `-timeout` (2m) warm.go:64, `-token` warm.go:65, `-token-file` warm.go:66, `-config` warm.go:67, `-json` warm.go:68, panel flags warm.go:69 | +| `status` | `-set` status.go:70, `-json` status.go:71, `-timeout` (10s) status.go:72, panel flags status.go:73 | +| `logs` | `-set` logs.go:47, `-server` logs.go:48, `-n` (200) logs.go:49, `-f` logs.go:50, `-json` logs.go:51, panel flags logs.go:52 | ## Design @@ -48,96 +48,106 @@ help instead of `serve`. An unknown subcommand is a `usageError`, never a silent otherwise; `doctor` and `warm` problems exit `1` without an extra line because their report is already printed (main.go:64-67). -Mode dispatch (`run`, main.go:264-389) maps `stdio|auth|panel|init|doctor|warm| +Mode dispatch (`run`, main.go:264-392) maps `stdio|auth|panel|init|doctor|warm| approve|status|logs` to their `run*`; anything else is `serve`. `panel` is one call, `manager.Run(manager.FromEnv(version))` (main.go:275): the panel is `internal/manager`, configured by environment rather than flags. Layering: `cmd/mcprig` carries no protocol logic. `serve` assembles `internal/mcpserver` (proxy) over `internal/downstream` (child processes, OAuth) -and wraps it with `internal/httplisten` (main.go:343-346); `status`, `logs`, +and wraps it with `internal/httplisten` (main.go:346-349); `status`, `logs`, `warm`, `approve` are HTTP clients of the panel API; `doctor` reads `registry.json`, the config and probes sockets (`auth` is `internal/downstream` with a print-only browser, auth.go:99-109). ## Flow -`serve` (main.go:291-389): parse flags → `-version` prints and exits → +`serve` (main.go:291-392): parse flags → `-version` prints and exits → `internal/config.Load` → `slog` on stderr → OTLP tracing when the env asks -(`startTracing`, main.go:599) → `oauth.OpenStore(stateDir())` → -`downstream.Connector` with an env whitelist (`downstream.EnvFor`) → +(`startTracing`, main.go:609) → `oauth.OpenStore(stateDir())` → +`downstream.Connector` with an env whitelist (`downstream.EnvFor`) and, in +`serve`, the on-disk server tails (`conn.ServerLogs`, main.go:317) → `mcpserver.New` → `mgr.LockPath = lockPath()` → `stats.NewRecorder(MCPRIG_SET)` assigned before warm-up so the panel sees schema weight → history at `/stats`, warning only on failure -(main.go:330-335) → `go mgr.Warm` in the background → `mgr.ToolOutURL` only when -a transport token exists (main.go:342) → `httplisten.New` → listen address from +(main.go:331-338) → `go mgr.Warm` in the background → `mgr.ToolOutURL` only when +a transport token exists (main.go:345) → `httplisten.New` → listen address from `-addr`, else `transport.host`/`transport.port`, else `127.0.0.1:9100` -(main.go:348-359) → `http.Server` with `ReadHeaderTimeout` 10s and `IdleTimeout` -60s but no `ReadTimeout`, because sets stream SSE (main.go:362) → +(main.go:351-362) → `http.Server` with `ReadHeaderTimeout` 10s and `IdleTimeout` +60s but no `ReadTimeout`, because sets stream SSE (main.go:365) → `SIGINT`/`SIGTERM` context → `SIGHUP` loop → `startToolout` → `ListenAndServe` in a goroutine → log line `прокси слушает` with address and usable server count -→ 5-second graceful shutdown on signal (main.go:386-388). +(main.go:381) → 5-second graceful shutdown on signal (main.go:386-391). -SIGHUP reload (main.go:392-434): read the nonce from `/reload.request` +SIGHUP reload (main.go:394-442): read the nonce from `/reload.request` before loading; `config.Load`; on failure `mgr.ReloadFailed` and the previous -config keeps serving; on success apply the auth policy to the listener -(`handler.SetAuth`, main.go:424), then `mgr.Reload`; finally write +config keeps serving; on success `mgr.Reload` runs first (main.go:428) — profiles +and tokens are one generation, so a key handed to the listener while the manager +still holds the rolled-back profile table would pass unprofiled — and the auth +policy reaches the listener (`handler.SetAuth`, main.go:435) only when +`RestartNeeded` is empty; otherwise one warning line names the fields that wait +for a set restart (main.go:431-433). Then write `/reload.status` atomically (temp file, 0600, rename — -main.go:495-532) with nonce, generation, applied, restartNeeded, error. -`stdio` (main.go:546-594) is the same assembly minus listener, auth policy and -warm-up — config, tracing, OAuth store, connector, manager, lock, recorder -labelled `stdio` (main.go:576), history at `/stdio/stats`, +main.go:505-542) with nonce, generation, applied, restartNeeded, error. +`stdio` (main.go:556-603) is the same assembly minus listener, auth policy and +warm-up — config, tracing, OAuth store, connector (no `ServerLogs`), manager, +lock, recorder labelled `stdio` (main.go:586-587), history at `/stdio/stats`, tool-out sweeper, then `mgr.Server().Run(ctx, &mcp.StdioTransport{})`. `panel`: `cmd` loads no config; `internal/manager` reads `registry.json`, takes -the `manager.pid` lock in the data dir (internal/manager/api.go:370-385), +the `manager.pid` lock in the data dir (internal/manager/api.go:374-389), listens on `MCPRIG_HOST:MCPRIG_PORT` (default `127.0.0.1:9091`) and spawns each set as ` serve --config /servers.json` in its own process group with `MCPRIG_SET` and `MCPRIG_DATA_DIR=/sets/` -(internal/manager/runtime.go:242-243, 841-846), writing set logs to -`/sets//mcprig.log` (internal/manager/setconfig.go:195-197); this -package itself writes only `reload.status`. +(internal/manager/runtime.go:262-265, 905), writing set logs to +`/sets//mcprig.log` and each server's stderr to +`/sets//serverlogs/.log` (internal/manager/setconfig.go:201-209); +this package itself writes only `reload.status`. `auth` resolves the target (auth.go:32-59): `-set` reads `/sets//servers.json` and stores the token in that same directory; `-config` keeps the store in the caller's data dir. It prints the link, waits up to `-timeout`, and reports whether `oauth.json` was written. -`warm` has three paths after pre-checks (warm.go:82-93): `-config` in-process via -`internal/mcpserver` (warm.go:170), `-all` from `/api/sets` (warm.go:400), else a -single set, with `-url` bypassing the panel or the port resolved by name -(warm.go:358-380). Token precedence `--token` → `--token-file` → `MCPRIG_TOKEN` -→ `~/.config/mcprig/.token` (warm.go:306-326); a failed set makes the -process exit `1` via `errWarmProblems`. +`warm` has three paths after pre-checks (warm.go:78-89): `-config` in-process via +`internal/mcpserver` (`warmLocal`, warm.go:166), `-all` from `/api/sets` +(`warmAll`, warm.go:384), else a single set (`warmOne`, warm.go:125), with `-url` +bypassing the panel or the port resolved by name (`endpointFor`, warm.go:342). +Token precedence `--token` → `--token-file` → `MCPRIG_TOKEN` +→ `~/.config/mcprig/.token` (`warmToken`, warm.go:290-309); a failed set +makes the process exit `1` via `errWarmProblems` (warm.go:31). ## Integration Internal packages here: `config`, `downstream`, `httplisten`, `manager`, `mcpserver`, `oauth`, `stats`, `toolout` (main.go:22-30), plus `registry` and `sandbox` (doctor.go:22-26) and `toollock` (approve.go:17). Panel API consumed -by the CLI: `POST /api/login` (panel.go:56), `/healthz` -(status.go:201), `/api/state` (status.go:125), `/api/calls?set=&limit=1` -(status.go:173), `/api/sets` (warm.go:389), `POST /api/sets//tools/approve` -(approve.go:103), `/api/sets//logs` and -`/api/sets//servers//logs` (logs.go:118-120). Every write carries +by the CLI: `POST /api/login` (panel.go:80), `/healthz` +(status.go:197), `/api/state` (status.go:120), `/api/calls?set=&limit=1` +(status.go:168), `/api/sets` (warm.go:384), `POST /api/sets//tools/approve` +(approve.go:98), `/api/sets//logs` and +`/api/sets//servers//logs` (logs.go:115-117). `fetchLogs` +(`logs.go:114-140`) turns the panel's `error` field into a CLI error instead of +an empty tail, and `printLogs` prints a server's line through `safelog.Text` +(`logs.go:191-205`). Every write carries `Origin` computed from the panel URL, because the panel's CSRF check rejects a -session cookie without it (panel.go:119-121, 138-143). +session cookie without it (panel.go:120, 145). On-disk layout: config default `os.UserConfigDir()/mcprig/servers.json` -(main.go:534-539); state dir `MCPRIG_DATA_DIR`, else `$XDG_STATE_HOME/mcprig`, -else `~/.local/state/mcprig`, else `.mcprig` (main.go:615-627); OAuth tokens at +(main.go:544-549); state dir `MCPRIG_DATA_DIR`, else `$XDG_STATE_HOME/mcprig`, +else `~/.local/state/mcprig`, else `.mcprig` (main.go:625-637); OAuth tokens at `/oauth.json` and per set `/sets//oauth.json`; approved-descriptor lock at `/tools.lock.json`, empty path when the variable is unset so a manual `serve` has no quarantine owner -(main.go:633-638); tool-out dumps under `/tool-out` +(main.go:643-648); tool-out dumps under `/tool-out` (internal/toolout/toolout.go:47-55); warm token file -`~/.config/mcprig/.token` (warm.go:320, 340-346). Environment read directly -here: `MCPRIG_PPROF` (main.go:38), `MCPRIG_SET` (main.go:323), -`MCPRIG_DATA_DIR`/`XDG_STATE_HOME` (main.go:616-628); the full set `panel` +`~/.config/mcprig/.token` (warm.go:304, 309). Environment read directly +here: `MCPRIG_PPROF` (main.go:38), `MCPRIG_SET` (main.go:326, 579), +`MCPRIG_DATA_DIR`/`XDG_STATE_HOME` (main.go:625-637); the full set `panel` reads is the `panelEnv` table, which `panel -h` prints (main.go:125-153) — OpenBao's `BAO_*`/`OPENBAO_*` arrive from `internal/manager/secrets.go:115-128`. Also -`MCPRIG_PANEL_URL`/`MCPRIG_PORT` (panel.go:32-35), `MCPRIG_PASSWORD` -(panel.go:46), `MCPRIG_PROXY_SECRET`, `MCPRIG_USER_HEADER` (panel.go:149, 159), -`MCPRIG_TOKEN` (warm.go:317), `MCPRIG_KEY` (init.go:131), plus for `doctor` +`MCPRIG_PANEL_URL`/`MCPRIG_PORT` (panel.go:42-50), `MCPRIG_PASSWORD` +(panel.go:70), `MCPRIG_PROXY_SECRET`, `MCPRIG_USER_HEADER` (panel.go:173, 183), +`MCPRIG_TOKEN` (warm.go:301), `MCPRIG_KEY` (init.go:131), plus for `doctor` `MCPRIG_BIND_IP`/`MCPRIG_HOST`/`MCPRIG_PORT`/`MCPRIG_PUBLIC_URL`/`MCPRIG_AUTH`/ `MCPRIG_PASSWORD_HASH` (doctor.go:88-98). `deploy/` relation: `mcprig.service` runs `mcprig panel` with diff --git a/cmd/mcprig/doctor.go b/cmd/mcprig/doctor.go index d913515..fc9a9b6 100644 --- a/cmd/mcprig/doctor.go +++ b/cmd/mcprig/doctor.go @@ -13,7 +13,6 @@ import ( "net/url" "os" "path/filepath" - "regexp" "sort" "strconv" "strings" @@ -530,17 +529,8 @@ func checkServices(o doctorOptions, reg *registry.Data, regErr error) []doctorLi return lines } -var secretRefRe = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}`) - func mentionedSecrets(raw []byte) []string { - seen := map[string]bool{} - for _, m := range secretRefRe.FindAllSubmatch(raw, -1) { - seen[string(m[1])] = true - } - names := make([]string, 0, len(seen)) - for name := range seen { - names = append(names, name) - } + names := config.EnvRefs(string(raw)) sort.Strings(names) return names } diff --git a/cmd/mcprig/logs.go b/cmd/mcprig/logs.go index 7f42d8b..cad1cc5 100644 --- a/cmd/mcprig/logs.go +++ b/cmd/mcprig/logs.go @@ -16,6 +16,8 @@ import ( "strings" "syscall" "time" + + "github.com/akrhin/mcprig/internal/safelog" ) // logsPollInterval — шаг опроса -f; переменная, чтобы тест не ждал секунду. @@ -120,11 +122,17 @@ func fetchLogs(ctx context.Context, client *http.Client, base string, creds pane return nil, err } var res struct { - Logs []json.RawMessage `json:"logs"` + Logs []json.RawMessage `json:"logs"` + Error string `json:"error"` } if err := json.Unmarshal(raw, &res); err != nil { return nil, fmt.Errorf("панель %s: %s: %w", base, path, err) } + // Панель отвечает пустым списком и причиной, когда хвост не прочитан: + // молчание в терминале читалось бы как «сервер ничего не писал». + if res.Error != "" { + return nil, fmt.Errorf("журнал сервера не прочитан: %s", res.Error) + } out := make([]logLine, 0, len(res.Logs)) for _, r := range res.Logs { out = append(out, decodeLogLine(r)) @@ -187,7 +195,9 @@ func printLogs(o *logsConfig, lines []logLine) { var b strings.Builder for _, l := range lines { if !o.JSON { - b.WriteString(l.Line) + // Вывод сервера — чужой текст: управляющие последовательности в + // терминале оператора подменяют видимый лог и заголовок окна. + b.WriteString(safelog.Text(l.Line)) b.WriteByte('\n') continue } diff --git a/cmd/mcprig/main.go b/cmd/mcprig/main.go index 83d4bf5..eb62601 100644 --- a/cmd/mcprig/main.go +++ b/cmd/mcprig/main.go @@ -312,6 +312,9 @@ func run() error { } // Env: ребёнку уходит whitelist плюс envAllow сервера, а не весь os.Environ(). conn := &downstream.Connector{Version: version, OAuth: cfg.OAuth, Store: store, Log: log, Env: downstream.EnvFor} + // stderr детей набора — в файл рядом с servers.json: панель читает его как + // «лог сервера». stdout ребёнка занят протоколом. + conn.ServerLogs = downstream.NewServerLogs(filepath.Dir(*cfgPath), log) mgr := mcpserver.New(cfg, version, conn) defer func() { if err := mgr.Close(); err != nil { @@ -417,13 +420,20 @@ func reloadOnce(mgr *mcpserver.Manager, handler *httplisten.Server, cfgPath stri if err != nil { res = mgr.ReloadFailed(err) } else { - // Политика доступа применяется слушателем здесь же: выдача нового - // ключа и потеря последнего не ждут перезапуска набора. Остальной - // транспорт — дело mgr.Reload. - if handler != nil && cfg.Transport != nil { + // Профили и токены — одно поколение, поэтому сначала Reload, потом + // ключи: SetAuth до Reload отдал бы слушателю ключ новой таблицы, + // пока менеджер ещё держит старую, и такой ключ прошёл бы без + // профиля. Транспортные поля, отвергнутые Reload, откатывают и + // профили — тогда новые ключи не принимаются до перезапуска набора. + res = mgr.Reload(cfg) + switch { + case handler == nil || cfg.Transport == nil: + case len(res.RestartNeeded) > 0: + log.Warn("reload: транспортные поля не вступили в силу, новые ключи начнут приниматься после перезапуска набора", + "restartNeeded", strings.Join(res.RestartNeeded, ", ")) + default: handler.SetAuth(transportTokens(cfg), cfg.Transport.AllowAnonymous, cfg.Transport.ClientNames) } - res = mgr.Reload(cfg) } if werr := writeReloadStatus(filepath.Join(dir, "reload.status"), res, nonce); werr != nil { log.Warn("reload.status не записан", "err", werr) diff --git a/cmd/mcprig/panel.go b/cmd/mcprig/panel.go index 03f30ac..f30c1e7 100644 --- a/cmd/mcprig/panel.go +++ b/cmd/mcprig/panel.go @@ -42,14 +42,23 @@ func panelFlags(fs *flag.FlagSet, panel *string, helpPanel string, creds *panelC // MCPRIG_PORT (9091 по умолчанию, как в deploy/mcprig.service). func panelBaseURL(panel string) string { if panel != "" { - return panel + return withScheme(panel) } if v := os.Getenv("MCPRIG_PANEL_URL"); v != "" { - return v + return withScheme(v) } return "http://127.0.0.1:" + envDefault("MCPRIG_PORT", "9091") } +// withScheme принимает адрес без схемы: «127.0.0.1:9091» — то, что человек +// копирует из `ss` или из браузера без http://. +func withScheme(v string) string { + if strings.Contains(v, "://") { + return v + } + return "http://" + v +} + // newPanelClient — клиент панели с cookie jar. Пароль задан — входит через // /api/login, и дальше ходит с сессией; пустой — рассчитывает на обратный // прокси, которому хватает panelHeaders. diff --git a/cmd/mcprig/panel_test.go b/cmd/mcprig/panel_test.go index 6dffa75..2bce3ed 100644 --- a/cmd/mcprig/panel_test.go +++ b/cmd/mcprig/panel_test.go @@ -8,6 +8,21 @@ import ( "testing" ) +// TestWithScheme: адрес без схемы — то, что человек копирует из `ss` или из +// браузера, — раньше падал на разборе URL до первого запроса. +func TestWithScheme(t *testing.T) { + cases := map[string]string{ + "127.0.0.1:9091": "http://127.0.0.1:9091", + "http://panel:9088": "http://panel:9088", + "https://panel.example": "https://panel.example", + } + for in, want := range cases { + if got := withScheme(in); got != want { + t.Fatalf("withScheme(%q) = %q, ждали %q", in, got, want) + } + } +} + // Вход в панель: пароль уходит JSON-ом в /api/login, дальше запросы несут // cookie, а --secret/--user — заголовки обратного прокси. func TestPanelLogin(t *testing.T) { diff --git a/cmd/mcprig/reload_test.go b/cmd/mcprig/reload_test.go index 15a416d..4a9110e 100644 --- a/cmd/mcprig/reload_test.go +++ b/cmd/mcprig/reload_test.go @@ -7,15 +7,21 @@ import ( "io" "log/slog" "net" + "net/http" + "net/http/httptest" "os" "os/exec" "path/filepath" + "slices" + "strings" "syscall" "testing" "time" "github.com/akrhin/mcprig/internal/config" + "github.com/akrhin/mcprig/internal/httplisten" "github.com/akrhin/mcprig/internal/mcpserver" + "github.com/akrhin/mcprig/internal/stats" ) func quietLog() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } @@ -176,3 +182,98 @@ func TestServeReloadsOnSIGHUP(t *testing.T) { time.Sleep(50 * time.Millisecond) } } + +// ─── ключи и профили — одно поколение ──────────────────────────────────────── + +// reloadServe — набор и его живой слушатель из файла: ключи и профили +// проверяются настоящим запросом, как у serve. +type reloadServe struct { + path string + mgr *mcpserver.Manager + h *httplisten.Server +} + +func newReloadServe(t *testing.T, body string) *reloadServe { + t.Helper() + path := filepath.Join(t.TempDir(), "servers.json") + writeServers(t, path, body) + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + mgr := mcpserver.New(cfg, "test", nil) + t.Cleanup(func() { _ = mgr.Close() }) + h, err := httplisten.New(cfg, mgr.Server(), quietLog(), nil) + if err != nil { + t.Fatalf("httplisten.New: %v", err) + } + return &reloadServe{path: path, mgr: mgr, h: h} +} + +// post гоняет один MCP-запрос через живой слушатель. +func (s *reloadServe) post(t *testing.T, auth, body string) (int, string) { + t.Helper() + r := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) + r.Host = "127.0.0.1" + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Accept", "application/json, text/event-stream") + if auth != "" { + r.Header.Set("Authorization", "Bearer "+auth) + } + w := httptest.NewRecorder() + s.h.ServeHTTP(w, r) + return w.Code, w.Body.String() +} + +const reloadInit = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":` + + `{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}` + +// Транспортные поля отвергнуты — профили откачены вместе с ними, и новый ключ +// не принимается слушателем: иначе он прошёл бы без профиля по чужой таблице. +func TestReloadRejectsKeyWhileProfilesRolledBack(t *testing.T) { + const oldKey, newKey = "old-key-0123456789", "new-key-0123456789" + s := newReloadServe(t, `{"servers": [{"name": "alpha", "command": ["downstream"], "enabled": true}], + "transport": {"type": "http", "authTokens": ["`+oldKey+`"], "allowedHosts": ["127.0.0.1"]}}`) + + writeServers(t, s.path, `{"servers": [{"name": "alpha", "command": ["downstream"], "enabled": true}], + "transport": {"type": "http", "authTokens": ["`+oldKey+`", "`+newKey+`"], + "allowedHosts": ["127.0.0.1", "localhost"], + "keyProfiles": {"`+stats.Fingerprint(newKey)+`": "strict"}}, + "profiles": {"strict": {"deny": ["alpha/*"]}}}`) + res := reloadOnce(s.mgr, s.h, s.path, quietLog()) + if !slices.Contains(res.RestartNeeded, "allowedHosts") { + t.Fatalf("restartNeeded = %v, ждали allowedHosts", res.RestartNeeded) + } + if code, body := s.post(t, newKey, reloadInit); code != http.StatusUnauthorized { + t.Fatalf("новый ключ принят без профиля: %d %s", code, body) + } + if code, body := s.post(t, oldKey, reloadInit); code != http.StatusOK { + t.Fatalf("старый ключ перестал работать: %d %s", code, body) + } +} + +// Без транспортных расхождений новый ключ принимается сразу и сразу под своим +// профилем: токен и профиль едут одним поколением. +func TestReloadAppliesKeyAndProfileTogether(t *testing.T) { + const oldKey, newKey = "old-key-0123456789", "new-key-0123456789" + s := newReloadServe(t, `{"servers": [{"name": "alpha", "command": ["downstream"], "enabled": true}], + "transport": {"type": "http", "authTokens": ["`+oldKey+`"], "allowedHosts": ["127.0.0.1"]}}`) + + writeServers(t, s.path, `{"servers": [{"name": "alpha", "command": ["downstream"], "enabled": true}], + "transport": {"type": "http", "authTokens": ["`+oldKey+`", "`+newKey+`"], + "allowedHosts": ["127.0.0.1"], + "keyProfiles": {"`+stats.Fingerprint(newKey)+`": "strict"}}, + "profiles": {"strict": {"deny": ["alpha/*"]}}}`) + if res := reloadOnce(s.mgr, s.h, s.path, quietLog()); len(res.RestartNeeded) != 0 || res.Err != "" { + t.Fatalf("reload: %+v", res) + } + if code, body := s.post(t, newKey, reloadInit); code != http.StatusOK { + t.Fatalf("новый ключ не принят сразу: %d %s", code, body) + } + callBody := `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":` + + `{"name":"invoke_command","arguments":{"server":"alpha","command_name":"echo"}}}` + code, body := s.post(t, newKey, callBody) + if code != http.StatusOK || !strings.Contains(body, "Blocked by mcprig policy") { + t.Fatalf("профиль нового ключа не действует: %d %s", code, body) + } +} diff --git a/cmd/testmcp/main.go b/cmd/testmcp/main.go index 98d2745..7a805e3 100644 --- a/cmd/testmcp/main.go +++ b/cmd/testmcp/main.go @@ -5,6 +5,7 @@ package main import ( "context" "errors" + "fmt" "log" "os" @@ -16,6 +17,12 @@ type echoIn struct { } func main() { + // Панель показывает в диалоге лога вывод процесса сервера: тест проверяет + // именно его, поэтому строка в stderr включается переменной, а не всегда. + if msg := os.Getenv("TESTMCP_STDERR"); msg != "" { + fmt.Fprintln(os.Stderr, msg) + } + server := mcp.NewServer(&mcp.Implementation{Name: "testmcp", Version: "0.0.1"}, nil) mcp.AddTool(server, &mcp.Tool{Name: "echo", Description: "Echo the given text back."}, diff --git a/codemap.md b/codemap.md index 9865c76..9782506 100644 --- a/codemap.md +++ b/codemap.md @@ -29,7 +29,7 @@ Two processes come out of one `main`: tool descriptor is denied, sandbox failure denies, unreadable lock file denies (`internal/toollock/codemap.md`, `internal/sandbox/codemap.md`). - Panel and set never share memory — reload is a file plus a nonce plus a signal - (`internal/manager`, `runtime.go:40-41`). + (`internal/manager`, `runtime.go:40-42`). - No build step for the UI: the panel is hand-written JS/CSS embedded with `go:embed` (`web/codemap.md`). @@ -42,7 +42,7 @@ Two processes come out of one `main`: | `web/` | Panel front end (SPA, no framework) plus `embed.go` that carries it in the binary | [View Map](web/codemap.md) | | `e2e/` | End-to-end suites: lifecycle (panel + set + stdio downstream), contract against a live BASE, proxy, keys, stdio | — | | `deploy/` | systemd units (`mcprig.service`, `mcprig-set@.service`, `mcprig-warm.{service,timer}`), `docker-compose.yml`, example sets | — | -| `scripts/` | Gates and stands: `contract-e2e.sh`, `sandbox-e2e.sh`, `dev-real-set.sh`, `docs-check.sh`, `release-notes.sh` | — | +| `scripts/` | Gates and stands: `contract-e2e.sh`, `sandbox-e2e.sh`, `dev-real-set.sh`, `docs-check.sh`, `release-notes.sh`; `acceptance/panel.cjs` is the 37-step Playwright walk of the panel (`scripts/acceptance/README.md`, `ACC_DAP` points at any stdio MCP server) | — | | `docs/` | Documentation: `docs/en/` (canon), `docs/ru/` (mirror), `docs/history/` (plans, audits, reference contract), `docs/diagrams/` | — | | `design/` | Logos, tokens, UI screenshots; not part of the build | — | @@ -68,8 +68,8 @@ spawns `mcprig serve`, and reloads it through `reload.request` + SIGHUP. `go.opentelemetry.io/otel`, `golang.org/x/time/rate`. - State on disk: config `$XDG_CONFIG_HOME/mcprig/servers.json`; data `$XDG_STATE_HOME/mcprig` (override `MCPRIG_DATA_DIR`) — `registry.json`, - `sets//{servers.json,oauth.json,tools.lock.json,logs}`, - `tool-out/` (`cmd/mcprig/main.go:564-574`, `internal/manager/api.go:98-107`). + `sets//{servers.json,oauth.json,tools.lock.json,logs,serverlogs/}`, + `tool-out/` (`cmd/mcprig/main.go:618-630,636-641`, `internal/manager/api.go:98-107`). - Diagram sources live as `.json` beside generated `.html`/`.png` in `docs/diagrams/`; only the `.json` is edited (`AGENTS.md`). diff --git a/design/ui/archive/panel-0.6.x.png b/design/ui/archive/panel-0.6.x.png new file mode 100644 index 0000000..214c2c9 Binary files /dev/null and b/design/ui/archive/panel-0.6.x.png differ diff --git a/design/ui/note.md b/design/ui/note.md index 5b9ce18..c453641 100644 --- a/design/ui/note.md +++ b/design/ui/note.md @@ -8,7 +8,7 @@ | --- | --- | | `index.html` | главный экран: топбар, рейл наборов, KPI, таблица наборов, таблица вызовов, правая колонка, статус-строка | | `states.html` | три состояния: пусто, набор остановлен, плотная таблица 40 строк | -| `panel.png` | скриншот настоящей панели (`web/`), тёмная тема, 1280×673 при ×2: набор `quasar` со страницами-пилюлями, Import / Export, Keys, Prompt и Delete set, метка ключа `hermes`, KPI на настоящих вызовах, таблица серверов; прежний снимок — `archive/panel-0.5.1.png`, макет при 1440×1000 — `archive/panel-0.4.x.png` | +| `panel.png` | скриншот настоящей панели (`web/`), тёмная тема, 1280×541 при ×2: три набора на своих портах, открытый `dev` с четырьмя healthy-серверами и 16 инструментами, шесть плиток состояния, сводка `32 CALLS · 7 DAYS | 0.0% ERROR RATE`; прежние снимки — `archive/panel-0.6.x.png`, `archive/panel-0.5.1.png`, макет при 1440×1000 — `archive/panel-0.4.x.png` | | `states.png` | скриншот `states.html` | Что взято в реализацию этапа 5: diff --git a/design/ui/panel-pages/fix-host-1280-dark-en.png b/design/ui/panel-pages/fix-host-1280-dark-en.png new file mode 100644 index 0000000..aaf1922 Binary files /dev/null and b/design/ui/panel-pages/fix-host-1280-dark-en.png differ diff --git a/design/ui/panel-pages/fix-host-1280-dark-ru.png b/design/ui/panel-pages/fix-host-1280-dark-ru.png new file mode 100644 index 0000000..4a2cc02 Binary files /dev/null and b/design/ui/panel-pages/fix-host-1280-dark-ru.png differ diff --git a/design/ui/panel-pages/fix-host-calls-375-dark-en.png b/design/ui/panel-pages/fix-host-calls-375-dark-en.png new file mode 100644 index 0000000..70a9294 Binary files /dev/null and b/design/ui/panel-pages/fix-host-calls-375-dark-en.png differ diff --git a/design/ui/panel-pages/fix-host-calls-375-win98-ru.png b/design/ui/panel-pages/fix-host-calls-375-win98-ru.png new file mode 100644 index 0000000..4743ead Binary files /dev/null and b/design/ui/panel-pages/fix-host-calls-375-win98-ru.png differ diff --git a/design/ui/panel-pages/fix-host-calls-768-dark-en.png b/design/ui/panel-pages/fix-host-calls-768-dark-en.png new file mode 100644 index 0000000..b686e64 Binary files /dev/null and b/design/ui/panel-pages/fix-host-calls-768-dark-en.png differ diff --git a/design/ui/panel-pages/fix-sets-1280-dark-en.png b/design/ui/panel-pages/fix-sets-1280-dark-en.png new file mode 100644 index 0000000..f352722 Binary files /dev/null and b/design/ui/panel-pages/fix-sets-1280-dark-en.png differ diff --git a/design/ui/panel-pages/fix-sets-1280-dark-ru.png b/design/ui/panel-pages/fix-sets-1280-dark-ru.png new file mode 100644 index 0000000..ae7dcd7 Binary files /dev/null and b/design/ui/panel-pages/fix-sets-1280-dark-ru.png differ diff --git a/design/ui/panel-pages/fix-sets-1280-win98-ru.png b/design/ui/panel-pages/fix-sets-1280-win98-ru.png new file mode 100644 index 0000000..237bf8b Binary files /dev/null and b/design/ui/panel-pages/fix-sets-1280-win98-ru.png differ diff --git a/design/ui/panel-pages/fix-sets-375-dark-en.png b/design/ui/panel-pages/fix-sets-375-dark-en.png new file mode 100644 index 0000000..217ed72 Binary files /dev/null and b/design/ui/panel-pages/fix-sets-375-dark-en.png differ diff --git a/design/ui/panel-pages/nav-host-375-dark-en.png b/design/ui/panel-pages/nav-host-375-dark-en.png new file mode 100644 index 0000000..ff28fe3 Binary files /dev/null and b/design/ui/panel-pages/nav-host-375-dark-en.png differ diff --git a/design/ui/panel-pages/nav-set-1280-dark-en.png b/design/ui/panel-pages/nav-set-1280-dark-en.png new file mode 100644 index 0000000..252d718 Binary files /dev/null and b/design/ui/panel-pages/nav-set-1280-dark-en.png differ diff --git a/design/ui/panel-pages/nav-sets-1280-dark-en.png b/design/ui/panel-pages/nav-sets-1280-dark-en.png new file mode 100644 index 0000000..9fcdf70 Binary files /dev/null and b/design/ui/panel-pages/nav-sets-1280-dark-en.png differ diff --git a/design/ui/panel-pages/polish-host-375-dark-en.png b/design/ui/panel-pages/polish-host-375-dark-en.png new file mode 100644 index 0000000..0300820 Binary files /dev/null and b/design/ui/panel-pages/polish-host-375-dark-en.png differ diff --git a/design/ui/panel-pages/polish-set-calls-375-dark-en.png b/design/ui/panel-pages/polish-set-calls-375-dark-en.png new file mode 100644 index 0000000..07009b8 Binary files /dev/null and b/design/ui/panel-pages/polish-set-calls-375-dark-en.png differ diff --git a/design/ui/panel-pages/polish-sets-1280-dark-en.png b/design/ui/panel-pages/polish-sets-1280-dark-en.png new file mode 100644 index 0000000..0da0ab9 Binary files /dev/null and b/design/ui/panel-pages/polish-sets-1280-dark-en.png differ diff --git a/design/ui/panel-pages/polish-sets-375-dark-en.png b/design/ui/panel-pages/polish-sets-375-dark-en.png new file mode 100644 index 0000000..b841ad3 Binary files /dev/null and b/design/ui/panel-pages/polish-sets-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-calls-375-dark-en.png b/design/ui/panel-pages/rev-after-calls-375-dark-en.png new file mode 100644 index 0000000..b5a1282 Binary files /dev/null and b/design/ui/panel-pages/rev-after-calls-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-host-1280-dark-en.png b/design/ui/panel-pages/rev-after-host-1280-dark-en.png new file mode 100644 index 0000000..dc54169 Binary files /dev/null and b/design/ui/panel-pages/rev-after-host-1280-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-host-375-dark-en.png b/design/ui/panel-pages/rev-after-host-375-dark-en.png new file mode 100644 index 0000000..cac7fdc Binary files /dev/null and b/design/ui/panel-pages/rev-after-host-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-light-sets-375.png b/design/ui/panel-pages/rev-after-light-sets-375.png new file mode 100644 index 0000000..c3158a7 Binary files /dev/null and b/design/ui/panel-pages/rev-after-light-sets-375.png differ diff --git a/design/ui/panel-pages/rev-after-logs-375-dark-en.png b/design/ui/panel-pages/rev-after-logs-375-dark-en.png new file mode 100644 index 0000000..09f532f Binary files /dev/null and b/design/ui/panel-pages/rev-after-logs-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-nord-host-375.png b/design/ui/panel-pages/rev-after-nord-host-375.png new file mode 100644 index 0000000..c0332a6 Binary files /dev/null and b/design/ui/panel-pages/rev-after-nord-host-375.png differ diff --git a/design/ui/panel-pages/rev-after-set-375-dark-ru.png b/design/ui/panel-pages/rev-after-set-375-dark-ru.png new file mode 100644 index 0000000..a0f7357 Binary files /dev/null and b/design/ui/panel-pages/rev-after-set-375-dark-ru.png differ diff --git a/design/ui/panel-pages/rev-after-sets-375-dark-en.png b/design/ui/panel-pages/rev-after-sets-375-dark-en.png new file mode 100644 index 0000000..1152a30 Binary files /dev/null and b/design/ui/panel-pages/rev-after-sets-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-stats-1280-dark-en.png b/design/ui/panel-pages/rev-after-stats-1280-dark-en.png new file mode 100644 index 0000000..820f761 Binary files /dev/null and b/design/ui/panel-pages/rev-after-stats-1280-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-stats-375-dark-en.png b/design/ui/panel-pages/rev-after-stats-375-dark-en.png new file mode 100644 index 0000000..0cc7ee8 Binary files /dev/null and b/design/ui/panel-pages/rev-after-stats-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-after-win98-set-1280.png b/design/ui/panel-pages/rev-after-win98-set-1280.png new file mode 100644 index 0000000..0fdbf7e Binary files /dev/null and b/design/ui/panel-pages/rev-after-win98-set-1280.png differ diff --git a/design/ui/panel-pages/rev-after-win98-set-375.png b/design/ui/panel-pages/rev-after-win98-set-375.png new file mode 100644 index 0000000..38285ae Binary files /dev/null and b/design/ui/panel-pages/rev-after-win98-set-375.png differ diff --git a/design/ui/panel-pages/rev-before-calls-375-dark-en.png b/design/ui/panel-pages/rev-before-calls-375-dark-en.png new file mode 100644 index 0000000..ffa2d41 Binary files /dev/null and b/design/ui/panel-pages/rev-before-calls-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-host-1280-dark-en.png b/design/ui/panel-pages/rev-before-host-1280-dark-en.png new file mode 100644 index 0000000..1f789c7 Binary files /dev/null and b/design/ui/panel-pages/rev-before-host-1280-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-host-375-dark-en.png b/design/ui/panel-pages/rev-before-host-375-dark-en.png new file mode 100644 index 0000000..d3d8b53 Binary files /dev/null and b/design/ui/panel-pages/rev-before-host-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-logs-375-dark-en.png b/design/ui/panel-pages/rev-before-logs-375-dark-en.png new file mode 100644 index 0000000..1cf00e6 Binary files /dev/null and b/design/ui/panel-pages/rev-before-logs-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-nord-host-375.png b/design/ui/panel-pages/rev-before-nord-host-375.png new file mode 100644 index 0000000..9ad736b Binary files /dev/null and b/design/ui/panel-pages/rev-before-nord-host-375.png differ diff --git a/design/ui/panel-pages/rev-before-servers-1280-dark-en.png b/design/ui/panel-pages/rev-before-servers-1280-dark-en.png new file mode 100644 index 0000000..9b4d4fd Binary files /dev/null and b/design/ui/panel-pages/rev-before-servers-1280-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-set-375-dark-en.png b/design/ui/panel-pages/rev-before-set-375-dark-en.png new file mode 100644 index 0000000..fb98bfd Binary files /dev/null and b/design/ui/panel-pages/rev-before-set-375-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-stats-1280-dark-en.png b/design/ui/panel-pages/rev-before-stats-1280-dark-en.png new file mode 100644 index 0000000..92f0ef5 Binary files /dev/null and b/design/ui/panel-pages/rev-before-stats-1280-dark-en.png differ diff --git a/design/ui/panel-pages/rev-before-win98-set-375.png b/design/ui/panel-pages/rev-before-win98-set-375.png new file mode 100644 index 0000000..82e20f4 Binary files /dev/null and b/design/ui/panel-pages/rev-before-win98-set-375.png differ diff --git a/design/ui/panel-pages/tap-calls-375-dark-en.png b/design/ui/panel-pages/tap-calls-375-dark-en.png new file mode 100644 index 0000000..47c75bc Binary files /dev/null and b/design/ui/panel-pages/tap-calls-375-dark-en.png differ diff --git a/design/ui/panel-pages/tap-calls-375-light-en.png b/design/ui/panel-pages/tap-calls-375-light-en.png new file mode 100644 index 0000000..49374a6 Binary files /dev/null and b/design/ui/panel-pages/tap-calls-375-light-en.png differ diff --git a/design/ui/panel-pages/tap-keys-375-dark-en.png b/design/ui/panel-pages/tap-keys-375-dark-en.png new file mode 100644 index 0000000..3732263 Binary files /dev/null and b/design/ui/panel-pages/tap-keys-375-dark-en.png differ diff --git a/design/ui/panel-pages/tap-servers-1280-dark-en.png b/design/ui/panel-pages/tap-servers-1280-dark-en.png new file mode 100644 index 0000000..6d9aa33 Binary files /dev/null and b/design/ui/panel-pages/tap-servers-1280-dark-en.png differ diff --git a/design/ui/panel-pages/tap-vars-1280-dark-en.png b/design/ui/panel-pages/tap-vars-1280-dark-en.png new file mode 100644 index 0000000..c55ee31 Binary files /dev/null and b/design/ui/panel-pages/tap-vars-1280-dark-en.png differ diff --git a/design/ui/panel.png b/design/ui/panel.png index 214c2c9..31098cc 100644 Binary files a/design/ui/panel.png and b/design/ui/panel.png differ diff --git a/docs/CURRENT-GOAL.md b/docs/CURRENT-GOAL.md index bedccad..058a9cf 100644 --- a/docs/CURRENT-GOAL.md +++ b/docs/CURRENT-GOAL.md @@ -325,13 +325,9 @@ admin-сессией, тонкий CLI, медленный первый стар ## Долги -- **Кнопка «Показать ключ» в панели убрана, а не починена.** Панель принципиально - не хранит полный ключ набора — показывает только префикс, поэтому показывать - нечего. Вернуться к вопросу, если понадобится: либо хранить полный ключ при - создании и отдавать его один раз явным действием, либо оставить как есть и - не обещать в интерфейсе. Ссылка на макет — `design/ui/note.md`. -- **Приёмник OAuth слушает только loopback.** На браузер с другого устройства - редирект на `127.0.0.1:8947` не возвращается — нужен проброс порта - (`ssh -L 8947:127.0.0.1:8947`). Если это окажется неудобным, следующий шаг — - явный адрес приёмника в настройках набора; просто разрешать не-loopback нельзя: - код на приёмнике подменит любой в локальной сети. +Все долги — в едином файле +[`docs/debts.md`](debts.md): находки полного аудита 2026-11-18 и независимого +свежего аудита того же дня (совпали), закрытые пункты и решения (кнопка +«Показать ключ», loopback-приёмник OAuth). До 0.6.6 закрыть D1–D13 тремя +волнами: безопасность и границы (D10, D12, D11, D13), память и корректность +(D1, D3, D5, D2, D4), процесс и качество (D6, D7, D8); приоритеты — в файле. diff --git a/docs/debts.md b/docs/debts.md new file mode 100644 index 0000000..c8acea6 --- /dev/null +++ b/docs/debts.md @@ -0,0 +1,104 @@ +# Долги mcprig + +Единый файл долгов: каждая находка аудита живёт здесь, а не в чате и не в +CURRENT-GOAL. Строка закрывается коммитом и получает ссылку на него; статус +`решение` — когда выяснилось, что менять не нужно. + +Ревизия 2026-11-18, источники: полный аудит +[`history/audits/2026-11-18-full-repo-audit.md`](history/audits/2026-11-18-full-repo-audit.md), +независимый свежий аудит того же дня (чтением, ~54 тыс. строк; находки совпали) +и отдельный аудит безопасности по скиллу `security-audit` (прогон +`mcprig-2026-11-18-1416`, 49 юнитов покрытия, только чтение исходников — отсюда +D10–D13). + +## Открытые + +Нет. D1–D13 закрыты или оказались решениями; ниже — чем именно и на каком +коммите. + +## Закрытые + +- **D13 · Needs validation · имя тега в тексте shell** — `dc95bc6`: тег + приходит через `env:` (`TAG`, `REF`) и читается как переменная, checkout + релиза идёт с `persist-credentials: false`. Остаток — не код: кто вправе + пушить теги `v*` и запускать dispatch, решают protection rules на хостинге, + из репозитория этого не видно. Проверено 2026-11-18 по API обоих хостов: + `tag_protections` и `branch_protections` в Gitea — `[]`, `rulesets` на + GitHub — `[]`, то есть **любой, у кого есть право записи, может запушить + `v*` и запустить release**. Правило поставлено 2026-11-18 на обоих хостах: + ruleset `protect release tags` (id 27553037, `creation`/`update`/`deletion` + для `refs/tags/v*`, обход — только роль admin) и tag protection Gitea + (id 1, `v*`, whitelist `sintez`). Репозиторий это не проверяет — состояние + читается по API хоста. +- **D7 · Nice · кэш статистики обнулялся целиком** — `c5d32f3`: переполнение + `cacheMax = 4096` вытесняет старейшую четверть по `mtime` файла + (`TestCacheEvictsOldestQuarter`). +- **D11 · Should · `/stats` отдавал любому ключу чужие данные** — `7e9c0c2`: + полный снимок получает только служебный вызов панели + (`X-MCPRig-Caller: panel`), ключ набора — редакцию с метками `(аноним)` и + пустыми текстами ошибок (`TestStatsRedactedPerCaller`). Документация + приведена в соответствие: `docs/en|ru/architecture.md`, `docs/en|ru/panel.md`. +- **D10 · Should · reload расщеплял поколения токенов и профилей** — `0dfb26d`: + `Reload` первым, `SetAuth` только при пустом `RestartNeeded`, иначе одна + строка `Warn` (`TestReloadRejectsKeyWhileProfilesRolledBack`, + `TestReloadAppliesKeyAndProfileTogether`). +- **D12 · Should · текст ошибки апстрима шёл мимо маскировки** — `0dfb26d`: + `err` чистится после решения о повторе, `recordMeta` маскирует мета-ошибку + объединением секретов всех серверов (`TestInvokeCommandMasksSecretInProtocolError`, + `TestMetaStatsMaskUpstreamSecret`). +- **D1 · Should · карта `refreshAt` не удаляла записи** — `0dfb26d`: + `sweepRefresh` выметает метки старше `catalogRefreshEvery` каждые 1024 + записи или при потолке 4096 (`TestMayRefreshSweepsStaleMarks`). +- **D2 · Should · кэш здоровья вечно ждал после паники пробы** — `d9e1198`: + `loadGuarded` с `recover`, один `Warn`, `wait` закрыт, вид пуст + (`TestHealthCachePanicDoesNotHang`). +- **D3 · Should · webhook-состояние не чистилось при удалении набора** — + `d9e1198`: `notifier.clearSet(id)` рядом с `rt.Forget(id)` + (`TestNotifyStateClearedOnDelete`). +- **D4 · Should · маскирование только по имени поля** — `d9e1198`: фильтр имени + снят, маскируется любое значение `env`/`headers` от 8 байт, `Bearer ` + снимается (`TestSecretsMasksEveryValue`). +- **D5 · Should · неудачные входы чистились только при >1024** — `d9e1198`: + просроченные окна убираются при каждой записи, сверх `loginFailsMax = 1024` + вытесняется запись с самым ранним окном (`TestLoginFailsMapBounded`, + `TestLoginFailsDropsExpired`). +- **D6 · Should · приёмка панели не гонялась в CI** — `04a607a`: `ACC_DAP` + стал необязательным (26 шагов без stdio-сервера, 11 пропускаются с явной + строкой), job `acceptance` в `.github/workflows/ci.yml` собирает бинарь, + поднимает панель на свободном порту 9100–9189 и гоняет приёмку, бюджет + 8 минут. Локальный прогон блока: `total 26, skipped 11, failed 0`. + На реальном раннере проверено: прогон + [44316150632](https://github.com/akrhin/mcprig/actions/runs/44316150632), + job `acceptance` — success, 13:40:49 → 13:46:10Z (5 мин 21 с из 8): + `playwright install --with-deps chromium`, сборка бинаря, панель, 26 шагов, + `failed: 0`. + +- README застыл на v0.6.3 (`README.md:34`, `README.ru.md:34`) — заменено на + `releases/latest` в `e469bd1`. + +## Решения + +- **Метка «— запуск —» ставится на старт процесса, менять нечего (бывший D8).** + Проверено по коду на `840779c`: `Writer` вызывается ровно в одном месте — + `internal/downstream/connect.go:181`, внутри stdio-ветки, которая собирает + `exec.Command` для нового процесса сервера; живая сессия (`conn.sess`) до + `Writer` не доходит. Файл хвоста живёт дольше процесса, поэтому метка на + каждое переподключение — это метка на каждый новый процесс, как и требуется. + Забить 256 КиБ метками можно только потоком падений, и тогда хвост обрезается + вместе с ними. + +- **Кнопка «Показать ключ» в панели убрана, а не починена.** Панель принципиально + не хранит полный ключ набора — показывает только префикс, поэтому показывать + нечего. Вернуться к вопросу, если понадобится: либо хранить полный ключ при + создании и отдавать его один раз явным действием, либо оставить как есть и + не обещать в интерфейсе. Ссылка на макет — `design/ui/note.md`. +- **tool-out: 410 уже отдаётся, менять нечего (бывший D9).** Проверено по коду + на `2d9a561`: просроченная выгрузка отвечает `410` («полный ответ больше не + хранится»), отсутствующая или чужая — `404` с одинаковым текстом, чтобы не + подтверждать существование файла. Расхождение — только в паре «файл умер и + имя забыто», и это осознанно: имя — capability внутри клиента. +- **Приёмник OAuth слушает только loopback.** На браузер с другого устройства + редирект на `127.0.0.1:8947` не возвращается — нужен проброс порта + (`ssh -L 8947:127.0.0.1:8947`). Если это окажется неудобным, следующий шаг — + явный адрес приёмника в настройках набора; просто разрешать не-loopback нельзя: + код на приёмнике подменит любой в локальной сети. diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 401dc05..b2d1947 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -79,7 +79,7 @@ What one reload applies: | `permissions`, `enabled`, `description`, `tags` | updated in place, session and tool cache kept | | untouched server | same record, same session, same cache | | set `rateLimit`, `profiles` | applied in place; `requestTimeout` and `healthMonitor` are constants the manager writes and never change | -| `authToken`, `authTokens`, `allowAnonymous`, `clientNames`, `keyProfiles` | applied live: on reload the panel hands the new token list and the set's openness to the listener (`SetAuth`), and a key's profile is resolved per request — a key rotation or a switch to an open set needs no restart | +| `authToken`, `authTokens`, `allowAnonymous`, `clientNames`, `keyProfiles` | applied live: on reload the panel hands the new token list and the set's openness to the listener (`SetAuth`), and a key's profile is resolved per request — a key rotation or a switch to an open set needs no restart. When the same reload lists a transport field in `restartNeeded`, the listener keeps its previous tokens: profiles and tokens are one generation, so a new key never arrives without its profile and starts being accepted only after the set restarts | | `host`, `port`, `path`, `type`, `allowedHosts`, a `transport` block that appears or disappears | listed in `restartNeeded`, the old values stay in force | `keyProfiles` is applied live: the manager reads it per request, unlike the @@ -184,9 +184,12 @@ Each set serves one stateless endpoint: matched; - 4 MiB request body cap; - no read timeout (an SSE stream must not be cut), 60 s idle timeout; -- `GET /healthz` public, `GET /stats` protected by the same bearer; an open set - has no key, so an anonymous `GET /stats` is answered with a redacted snapshot — - no client labels, no upstream error text ([panel.md](panel.md#health)). +- `GET /healthz` public, `GET /stats` protected by the same bearer. The full + snapshot — client labels, upstream error texts — goes to the panel's own + service call only (`X-MCPRig-Caller: panel`, sent by the manager that polls a + set); every key gets the redacted one: counters and latencies stay, client + labels become `(аноним)` and error texts are dropped + ([panel.md](panel.md#health)). ## OAuth diff --git a/docs/en/dev/development.md b/docs/en/dev/development.md index 2aafbff..f4cda87 100644 --- a/docs/en/dev/development.md +++ b/docs/en/dev/development.md @@ -76,6 +76,28 @@ against this binary (`E2E_STRICT=1`). The checks are derived from An empty `E2E_BASE` skips the suite; with `E2E_STRICT=1` it exits non-zero so a 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, +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 +panel must be empty and passwordless: + +```bash +MCPRIG_DATA_DIR=$(mktemp -d) MCPRIG_AUTH=off MCPRIG_PORT=9131 ./mcprig panel & +ACC_BASE=http://127.0.0.1:9131 ACC_DAP=/path/to/stdio-mcp \ + node scripts/acceptance/panel.cjs +``` + +A failed step prints the browser state next to it, so a timing flake is told +apart from a defect. CI runs the 26 steps that need no stdio server: the +`acceptance` job in `.github/workflows/ci.yml` builds the binary, starts the +panel on a free port of 9100–9189 and waits for `/healthz`. Who changed the +panel's routes or forms without updating the script sees a red job rather than +a stale green one. + ## Live stand `scripts/dev-real-set.sh` builds the binary, starts a panel with auth off, adds diff --git a/docs/en/panel.md b/docs/en/panel.md index 69ddd8e..b700f78 100644 --- a/docs/en/panel.md +++ b/docs/en/panel.md @@ -19,7 +19,8 @@ CSP: no inline scripts or styles. | top bar | breadcrumbs `mcprig / `, the MCP endpoint of the open set with a copy button, the appearance menu — **theme** (Default or Windows 98) and the colour scheme of that theme — the interface language, and a static `admin` chip that is hidden on narrow screens | | left rail | all sets as name plus `:port · state` and a state dot; **+ New set** | | pages | **Overview** at `#/`, **Sets** at `#/sets`, **Statistics** at `#/stats/`, **All servers** at `#/servers` and **Variables** at `#/vars`, as pills at the top of the content; a set keeps `#/set/` and each of its tabs has its own address, so a reload, a back button and a shared link all land where they should | -| host overview | what the daemon is serving right now: sets running and sets stopped, servers ok, not checked and failing, tools waiting for approval, calls and error rate over the last 7 days, and the size and retention of `/tool-out` as a dash — the API has no field for it, so the panel says so instead of guessing. Under the tiles: every set by last call with its state and the daemon's reason, and the latest calls of all sets; a row opens that set | +| sets page | the list of sets at `#/sets`: name with `:port`, state, the number of servers and of keys; a row opens the set. An address that names no set — the bare `#/sets` or a route the panel does not know — lands here, not on the set that was open last; deleting the open set lands here too, not on a neighbour | +| host overview | what the daemon is serving right now: sets running and sets stopped, servers ok, not checked and failing, tools waiting for approval, calls and error rate over the last 7 days, and the size and retention of `/tool-out` as a dash — the API has no field for it, so the panel says so instead of guessing. Under the tiles: every set by last call with its state and the daemon's reason, and the latest calls of all sets; a row opens that set. On a phone each call reads as a card — time and status, set and server, tool and duration — while the sets list keeps its columns | | set head | name, port chip, state badge, **Import / Export**, **Prompt**, **Restart**, **Start/Stop**, and the red **Delete set** that removes the set and its directory; under them the key prefix with its `key:` label, the number of servers and tools plus the `list_commands` weight (bytes, tokens) | | 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** | @@ -27,6 +28,7 @@ CSP: no inline scripts or styles. | 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 | | 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 | | variables page | every `${NAME}` your servers reference with whether a value is set and where it comes from, a form that writes a value, and the **×** that forgets it | | logs tab | the log tail of the set with **refresh**; it is a tab, not a drawer, so the log keeps its place in the address `#/set//logs` | | footer | the status bar: `M servers` of the registry, `mcprig ` and the time it was updated. The sets and how many are running are the line at the bottom of the left rail — `N sets · M running` | @@ -41,6 +43,10 @@ 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 browser title names what is open: `mcprig — Overview`, `mcprig — Sets` and +the like for other pages, `mcprig — set ` on a set, and with ` · ` +when a tab other than **Overview** is open. + Everything on the page comes from the panel API below plus `GET /stats` of the running sets. Nothing else is stored in the browser but the chosen theme, its colour scheme and the interface language. @@ -88,10 +94,19 @@ does not validate them itself — it shows what the backend answers, including `тег untrusted требует sandbox: сервер без изоляции не стартует`. Each server row has a **Log** button: it opens a drawer with the set's log -filtered by that server's name — a server has no log file of its own. The -drawer reads `GET /api/sets//servers//logs?lines=200` and prints the -lines as text; a name that never appears in the log shows `log is empty`, and a -failed request keeps the lines already shown and reports the reason above them. +filtered by that server's name plus the tail of the server process's own stderr +(`sets//serverlogs/.log`). The tail survives a stop so the trace of a +crash stays readable, and it is cleared on the next start of the set; an automatic +restart after a crash appends to the same file under a new marker instead, so the +reason the server died is not wiped a second after it died. The drawer +reads `GET /api/sets//servers//logs?lines=200` and prints the lines as +text; a server that has neither shows `log is empty`, and a failed request keeps +the lines already shown and reports the reason above them. Every start writes a +`— запуск —` marker first, so a restart after a crash is told apart from +the first start; when the tail exists but cannot be read, the answer carries `error` +and the drawer prints it instead of pretending the server was silent. The set +lines come first and the process tail after them, so the two are not one merged +timeline; a line that names both the server and the access log appears twice. The **Tools** button of a row switches to the **Tools** tab with that server picked in its **Server** filter @@ -299,13 +314,13 @@ shipped unit, the panel's stdout in a foreground run. | `GET /` | panel (redirects to `/login` when auth is on and there is no session) | | `GET /login`, `POST /api/login`, `POST /api/logout` | session login | | `GET /api/state` | servers, sets, `firstPort` and `version` of the running binary (the footer prints it) — the first paint. A set's `keyMark` is the label its primary key carries in the statistics: the key's label when it has one, otherwise `key:`; empty for an open set | -| `GET /api/sets`, `POST /api/sets` | list and create sets; a new closed set returns its token once in the `201` body | +| `GET /api/sets`, `POST /api/sets` | list and create sets; a new closed set returns its token once in the `201` body. A set id is lowercase latin letters, digits, hyphen and underscore (`my-lab`); a name outside the pattern is `400` with that rule in the message — the backend no longer renames it silently | | `PUT /api/sets/`, `DELETE /api/sets/` | update and delete (stops it). The edit is written before it is applied, so a failed apply is never a 500: a restart that did not come back is `failed` (`{"":""}`) next to the set view, and a process that refused a reload reports it in the view's `reloadError`, so the panel does not show a saved edit as lost. A change of `port`, or a new `${VAR}` brought by a new server, restarts the set; `open` reaches the live listener by reload. A `token` in the body replaces the primary key and creates one when the set has no active key | | `POST /api/sets//start`, `/stop`, `/restart` | lifecycle | | `POST /api/sets//reload` | apply `servers.json` without a restart: `{"reloaded":true,"generation":N,"applied":[…],"restartNeeded":[…],"error":"…"}`. A stopped set answers `{"reloaded":false,"reason":"набор не запущен"}` and the file is written anyway. A non-empty `restartNeeded` or a set `error` gives `reloaded:false` with the cause in `reason`; a write failure is `500` | | `GET /api/sets//servers` | per-server health for one set | | `GET /api/sets//logs?lines=N` | log tail (default 200 lines) | -| `GET /api/sets//servers//logs` | one downstream's log lines | +| `GET /api/sets//servers//logs` | one downstream's log lines, oldest first: a `— запуск —` marker opens each run of the process, and an unreadable tail adds `error` (absent means the server simply wrote nothing) | | `GET /api/sets//tools` | `{"tools":[…]}` — the set's descriptor records: `server`, `tool`, `hash` (as the catalog serves it now), `approvedHash` and `state` (`ok`, `changed`) | | `POST /api/sets//tools/approve` | approve the current descriptor: `{"server":"serena","tool":"find_symbol"}`, or `{"all":true}` for everything currently changed; answers `{"approved":["serena/find_symbol"]}`, empty when nothing needed it. The record is written with `approvedBy: "panel"` | | `POST /api/sets//prompt` | one text for an agent out of three parts: `{"task":"…","intro":"…","servers":["…"]}` → `{"prompt":"…","notes":["…"]}`. `intro` and `servers` are optional, an empty `task` is `400`; tools come from the live catalog with their input schemas, a stopped set falls back to the `tools.lock.json` names and says so in `notes` | @@ -382,7 +397,11 @@ loses no output: the old file stays in place and the error text is shown in the set status `error`. `/api/calls` polls each running set's `/stats` with a 2 s timeout and its -registry key. A **running** set that does not answer is listed in `unreachable` +registry key, and marks the request as the panel's own service call +(`X-MCPRig-Caller: panel`) — that is what earns the full snapshot; any other +holder of the key gets the redacted one (see +[architecture.md](architecture.md)). A **running** set that does not answer is +listed in `unreachable` by id; its error text is not forwarded. A stopped set is not polled: its tail and counters come from the raw journal on disk (see [Call history](#call-history)), so a missing directory answers empty instead of landing in `unreachable`. @@ -551,7 +570,8 @@ from the `Origin` checks: a failed login grants nothing. `Origin` is compared in full — scheme, host and port; `MCPRIG_ALLOWED_HOSTS` is not a list of sources (it names the panel itself). `X-Forwarded-Proto`, `X-Forwarded-Host` and `X-Forwarded-For` are trusted only when -`MCPRIG_PROXY_SECRET` is set *and* the peer is loopback or listed in +`MCPRIG_PROXY_SECRET` is set, the request carries `x-mcp-proxy-secret` equal to it +(compared in constant time), *and* the peer is loopback or listed in `MCPRIG_TRUSTED_PROXIES` (an IP or a CIDR, comma-separated): a trusted proxy makes an `https` request count as secure and a forwarded host count as the panel's public name, so an `https` Origin matches. diff --git a/docs/history/audits/2026-11-16-mcp-field-test.md b/docs/history/audits/2026-11-16-mcp-field-test.md index 4fd1d09..a73e8c8 100644 --- a/docs/history/audits/2026-11-16-mcp-field-test.md +++ b/docs/history/audits/2026-11-16-mcp-field-test.md @@ -235,3 +235,33 @@ | контраст и тап-таргеты | raven `audit_contrast`, `audit_tap_targets` | | артефакт дизайна и превью | open-design `get_project` | | отладка с точкой останова | dap-mcp `debug_launch` c `breakpoints` → `debug_snapshot` | + +## Набор `ha` на боевой панели (2026-11-17) + +Проверено живым прогоном под паролем (вход `POST /api/login`, `Origin` обязателен +на небезопасных методах, иначе `403`; пароль брался из окружения, в чат не +попадал). + +- Набор `ha` (порт 9102, `autostart: true`) — **8 серверов, все `healthy`**: + `siyuan`, `ticktick`, `qbittorrent`, `commafeed-mcp`, `arr-lidarr`, + `arr-prowlarr`, `arr-slskd`, `arr-status`; 969 инструментов, ни одного в + ожидании подтверждения. Набор запущен с 11:57. +- Проверка каждого сервера (`POST /api/servers/<имя>/probe`) — 200 у всех восьми: + `qbittorrent` 152 мс, `arr-prowlarr` 76 мс, `arr-slskd` 59 мс, + `arr-lidarr` 151 мс, `arr-status` 272 мс, `siyuan` 574 мс, + `commafeed-mcp` 4257 мс, `ticktick` 5605 мс (медленные — их бэкенды, не прокси). +- Ключ выдаётся и отзывается: `POST /api/sets/ha/keys` → `{token, key}`, после + работы `DELETE /api/sets/ha/keys/` → `revokedAt`; в списке остаётся + `activeKeys: 1`. +- Через выданный ключ MCP отвечает: `initialize` 200 (`protocolVersion` + 2025-11-25), `tools/list` — 9 мета-инструментов, `list_servers` — восемь + серверов с описаниями, числом инструментов и пометкой `approval`. +- Отказы внятные: неизвестный инструмент — `Error: неизвестный инструмент + "app_version" у сервера "qbittorrent"`, а `describe_commands` на него отвечает + `{"commands": [], "missing": ["app_version"]}` — то есть промах виден и в + ошибке, и в описании. +- Собственный отказ сервера проходит насквозь как `isError: true` с текстом + бэкенда: `siyuan` `list_notebooks` → `{"error": "fetch failed", "endpoint": + "/api/notebook/lsNotebooks"}`. Сервер `healthy` — значит связь с ним есть, а + падает его собственный API (адрес или токен SiYuan), это дело настройки + сервера, не прокси. diff --git a/docs/history/audits/2026-11-17-panel-acceptance.md b/docs/history/audits/2026-11-17-panel-acceptance.md new file mode 100644 index 0000000..68415c2 --- /dev/null +++ b/docs/history/audits/2026-11-17-panel-acceptance.md @@ -0,0 +1,674 @@ +# Приёмка панели 0.6.5: четыре расхождения и их причины + +Владелец проверил выпущенный бинарь на своём инстансе (`MCPRIG_DATA_DIR=/tmp/opencode/verify-data`, +порт 9112, `MCPRIG_AUTH=off`, `?mock=1`) и нашёл четыре места, где панель ведёт себя +не так, как обещал отчёт предыдущей полосы (`docs/history/audits/2026-11-17-panel-pages.md`). +Правки — в `web/`, ветка `fix/panel-acceptance`. `CHANGELOG.md`, `CHANGELOG.ru.md` и +`docs/history/index.md` правит тот, кто сводит ветку: нужные строки выписаны в конце. + +Проверял по реальному рендеру: свой инстанс (`MCPRIG_DATA_DIR=/tmp/opencode/pages-data`, +порт 9099, `MCPRIG_AUTH=off`) и демо-данные `?mock=1` из `web/mock/*.json`. Ширины +375, 768 и 1280, языки EN и RU, схемы dark и w98 (Win98 поверх своих 10–11 px). + +## 1. Неизвестный маршрут открывал последний набор + +Причина не в одной строке, а в трёх местах сразу: + +- `pageOf()` (`web/app.js`) отдаёт `sets` для любого незнакомого адреса — так и было задумано; +- `route()` приводил панель к адресу только когда в адресе назван набор + (`if (r.page === 'sets' && r.set)`), поэтому на `#/nonsense` ничего не менялось: + оставался `st.sel` от прошлого клика; +- `renderChrome()` считал `onSets = st.page === 'sets'` и на любой странице наборов + показывал шапку набора и вкладки. **Списка наборов в панели не существовало вовсе** — + списком был только левый рельс, а `#/sets` открывал обзор последнего выбранного набора. + Это и видел владелец: `#/sets` на скриншоте `design/ui/panel-pages/after-sets-1280-dark-en.png` + предыдущей полосы — обзор набора `main`, а не список. + +Что сделано: + +- появилось состояние `st.list` — «страница наборов без набора в адресе»; `route()` + ставит его из адреса и в этом случае обнуляет `st.sel`; +- в `#page-sets` добавлен блок `#sets-list`: таблица **Set** (имя и `:port`), **State**, + **Servers**, **Keys** — строка ведёт на `#/set/`; данные те же, что уже приходят + в `/api/state`, ни одного нового поля бэкенда; +- `renderChrome()` в режиме списка прячет шапку набора, вкладки и **все панели вкладок** + (`applyTab(null)`), показывает `#sets-list` и рисует его же (`renderSetsList()`); +- `loadState()` в режиме списка не выбирает первый набор автоматически — раньше + `indexOf(null) === -1` тянул `select(ids[0])` и список немедленно превращался в набор; +- `select()` снимает режим списка и вызывает `renderChrome()`, поэтому шапка и вкладки + возвращаются вместе с набором; +- крошка в режиме списка называет страницу (`Наборы`), а не прочерк. + +Проверено в браузере: `#/nonsense` → список, `#/sets` → список, `#/set/main` → набор, +клик по строке списка кладёт `#/set/main` в историю, «назад» возвращает к списку. + +## 2. Заголовок окна не следовал странице + +Было: `document.title = st.sel ? t('title.set', {name: st.sel}) : t('title.panel')` — +`st.sel` переживал переход на другую страницу, поэтому `#/` и `#/sets` назывались +`mcprig — set main`, а по-английски ещё и `set` вместо имени набора. + +Стало (`setTitle()`, вызывается из `renderChrome()`, `setTab()` и `select()`): + +| адрес | заголовок EN | заголовок RU | +| --- | --- | --- | +| `#/` | `mcprig — Overview` | `mcprig — Обзор` | +| `#/sets` | `mcprig — Sets` | `mcprig — Наборы` | +| `#/stats/7d` | `mcprig — Statistics` | `mcprig — Статистика` | +| `#/servers` | `mcprig — All servers` | `mcprig — Все серверы` | +| `#/vars` | `mcprig — Variables` | `mcprig — Переменные` | +| `#/set/main` | `mcprig — set main` | `mcprig — набор main` | +| `#/set/main/keys` | `mcprig — set main · Keys` | `mcprig — набор main · Ключи` | +| `#/nonsense` | `mcprig — Sets` | `mcprig — Наборы` | + +Ключ `title.panel` сокращён до `mcprig` — из него теперь собирается «`mcprig` — страница». +Набор называется по имени, а не по `id`. + +## 3. Мок отставал от выпуска + +`web/mock/state.json` отвечал `version: 0.6.4`, живой `/api/state` — `0.6.5`; подвал +панели показывает именно это поле, так что демо-режим врал о версии. Исправлено на +`0.6.5`. Остальные поля сверены тем же скриптом, что и в прошлый раз +(`/tmp/opencode/mock-parity.py`: собирает все `json:"…"` теги из `internal/` и имена из +map-литералов, затем walk по `web/mock/*.json`): `mock: все поля есть в живых ответах +(257 имён сверено)`. Ключи `reloadErrors`, `failed`, `throttledTools` скрипт пропускает — +их ключи это id наборов, а не поля. + +## 4. «Latest calls» на обзоре хоста на 375 px + +Вкладку **Calls** набора владелец признал годной и просил не трогать — она и не +тронута: у `#calls-table` прежняя раскладка `data-label`. + +Плохо было на обзоре хоста: `#host-calls-table` — настоящая таблица из шести колонок, +на 375 px она сжималась и подписи TIME/SET/SERVER/TOOL/MS/STATUS перемешивались со +значениями. Теперь при ширине ≤ 760 px каждая строка — карточка, запись читается сверху +вниз: + +``` +11/08, 23:14 ● ok +main socraticode +codebase_search 329 +``` + +Время (моно, приглушённое) и статус — первая строка; набор и сервер — вторая; +инструмент (моно, переносится) и миллисекунды — третья. Ячейки получают `data-col` +в `renderHostCalls()`, раскладка — в `web/app.css` под `#host-calls-table` (правило +привязано к id этой таблицы, поэтому вкладку **Calls** не задевает). На 768 и 1280 +таблица остаётся таблицей: свёртка включается на ≤ 760 px. + +## Что проверено + +| проверка | результат | +| --- | --- | +| `node --check web/app.js` | ok | +| `bash scripts/docs-check.sh` | `links resolve`, `no personal paths`, `no orphans`, `language parity`, `anchors (10)` — все ok | +| маршруты (`#/set/main`, `…/keys`, `…/nope`, `#/sets`, `#/nonsense`, `#/`, `#/stats/7d`, `#/servers`, `#/vars`) | страница, вкладка, `aria-current` и заголовок — как в таблицах выше | +| история | рельс → `#/set/main`, вкладка → `#/set/main/calls`, «назад» ×2 → `#/set/main` (обзор) → `#/sets` (список) | +| консоль | ошибок нет (единственные ошибки в сессии — от мёртвого инстанса 9112, не от этих страниц) | +| горизонтальный скролл на 375 | `scrollWidth === clientWidth === 375` на `#/`, `#/sets` и `#/set/main/calls` | +| mock parity | `257 имён сверено`, расхождений нет | + +Скриншоты — `design/ui/panel-pages/`: + +| файл | что видно | +| --- | --- | +| `fix-sets-1280-dark-en.png` | страница **Sets** на 1280, EN, dark | +| `fix-sets-375-dark-en.png` | она же на 375 — карточки, без горизонтального скролла | +| `fix-sets-1280-dark-ru.png` | она же на 1280, RU | +| `fix-sets-1280-win98-ru.png` | она же в теме Win98, RU | +| `fix-host-1280-dark-en.png`, `fix-host-1280-dark-ru.png` | обзор хоста целиком | +| `fix-host-calls-768-dark-en.png` | 768 — таблица вызовов осталась таблицей | +| `fix-host-calls-375-dark-en.png`, `fix-host-calls-375-win98-ru.png` | 375 — карточки вызовов, dark и Win98 | + +До/после по свёртке: `design/ui/panel-pages/after-host-1280-dark-en.png` (предыдущая +полоса) и `fix-host-calls-375-dark-en.png` (сейчас). + +## Отклонения и то, что осталось как есть + +- **Win98** держит свои 10–11 px и 21–24 px хром — это зафиксированное решение + предыдущей полосы (пункт 6 в `2026-11-17-panel-fixes.md`): тема воспроизводит систему, + а не современный интерфейс. Правило «не мельче 12 px / цель ≥ 32 px» выполняется в + четырёх схемах Default; карточки вызовов в Win98 читаются теми же 11 px. +- `#/set//nope` открывает обзор **и нормализует адрес** на `#/set/`: так ссылка + в строке браузера перестаёт врать. Кнопка «назад» после этого возвращает к прежней + записи истории, а не к несуществующей вкладке. +- Список наборов показывает состояние без причины простоя — причина осталась на обзоре + хоста, в строке набора. Дублировать красную строку в двух таблицах не стали. +- Числа `/tool-out` по-прежнему прочерк: поля в API нет (`internal/toolout` знает TTL, + но наружу его не отдаёт). Подпись под плитками говорит об этом прямым текстом. + +## Файлы + +- `web/index.html` — блок `#sets-list`, `class="num"` у числовых колонок. +- `web/app.js` — `st.list`, `route()`, `loadState()`, `renderChrome()`, `renderCrumb()`, + `select()`, `setTab()`, `setTitle()`, новый `renderSetsList()`, `callRow()` и `data-col` + в `renderHostCalls()`; ключи `title.panel` (EN и RU). +- `web/app.css` — карточная раскладка `#host-calls-table` на ≤ 760 px, цель нажатия + у ссылок списка наборов. +- `web/mock/state.json` — `version: 0.6.5`. +- `docs/en/panel.md`, `docs/ru/panel.md` — строка «страница наборов» и про заголовок окна. + +## Строки для CHANGELOG + +`CHANGELOG.md`, под `## [Unreleased]`: + +``` +### Fixed +- Panel: an address that names no set (`#/sets` or an unknown route) opens the list of + sets instead of the set that was open last; the window title follows the page, and the + latest calls on the host overview read as cards on a phone. +``` + +`CHANGELOG.ru.md`, там же: + +``` +### Исправлено +- Панель: адрес без набора (`#/sets` или неизвестный маршрут) открывает список наборов, + а не набор, открытый последним; заголовок окна следует за страницей, а последние вызовы + на обзоре хоста на телефоне читаются карточками. +``` + +## Жалоба владельца: «через гуй настроить ничего нельзя, ничего не сохраняется» + +Проверка на чистой установке: `MCPRIG_DATA_DIR=/tmp/opencode/clean-data +MCPRIG_AUTH=off MCPRIG_PORT=9114`, в каталоге только `manager.pid`, панель +открывается на обзоре хоста (`#/`). + +**Что воспроизвелось.** Набор создаётся (запись в `registry.json` появляется, +рельс показывает `lab :9115 · stopped`), но панель остаётся на обзоре хоста: +адрес не меняется, вкладки набора скрыты, клик по набору в рейле меняет только +`document.title` (`mcprig — set lab`) — `location.hash` остаётся `#/`, видимая +страница остаётся `#page-host`. С чистой установки попасть в набор нельзя: +вкладок нет, значит нет ни «Add server», ни ключей, ни логов. + +**Корень.** `select()` писал адрес и, значит, переключал страницу только когда +панель уже стояла на странице наборов: +`if (st.page === 'sets' && id && (force || location.hash.indexOf('#/set/') === 0))` +(`web/app.js:1976`). Явный выбор — клик в рейле (`web/app.js:4085-4091`, +`select(row.dataset.id, true)`) и создание набора (`web/app.js:4525`, +`select(set.id, true)`) — приходил с `force`, но при `st.page === 'host'` блок +пропускался целиком. Отсюда же второй симптом: при создании набора с обзора +адрес не менялся, а при создании со страницы набора появлялся сразу +`#/set//servers` — то есть поведение зависело от того, откуда пришли. + +**Правка** (`web/app.js:1971-1980`): явный выбор открывает страницу набора сам, +а не только пишет адрес. + +```js +if (id && (force || location.hash.indexOf('#/set/') === 0)) { + if (st.page !== 'sets') { applyPage('sets'); } + var next = setHash(id, st.tab); + if (location.hash !== next) { history.pushState(null, '', next); } +} +``` + +Автовыбор первого набора (`select(ids[0])` без `force`) страницу не трогает, +поэтому `#/` по-прежнему открывается обзором хоста, а `#/sets` — списком. + +**Проверка на сборке из ветки** (`MCPRIG_DATA_DIR=/tmp/opencode/nav-data +MCPRIG_AUTH=off MCPRIG_PORT=9117`), playwright: + +| Шаг | Ожидание | Факт | +| --- | --- | --- | +| чистый старт `#/` | обзор, 0 вкладок | `#/`, `#page-host`, вкладок 0 | +| создать первый набор | страница набора, вкладки | `#/set/lab`, `#page-sets`, вкладок 6 | +| из `#/` клик по набору в рейле | открыть набор | `#/set/lab`, вкладок 6 | +| из `#/stats/today` клик по рейлу | открыть набор | `#/set/lab`, вкладок 6 | +| загрузка `#/` | обзор, без автоперехода | `#/`, обзор, 0 вкладок | +| `#/sets` | список наборов | `#page-sets`, список, вкладок 0 | +| строка списка → набор → «назад» | набор → список | `#/set/lab` → `#/sets` | + +Сквозной сценарий на той же сборке: набор `lab` → сервер `dap` +(`/home/sintez/.local/share/dap-mcp/bin/dap-mcp`, stdio) → «add to set» → +Start → `running`, сервер `Healthy`, 13 инструментов `approved` → ключ `cli` +выдан (`3dbaf40f977a…`) → `initialize` на `http://127.0.0.1:9118/mcp` → 200, +`tools/list` 9 мета-инструментов, `invoke_command({server:"dap", +command_name:"debug_list_sessions"})` → `{"sessions":[]}`. То есть после правки +чистая установка настраивается через панель до работающего MCP-эндпоинта. + +**Что при проверке работало и правки не требует:** создание набора (в том числе +с пустым портом — берётся свободный, и с занятым — «порт 9116 занят набором +no-port»), создание и правка сервера (`env`, `cwd`, описание сохраняются и +возвращаются в форму после переоткрытия), привязка сервера к набору, запуск +набора с внятной ошибкой на неразрешимой переменной («переменная GITEA_TOKEN: +источник не найден …; набор lab не запущен»), переменные `#/vars` («value saved +for TEST_VAR · file»), выдача и отзыв ключей, тема и язык (`localStorage` +`mcprig.theme` / `mcprig.palette.win98` / `mcprig.lang` переживают перезагрузку). + +**Найденное рядом, не исправлено:** список ключей показывает идентификатор +ключа (`9cdc08cd1c79`), а подпись обещает «первый 8 символов» токена — мелочь +копирайта; `web/codemap.md` отстал от PR #31 по номерам строк (обновлена +только секция экранов, затронутая этой правкой). + +### Бейдж состояния набора был чёрным + +Найдено при просмотре скриншотов: в списке наборов и на обзоре хоста состояние +рисовалось чёрным кружком. Причина — два соглашения об имени класса в одном +месте: `setState()` возвращает `cls: 'ok'|'err'|'warn'`, `badgeState()` — +`'badge-ok'|'badge-err'|'badge-unknown'`, а `paintBadge()` склеивал +`'badge ' + cls`, и для `setState` получался класс `badge ok`, которого в +`web/app.css` нет (там `.badge-ok`, `.badge-err`, `.badge-warn`, `.badge-unknown`). + +Правка — одна строка в `paintBadge` (`web/app.js:1741-1746`): префикс `badge-` +добавляется, только если его нет. Проверено на `?mock=1#/sets` (1280, тёмная +тема): `badge badge-ok` → `rgb(67, 196, 139)`, `badge badge-err` → +`rgb(242, 119, 110)`, кружок берёт цвет из `currentColor`. + +### Что осталось косметикой + +Три вещи отданы полосе designer (отдельный раздел «Полировка после приёмки»): +ширины колонок `#sets-table` (State 305 px против Keys 158 px), висящая точка в +статусбаре на 375 px (`#f-version` держит `mcprig 0.6.5 ·` вместе с +разделителем) и одинокая кнопка `#copy` в шапке на 375 px, когда адрес +эндпоинта скрыт. + +## Полировка после приёмки + +Три косметических дефекта, найденных на живом инстансе (1280×900, тёмная тема, +EN). Правка — в `web/app.css`, плюс одна строка в `web/app.js`. Поведение и +разметка не менялись. + +### 1. Колонки `#sets-table` разъезжались + +**Было.** Set 301, State 305, Servers 223, Keys 158 при ширине таблицы 988 px +(у владельца 1031 — разница в шрифте). State занимал вчетверо больше своего +содержимого (бейдж ~78 px), между State и Servers — пустой провал, числа +прижаты вправо. + +**Причина.** У таблицы авто-раскладка. Заданная `width` у `th` в ней — только +пожелание: лишнее место браузер раздаёт по своему усмотрению, и колонка из +одного слова получает столько же, сколько колонка с названием набора. Одни +`th { width }` ширины не сдвинули ни на пиксель — понадобился `table-layout`. + +**Стало** (`web/app.css:534-541`): `#sets-table { table-layout: fixed }` плюс +`th:nth-child(2)` 140 px, `(3)` 110 px, `(4)` 96 px. Замер: Set 642 / State 140 +/ Servers 110 / Keys 96. Русские заголовки «Состояние» и «Серверов» в свои +колонки помещаются (`th.scrollWidth === th.clientWidth`). + +Мобильный вид не затронут: `#sets-table` — тот же `.rtable`, что у +`#host-calls-table`, на ≤ 760 px строки становятся карточками +(`display: block`), и `table-layout` там ни на что не влияет. Проверено на 375 +и 700 px. + +### 2. Точка-разделитель висела в конце строки + +**Было.** `#f-version` содержал `mcprig 0.6.5 ·`: разделитель лежал внутри +спана версии. На 375 px, когда хвост статусбара не влезал, строка рвалась после +точки, и «обновлено» уезжало вниз без версии, к которой относится. + +**Стало.** Точка убрана из текста (`web/app.js:1603`, `renderChrome`), её +рисует CSS: `.statusbar #f-version + span::before { content: '·' }` +(`web/app.css:802`) — точка принадлежит тому, что за ней следует, и переносится +вместе с ним. Сам статусбар стал `flex-wrap: wrap` с `min-height` вместо +`height` (`web/app.css:787-794`), а правая группа неразрывна — +`.statusbar .right { white-space: nowrap; gap: 6px }` (`web/app.css:795-801`), +поэтому время не отрывается от «обновлено». + +Проверено на искусственно длинном счётчике при 375: правая группа целиком +уходит на вторую строку, статусбар растёт с 30 до 35 px, висящей точки нет. В +обычном случае строка одна, высота 30 px. + +### 3. Одинокая кнопка копирования в шапке на 375 px + +**Было.** На ≤ 640 px `.endpoint` сжимался до 44 px, подпись и адрес +скрывались — оставалась тёмная плашка 29×32, читаемая как случайный квадрат. + +**Стало** (`web/app.css:900-908`): у кнопки остаётся компактная подпись — +«ENDPOINT ⧉» (103 px) в EN и «АДРЕС ⧉» (82 px) в RU, адрес по-прежнему скрыт. +Заодно на ≤ 640 px убран хлебный корень «mcprig /» (`#crumb-root` и +разделитель): на узком экране он повторял то, что и так написано в заголовке +страницы, и отнимал место у кнопки. + +### Контраст новых блоков + +raven `audit_contrast`, строки сняты со страницы: фон — эффективный, альфа +складывается по цепочке предков, а не берётся из объявленного `background`. +`badge-warn` в моке не встречается — временная строка +`stopped` добавляется в `#sets-body`, +меряется и убирается. + +| блок | тёмная | светлая | +| --- | --- | --- | +| `#sets-table thead th` | 6.54 | 5.51 | +| ссылка набора | 7.95 (AAA) | 5.49 | +| `badge-ok` «running» | 7.00 | 4.99 | +| `badge-err` «failed» | 5.82 | 4.70 | +| `badge-warn` «stopped» | 7.60 (AAA) | 4.55 | +| число `td.num` | 16.30 (AAA) | 17.25 (AAA) | +| статусбар: счётчики, версия, «обновлено», время | 6.29 | 5.17 | +| подпись кнопки `#copy` | 5.95 | 5.85 | +| адрес эндпоинта | 14.83 (AAA) | 18.34 (AAA) | + +Провалов AA нет ни в одной схеме, неопределённого фона нет. Тонкое место — +`badge-warn` в светлой схеме: 4.55 при пороге 4.5. Запас 0.05 — это сегодняшние +токены (`--warn` на `--warn-bg`), а не следствие правки, но если палитра +сдвинется, этот бейдж сломается первым. + +### Чем проверено + +| проверка | результат | +| --- | --- | +| `node --check web/app.js` | ok | +| `bash scripts/docs-check.sh` | `links resolve`, `no personal paths`, `no orphans`, `language parity`, `anchors (10)` — все ok | +| горизонтальный скролл на 375 | `scrollWidth === clientWidth === 375` на `#/`, `#/sets`, `#/set/main/calls`; элементов, выходящих за вьюпорт, нет | +| консоль | `Total messages: 0 (Errors: 0, Warnings: 0)` | +| контраст | raven, тёмная и светлая схемы, 12 строк, провалов нет | + +Скриншоты — `design/ui/panel-pages/`, тёмная тема, EN: + +| файл | что видно | +| --- | --- | +| `polish-sets-1280-dark-en.png` | `#sets-table` с новыми ширинами | +| `polish-sets-375-dark-en.png` | карточки наборов на 375 и подпись у кнопки копирования | +| `polish-host-375-dark-en.png` | статусбар одной строкой | +| `polish-set-calls-375-dark-en.png` | страница набора на 375 | + +Отдельно к инструментам, для следующей полосы: ассеты панели вшиты через +`go:embed`, поэтому правка `web/*` видна только после пересборки бинаря и +перезапуска процесса — до этого отдаётся старый CSS, и замеры показывают +прежние числа. + +## Цели нажатия в 32 px + +Замер обхода всех интерактивных элементов на пяти страницах (375 и 1280, +обе схемы) нашёл четыре цели ниже порога. Все четыре — по одной строке CSS, +разметку менять не понадобилось. + +| цель | было | стало | +| --- | --- | --- | +| `button#srv-new.btn.btn-sm` (All servers) | 80×27 | 80×32 | +| `button#env-save.btn.btn-sm` (Variables) | 46×27 | 46×32 | +| `label.check` вокруг `input#only-err` (Calls) | 96×19 | 96×32 | +| `input` подписи ключа в `#key-list` (Keys) | 260×31 | 260×32 | + +- `.btn-sm { min-height: 27px }` → `32px` (`web/app.css:469`). Это общий класс + мелкой кнопки: им же нарисованы `check`/`log`/`edit` в строке сервера, `save`/ + `revoke` у ключа, `Download JSON`/`Copy` на Import/Export. Строки выросли на + те же 5 px, но остались плотными — 32 px это нижняя граница под палец, а не + воздух. +- `label.check` получил `min-height: 32px` и `cursor: pointer` + (`web/app.css:643`): сама галочка осталась 13×13, но нажимается вся подпись, + а `