From f27fd035bc9515eedced9525dc1577211b3d5e0b Mon Sep 17 00:00:00 2001 From: Denozordec Date: Sun, 22 Nov 2026 01:51:25 +0700 Subject: [PATCH] =?UTF-8?q?fix(mcp):=20=D1=83=D0=BF=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B8=D1=82=D1=8C=20=D0=B2=D1=8B=D0=B1=D0=BE=D1=80=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D1=80=D0=B5=D1=88=D0=B5=D0=BD=D0=B8=D0=B9=20?= =?UTF-8?q?=D0=B8=20=D1=83=D1=81=D0=BA=D0=BE=D1=80=D0=B8=D1=82=D1=8C=20?= =?UTF-8?q?=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D1=83=20=D1=84=D1=80=D0=BE=D0=BD?= =?UTF-8?q?=D1=82=D0=B5=D0=BD=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitea/workflows/docker.yml | 49 +++++++++++++++++++++++++++++- components/mcp/mcp-workspace.tsx | 46 ++++++++++++++++++++++++++-- tests/e2e/mcp-auth-context.spec.ts | 17 +++++++++++ tests/e2e/mcp-context.spec.ts | 1 + 4 files changed, 110 insertions(+), 3 deletions(-) diff --git a/.gitea/workflows/docker.yml b/.gitea/workflows/docker.yml index 38c57dd0..c792cf7a 100644 --- a/.gitea/workflows/docker.yml +++ b/.gitea/workflows/docker.yml @@ -19,12 +19,39 @@ jobs: tag: ${{ steps.release.outputs.tag }} bump: ${{ steps.release.outputs.bump }} release_url: ${{ steps.release.outputs.release_url }} + backend_reuse_version: ${{ steps.changes.outputs.backend_reuse_version }} steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 + - name: Check if the released backend can be reused + id: changes + shell: bash + env: + EVENT_NAME: ${{ gitea.event_name }} + BEFORE_SHA: ${{ gitea.event.before }} + run: | + set -euo pipefail + if [[ "$EVENT_NAME" != push || ! "$BEFORE_SHA" =~ ^[0-9a-f]{40}$ ]] || + ! git merge-base --is-ancestor "$BEFORE_SHA" HEAD 2>/dev/null; then + exit 0 + fi + # Compare with a published release, including changes from any failed earlier run. + BASE_TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' "$BEFORE_SHA" 2>/dev/null || true) + if [[ ! "$BASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || git diff --quiet "$BASE_TAG" HEAD --; then + exit 0 + fi + if git diff --quiet --no-renames "$BASE_TAG" HEAD -- . \ + ':(exclude)app/**' ':(exclude)components/**' ':(exclude)lib/**' ':(exclude)shared/**' \ + ':(exclude)entities/**' ':(exclude)public/**' ':(exclude)hooks/**' ':(exclude)tests/e2e/**' \ + ':(exclude)Dockerfile.frontend' ':(exclude)next.config.ts' ':(exclude)tsconfig.json' \ + ':(exclude)postcss.config.mjs' ':(exclude)eslint.config.mjs' ':(exclude)components.json' \ + ':(exclude,top,glob)playwright*.config.ts'; then + echo "backend_reuse_version=${BASE_TAG#v}" >> "$GITHUB_OUTPUT" + fi + - name: Test release version calculation run: node --test .ci/scripts/compute-release.test.mjs @@ -42,17 +69,21 @@ jobs: test -f .ci/release/release-manifest.json backend-test: + needs: prepare-release runs-on: ubuntu-latest steps: - name: Checkout + if: needs.prepare-release.outputs.backend_reuse_version == '' uses: actions/checkout@v4 - name: Setup Node 22 + if: needs.prepare-release.outputs.backend_reuse_version == '' uses: actions/setup-node@v4 with: node-version: 22 - name: Start PostgreSQL 18 + if: needs.prepare-release.outputs.backend_reuse_version == '' shell: bash run: | set -euo pipefail @@ -93,6 +124,7 @@ jobs: exit 1 - name: Install and test backend + if: needs.prepare-release.outputs.backend_reuse_version == '' shell: bash env: REQUIRE_TEST_POSTGRES: "1" @@ -112,7 +144,7 @@ jobs: npm run test --prefix backend - name: Stop PostgreSQL - if: always() + if: always() && needs.prepare-release.outputs.backend_reuse_version == '' shell: bash run: docker rm -f "${PG_CONTAINER:-}" 2>/dev/null || true @@ -123,6 +155,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout + if: needs.prepare-release.outputs.backend_reuse_version == '' uses: actions/checkout@v4 - name: Configure backend image name @@ -135,6 +168,7 @@ jobs: echo "IMAGE_NAME=${{ env.REGISTRY }}/${owner}/${stem}-backend" >> "${GITHUB_ENV}" - name: Prepare backend build context + if: needs.prepare-release.outputs.backend_reuse_version == '' shell: bash run: | set -euo pipefail @@ -174,6 +208,7 @@ jobs: password: ${{ secrets.ACTIONS_PAT }} - name: Build and push backend image + if: needs.prepare-release.outputs.backend_reuse_version == '' uses: docker/build-push-action@v5 with: context: .ci/docker/backend @@ -195,6 +230,18 @@ jobs: org.opencontainers.image.revision=${{ gitea.sha }} org.opencontainers.image.created=${{ gitea.event.head_commit.timestamp }} + - name: Tag the existing backend image for this release + if: needs.prepare-release.outputs.backend_reuse_version != '' + shell: bash + env: + BACKEND_VERSION: ${{ needs.prepare-release.outputs.backend_reuse_version }} + RELEASE_VERSION: ${{ needs.prepare-release.outputs.version }} + run: | + set -euo pipefail + docker buildx imagetools create --prefer-index=false \ + --tag "$IMAGE_NAME:$GITHUB_SHA" --tag "$IMAGE_NAME:$RELEASE_VERSION" \ + "$IMAGE_NAME:$BACKEND_VERSION" + frontend-image: needs: prepare-release runs-on: ubuntu-latest diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx index 1a4f4392..0394289b 100644 --- a/components/mcp/mcp-workspace.tsx +++ b/components/mcp/mcp-workspace.tsx @@ -31,6 +31,11 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } f const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос" const modeLabels = { observer: "Наблюдатель", approval: "С подтверждением", autonomous: "Автономный" } +const operationSectionLabels: Record = { + backups: "Резервные копии", certificates: "Сертификаты", filters: "Фильтры маршрутизации", firewall: "Межсетевой экран", + ipsec: "IPsec", logs: "Журналы", mcp: "Управление MCP", network: "Сеть и маршрутизация", "recursive-routes": "Рекурсивные маршруты", + servers: "Серверы", settings: "Настройки", traffic: "Трафик", uptime: "Доступность", users: "Пользователи", wireguard: "WireGuard", +} const tabs = { overview: "Обзор", connections: "Подключения", permissions: "Разрешения", devices: "Интерфейсы", requests: "Обращения", plans: "Планы и операции", routing: "Route AI", settings: "Настройки" } type Tab = keyof typeof tabs type RecordRow = Record @@ -162,7 +167,19 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 }) const permissions = getClaims()?.permissions ?? [] const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission))) - const toggle = (id: string) => setSelected(ids => ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id]) + const selectedIds = new Set(selected) + const bySection = new Map() + for (const operation of eligible) { + const group = bySection.get(operation.section) + if (group) group.push(operation) + else bySection.set(operation.section, [operation]) + } + const groups = [...bySection] + .sort(([left], [right]) => (operationSectionLabels[left] ?? left).localeCompare(operationSectionLabels[right] ?? right, "ru")) + const selectOperations = (operations: McpOperationDescriptor[], checked: boolean) => { + const groupIds = new Set(operations.map(operation => operation.id)) + setSelected(ids => checked ? [...new Set([...ids, ...groupIds])] : ids.filter(id => !groupIds.has(id))) + } const save = async () => { setBusy(true); setError("") try { @@ -173,7 +190,32 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp } return { if (!open && !busy) close() }}>{editing ? "Изменить разрешения" : "Новое подключение"}Шаг {step} из 4 · доступ ограничивается правами текущего владельца. {step === 1 && <> setName(event.target.value)} placeholder="Агент диагностики" /> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}} - {step === 2 && <> setServerText(event.target.value)} placeholder="1, 2" />
{eligible.map(operation => toggle(operation.id)} />)}

Новые инструменты не добавляются в доступ автоматически. Для применения планов выберите также инструменты просмотра и применения.

} + {step === 2 && <> + setServerText(event.target.value)} placeholder="1, 2" /> + +
+ + + Выбрано {selected.length} +
+
+ {groups.map(([section, items]) => { + const title = operationSectionLabels[section] ?? section + const count = items.filter(operation => selectedIds.has(operation.id)).length + return
+ 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} /> +
+ {title} {count} / {items.length} +
+ {items.map(operation => selectOperations([operation], checked)} />)} +
+
+
+ })} + {!eligible.length &&

Нет доступных операций.

} +
+

Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.

+ } {step === 3 && <>
{Object.entries(limits).map(([key, value]) => )[key]}> setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} />)}
setDanger(value as typeof danger)}>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}} {step === 4 &&

{name || "Без названия"} · {modeLabels[mode]}

Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

}
{step < 4 ? : }
diff --git a/tests/e2e/mcp-auth-context.spec.ts b/tests/e2e/mcp-auth-context.spec.ts index 33fa9f77..129fda80 100644 --- a/tests/e2e/mcp-auth-context.spec.ts +++ b/tests/e2e/mcp-auth-context.spec.ts @@ -292,6 +292,9 @@ test('synthetic: OAuth approval becomes unavailable when the selected connection test('synthetic: issue only selected server/read permission and hide one-time token', async ({ page }) => { const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read']) + const logStatus = { ...read, id: 'logs.status', toolName: 'mm_logs_status', title: 'Статус журналов' } + const capabilities = { ...read, id: 'capabilities.read', toolName: 'mm_capabilities_get', title: 'Доступные возможности', section: 'mcp', requiredPermissions: [] } + await page.route('**/api/mcp/catalog', route => route.fulfill({ json: { stage: 'runtime', executionAvailable: true, operations: [read, logStatus, capabilities, forbidden] } })) await page.goto('/mcp?tab=connections') await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click() const dialog = page.getByRole('dialog') @@ -299,6 +302,20 @@ test('synthetic: issue only selected server/read permission and hide one-time to await dialog.getByRole('button', { name: 'Далее', exact: true }).click() await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0) await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1') + await dialog.getByRole('button', { name: 'Выбрать все операции' }).click() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 3') + await dialog.getByRole('button', { name: 'Снять все' }).click() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 0') + const logsGroup = dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }) + await logsGroup.check() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 2') + await dialog.locator('summary').filter({ hasText: 'Журналы' }).click() + await expect(dialog.getByRole('checkbox', { name: read.title, exact: true })).toBeChecked() + await dialog.getByRole('checkbox', { name: logStatus.title, exact: true }).uncheck() + await expect(logsGroup).toHaveAttribute('aria-checked', 'mixed') + await logsGroup.check() + await logsGroup.uncheck() + await expect(dialog.getByRole('status')).toHaveText('Выбрано 0') await dialog.getByRole('checkbox', { name: read.title, exact: true }).check() await dialog.getByRole('button', { name: 'Далее', exact: true }).click() await dialog.getByRole('button', { name: 'Далее', exact: true }).click() diff --git a/tests/e2e/mcp-context.spec.ts b/tests/e2e/mcp-context.spec.ts index cb0db99e..c4779c6d 100644 --- a/tests/e2e/mcp-context.spec.ts +++ b/tests/e2e/mcp-context.spec.ts @@ -415,6 +415,7 @@ test("MCP: доступ, проверка подключения, выдача await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент") await page.getByRole("button", { name: "Далее", exact: true }).click() await page.getByLabel("ID разрешённых серверов через запятую").fill("1") + await page.locator("summary").filter({ hasText: "Журналы" }).click() await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check() await page.getByRole("button", { name: "Далее", exact: true }).click() await page.getByRole("button", { name: "Далее", exact: true }).click()