Files
MikrotikManager/tests/e2e/mcp-context.spec.ts
T

1194 lines
83 KiB
TypeScript

import { test, expect, type Page } from "@playwright/test"
import { createHash } from "node:crypto"
import { evaluateMcpPolicy } from "../../backend/src/modules/mcp/policy"
import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const at = "2026-10-17T00:00:00Z"
const operation = { id: "logs.query", toolName: "mm_logs_query", title: "Поиск логов", section: "logs", version: 1, effect: "read", risk: "ordinary", scope: "servers", requiredPermissions: ["mm:servers:read"], implementation: "available", annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } }
const connection = { id, name: "Диагностика WAN", ownerId: "ui-admin", policy: { id, version: 1, status: "active", mode: "approval", expiresAt: "2099-01-01T00:00:00Z", permissions: ["mm:servers:read"], scope: { serverIds: [1], operationIds: ["logs.query", "routing.profiles.save"], allowGlobal: false }, dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }
async function setup(page: Page, fail = false) {
await page.addInitScript(() => { localStorage.setItem("mmapp_token", "header." + btoa(JSON.stringify({ sub: "ui-admin", apps: ["mm"], permissions: ["mm:settings:admin", "mm:servers:read", "mm:network:admin"], exp: 4102444800 })) + ".signature") })
const calls: string[] = []
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname, method = route.request().method()
calls.push(method + " " + path)
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,PUT,DELETE,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
if (method === "OPTIONS") return route.fulfill({ headers, status: 204 })
const json = (body: unknown) => route.fulfill({ headers, json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] })
if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] })
if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at })
if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] })
if (path === "/api/mcp/devices/catalog") return json({ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }], resources: [{ id: "bridge", title: "Bridge", read: true, create: true, update: true, delete: true, fields: [{ key: "name", type: "string", requiredOnCreate: true }, { key: "comment", type: "string", requiredOnCreate: false }, { key: "disabled", type: "boolean", requiredOnCreate: false }] }] })
if (path === "/api/mcp/devices/1/bridge/plan") return json({ planId: id, state: "awaiting-approval" })
if (path === "/api/mcp/devices/1/bridge") return json({ items: [{ ".id": "*A", name: "lab-bridge", comment: "baseline", disabled: "true" }], total: 1, nextOffset: null })
if (path.endsWith("/check")) return json({ ok: true, checks: { enabled: true, active: true, protocolHandshake: true }, checkedAt: at, protocolProbe: { status: "passed", elapsedMs: 12, credentialType: "temporary-capabilities-read", capabilitiesRead: "passed", clientCredentialsVerified: false } })
if (path.endsWith("/grants")) return json({ grants: [] })
if (path === "/api/mcp/routing-profiles/plan") return json({ planId: id, state: "awaiting-approval" })
if (path === "/api/mcp/routing-profiles") return json({ profiles: [{ id, connection_id: id, config: { name: "Community WAN", community: "65000:10", family: "ipv6", table: "main" }, state: { pausedReason: "Допуск контроллера истёк" }, enabled: false, grant_expires_at: at }] })
if (path === "/api/mcp/protections") return json({ protections: [] })
if (path === "/api/mcp/settings") return json({ enabled: true, requestsRetentionDays: 30, auditRetentionDays: 180 })
if (path === "/api/mcp/management-channels") return json(method === "POST" ? { id, serverId: 1, expiresAt: at, verification: "identity-and-reachability", independence: "human-attestation" } : { channels: [] })
if (path === `/api/mcp/operations/${id}/recover`) return json({ planId: id, state: "awaiting-approval" })
if (path === `/api/mcp/operations/${id}/reconcile`) return json({ operationId: id, state: "applied", results: [], automaticRetry: false })
if (path === "/api/mcp/oauth/clients") return json({ clients: [] })
if (path.startsWith("/api/mcp/")) return json({ items: [], total: 0, nextCursor: null })
if (path === "/api/servers") return json([])
return json({})
})
return calls
}
test("MCP приостанавливает опрос по сигналу скрытия документа и возобновляет при показе", async ({ page }) => {
const calls = await setup(page)
const overviewCalls = () => calls.filter(call => call === "GET /api/mcp/overview").length
await page.clock.install()
await page.goto("/mcp?tab=overview")
await expect.poll(overviewCalls).toBeGreaterThan(0)
const setDocumentHidden = (hidden: boolean) => page.evaluate(value => {
Object.defineProperty(document, "hidden", { configurable: true, value })
document.dispatchEvent(new Event("visibilitychange"))
}, hidden)
await setDocumentHidden(true)
await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1_000))
const before = overviewCalls()
await page.clock.runFor(6_000)
expect(overviewCalls()).toBe(before)
const resumed = page.waitForRequest(request =>
request.method() === "GET" && new URL(request.url()).pathname === "/api/mcp/overview",
)
await setDocumentHidden(false)
await resumed
await expect.poll(overviewCalls).toBeGreaterThan(before)
})
test("MCP завершает начатое чтение и ждёт показа вкладки перед следующим опросом", async ({ page }) => {
await setup(page)
await page.clock.install()
let starts = 0
let finishFirstRequest!: () => void
const firstRequest = new Promise<void>(resolve => { finishFirstRequest = resolve })
await page.route("**/api/mcp/overview", async route => {
if (route.request().method() !== "GET") return route.fallback()
starts++
if (starts === 1) await firstRequest
return route.fallback()
})
const setDocumentHidden = (hidden: boolean) => page.evaluate(value => {
Object.defineProperty(document, "hidden", { configurable: true, value })
document.dispatchEvent(new Event("visibilitychange"))
}, hidden)
try {
await page.goto("/mcp?tab=overview")
await expect.poll(() => starts).toBe(1)
await setDocumentHidden(true)
const completed = page.waitForResponse(response => new URL(response.url()).pathname === "/api/mcp/overview" &&
response.request().method() === "GET" && response.ok())
finishFirstRequest()
await completed
await page.clock.runFor(11_000)
expect(starts).toBe(1)
await setDocumentHidden(false)
await expect.poll(() => starts).toBe(2)
} finally {
finishFirstRequest()
}
})
test("MCP: медленное чтение завершается без отмены очередным опросом", async ({ page }) => {
await setup(page)
let calls = 0
let release!: () => void
const pending = new Promise<void>(resolve => { release = resolve })
await page.route("**/api/mcp/overview", async route => {
calls++
await pending
await route.fulfill({ json: { connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at } })
})
await page.clock.install()
await page.goto("/mcp?tab=overview")
try {
await expect.poll(() => calls).toBeGreaterThan(0)
const initialCalls = calls
await page.clock.runFor(11_000)
expect(calls).toBe(initialCalls)
} finally {
release()
}
await expect(page.getByText("MCP включён", { exact: true })).toBeVisible()
await page.clock.runFor(5_000)
await expect.poll(() => calls).toBeGreaterThan(1)
})
test("MCP: явное обновление заменяет медленное чтение и сохраняет свежий ответ", async ({ page }) => {
await setup(page)
let calls = 0
let release!: () => void
const pending = new Promise<void>(resolve => { release = resolve })
await page.route("**/api/mcp/overview", async route => {
const current = ++calls
if (current === 1) await pending
await route.fulfill({ json: { connections: 1, calls: current === 1 ? 7 : 99, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at } })
})
await page.clock.install()
await page.goto("/mcp?tab=overview")
try {
await expect.poll(() => calls).toBe(1)
await page.evaluate(() => window.dispatchEvent(new Event("mcp-refresh")))
await expect.poll(() => calls).toBe(2)
await expect(page.getByText("99", { exact: true })).toBeVisible()
} finally {
release()
}
await page.clock.runFor(1_000)
await expect(page.getByText("99", { exact: true })).toBeVisible()
await expect(page.getByText("7", { exact: true })).toHaveCount(0)
})
test("MCP: зависшее чтение показывает ошибку и повторяется после срока ожидания", async ({ page }) => {
await setup(page)
let calls = 0
let release!: () => void
const pending = new Promise<void>(resolve => { release = resolve })
await page.route("**/api/mcp/overview", async route => {
if (++calls === 1) await pending
await route.fulfill({ json: { connections: 1, calls: 7, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at } })
})
await page.clock.install()
await page.goto("/mcp?tab=overview")
try {
await expect.poll(() => calls).toBe(1)
await page.clock.runFor(60_001)
await expect(page.getByRole("alert").filter({ hasText: "Обновление не завершилось за минуту" })).toBeVisible()
await page.clock.runFor(5_000)
await expect.poll(() => calls).toBeGreaterThan(1)
await expect(page.getByText("MCP включён", { exact: true })).toBeVisible()
await expect(page.getByRole("alert").filter({ hasText: "Обновление не завершилось за минуту" })).toHaveCount(0)
} finally {
release()
}
})
test("MCP журнал: заполненная квота объясняет удержание и показывает admin counters",async({page})=>{
await setup(page)
await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:7,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:8,limit:8,remaining:0},global:{exhausted:true,usage:{used:128,limit:128,remaining:0}},retentionDays:14}}}))
await page.goto("/mcp")
const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
await expect(capacity.getByText("8 / 8",{exact:false})).toBeVisible()
await expect(capacity.getByText("128 / 128",{exact:false})).toBeVisible()
await expect(capacity.getByRole("alert")).toContainText("Личная и общая квоты журнала заполнены")
await expect(capacity).toContainText("Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования")
await expect(capacity).toContainText("Архив сохраняет все исходные записи и продолжает занимать место")
await expect(capacity).toContainText("14 дн.")
await capacity.screenshot({path:"test-results/mcp-poll-capacity-full.png"})
})
test("MCP журнал: non-admin global usage скрыт, ошибка обновления не сохраняет зелёный статус",async({page})=>{
await setup(page)
let failed=false
await page.route("**/api/mcp/overview",route=>route.fulfill(failed?{status:503,json:{error:"Аудит временно недоступен"}}:{json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:false,usage:null},retentionDays:14}}}))
await page.goto("/mcp")
const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
await expect(capacity).toContainText("Квота не заполнена")
await expect(capacity).not.toContainText("128")
failed=true;await capacity.getByRole("button",{name:"Обновить статус"}).click()
await expect(capacity.getByRole("status")).toContainText("Свободное место не подтверждено")
await expect(capacity).not.toContainText("Квота не заполнена")
})
test("MCP журнал: на мобильном общая квота блокирует запуск при свободной личной",async({page})=>{
await setup(page);await page.setViewportSize({width:390,height:844})
await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:true,usage:null},retentionDays:14}}}))
await page.goto("/mcp")
const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
await expect(capacity.getByRole("alert")).toContainText("Общая квота журнала заполнена")
await expect(capacity).toContainText("Осталось: 7")
expect(await capacity.evaluate(element=>element.scrollWidth<=element.clientWidth)).toBe(true)
await capacity.screenshot({path:"test-results/mcp-poll-capacity-mobile.png"})
})
const routePathCheckConfig = {
name: "Проверка назначения", serverId: 1, community: "65000:10", family: "ipv4", table: "main", probeVrf: "main",
candidates: [{ id: "probe", wanInterface: "wan", downstreamInterface: "down", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "exit", expectedHops: [{ serverId: 3, interface: "exit" }] } }],
}
test("MCP: строки и курсор обращений принадлежат текущей странице и фильтру", async ({ page }) => {
await setup(page)
const secondCursor = "fa58fa40-4bcb-4616-9316-cb69463b3151"
let releaseSecond!: () => void
const holdSecond = new Promise<void>(resolve => { releaseSecond = resolve })
let failFiltered = true
await page.route(url => url.pathname === "/api/mcp/requests", async route => {
const params = new URL(route.request().url()).searchParams
const filtered = params.get("tool") === "mm_servers_list"
const cursor = params.get("cursor")
if (cursor === id) await holdSecond
if (filtered && failFiltered) return route.fulfill({ status: 503, json: { error: "Обращения временно недоступны" } })
const tool = filtered ? "mm_servers_list" : cursor === id ? "mm_logs_follow" : "mm_logs_query"
return route.fulfill({ json: { items: [{ id, tool, status: "completed", created_at: at }], total: 1, nextCursor: filtered ? null : cursor === id ? secondCursor : id } })
})
await page.goto("/mcp?tab=requests")
const next = page.getByRole("button", { name: "Далее", exact: true })
const first = page.getByText("mm_logs_query", { exact: true })
const second = page.getByText("mm_logs_follow", { exact: true })
const filtered = page.getByText("mm_servers_list", { exact: true })
const staleNotice = page.getByText("показаны ранее полученные данные", { exact: false })
const refresh = page.getByRole("button", { name: "Обновить", exact: true })
try {
await expect(first).toBeVisible()
const secondRequest = page.waitForRequest(request => {
const url = new URL(request.url())
return url.pathname === "/api/mcp/requests" && url.searchParams.get("cursor") === id
})
await next.click()
expect(new URL((await secondRequest).url()).searchParams.get("limit")).toBe("50")
await expect(first).toHaveCount(0)
await expect(next).toBeDisabled()
} finally {
releaseSecond()
}
await expect(second).toBeVisible()
await expect(next).toBeEnabled()
const filteredRequest = page.waitForRequest(request => {
const url = new URL(request.url())
return url.pathname === "/api/mcp/requests" && url.searchParams.get("tool") === "mm_servers_list"
})
await page.getByRole("textbox", { name: "Имя инструмента" }).fill("mm_servers_list")
expect(Object.fromEntries(new URL((await filteredRequest).url()).searchParams)).toEqual({ limit: "50", tool: "mm_servers_list" })
await expect(page.getByRole("alert").filter({ hasText: "Обращения временно недоступны" })).toBeVisible()
await expect(second).toHaveCount(0)
await expect(staleNotice).toHaveCount(0)
await expect(next).toBeDisabled()
failFiltered = false
await refresh.click()
await expect(filtered).toBeVisible()
failFiltered = true
await refresh.click()
await expect(staleNotice).toBeVisible()
await expect(filtered).toBeVisible()
})
test("MCP: аудит передаёт поддерживаемый фильтр пользователя и сбрасывает курсор", async ({ page }) => {
await setup(page)
const requests: Record<string, string>[] = []
await page.route(url => url.pathname === "/api/mcp/audit", route => {
const params = Object.fromEntries(new URL(route.request().url()).searchParams)
requests.push(params)
return route.fulfill({ json: { items: [{ id: "10", action: params.userId ? "audit-filtered" : "audit-initial", created_at: at }], total: 1, nextCursor: null } })
})
await page.goto(`/mcp?tab=settings&audit.connectionId=${id}&audit.cursor=11&audit.status=denied&audit.serverId=7`)
await expect(page.getByText("audit-initial", { exact: true })).toBeVisible()
expect(requests[0]).toEqual({ limit: "50", connectionId: id, cursor: "11" })
await expect(page.getByRole("textbox", { name: "Фильтр состояния" })).toHaveCount(0)
await expect(page.getByLabel("Фильтр ID сервера")).toHaveCount(0)
await page.getByLabel("Фильтр пользователя").fill("ui-admin")
await expect(page.getByText("audit-filtered", { exact: true })).toBeVisible()
expect(requests.at(-1)).toEqual({ limit: "50", connectionId: id, userId: "ui-admin" })
expect(new URL(page.url()).searchParams.has("audit.cursor")).toBe(false)
})
test("Route AI: самостоятельная проба имеет отдельное назначение и не разрешает Community", async ({ page }) => {
await setup(page)
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ headers, json: { profiles: [{ id, connection_id: id, config: routePathCheckConfig, enabled: false }] } }))
await page.route(`**/api/mcp/routing-profiles/${id}/check`, route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
return route.fulfill({ headers, json: { proofPurpose: route.request().postDataJSON().proofPurpose, status: "verified", returnPathVerified: false } })
})
await page.goto("/mcp?tab=routing")
await page.getByLabel("Профиль для проверки пути").selectOption(id)
await page.getByLabel("Проверяемый путь").selectOption("probe")
const purpose = page.getByLabel("Назначение проверки")
await expect(purpose).toHaveValue("community")
for (const value of ["community", "control-path"] as const) {
await purpose.selectOption(value)
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/api/mcp/routing-profiles/${id}/check`))
await page.getByRole("button", { name: "Проверить контрольный путь", exact: true }).click()
expect((await sent).postDataJSON()).toEqual({ candidateId: "probe", proofPurpose: value })
await expect(page.locator("pre[role=status]").filter({ hasText: '"proofPurpose"' })).toContainText(`"${value}"`)
}
await expect(page.getByText("Результат не разрешает переключение Community", { exact: false })).toBeVisible()
})
test("Route AI: смена выбора отбрасывает запоздалый результат и ошибку пробы", async ({ page }) => {
await setup(page)
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
const anotherId = "fa58fa40-4bcb-4616-9316-cb69463b3151"
const candidate = routePathCheckConfig.candidates[0]
const config = { ...routePathCheckConfig, candidates: [candidate, { ...candidate, id: "reserve", wanInterface: "wan-b", gateway: "192.0.2.2", gatewayRef: { resource: "ipv4_route", id: "*s" } }] }
await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ headers, json: { profiles: [id, anotherId].map(profileId => ({ id: profileId, config, version: 1, enabled: false })) } }))
let requestCount = 0
let release: () => void = () => {}
await page.route("**/api/mcp/routing-profiles/*/check", async route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
const request = ++requestCount
if (request < 3) await new Promise<void>(resolve => { release = resolve })
return request === 2
? route.fulfill({ status: 502, headers, json: { error: "Старая ошибка пробы" } })
: route.fulfill({ headers, json: { marker: request === 1 ? "old-proof" : "current-proof", ...route.request().postDataJSON() } })
})
await page.goto("/mcp?tab=routing")
const profile = page.getByLabel("Профиль для проверки пути")
const path = page.getByLabel("Проверяемый путь")
const purpose = page.getByLabel("Назначение проверки")
const check = page.getByRole("button", { name: "Проверить контрольный путь", exact: true })
const start = async (number: number) => {
await check.click()
await expect.poll(() => requestCount).toBe(number)
}
await profile.selectOption(id)
await path.selectOption("probe")
await start(1)
await path.selectOption("reserve")
await path.selectOption("probe")
release()
await expect(check).toBeEnabled()
await expect(page.getByText("old-proof", { exact: false })).toHaveCount(0)
await start(2)
await profile.selectOption(anotherId)
await path.selectOption("reserve")
await purpose.selectOption("control-path")
release()
await expect(check).toBeEnabled()
await expect(page.getByText("Старая ошибка пробы", { exact: false })).toHaveCount(0)
await start(3)
const result = page.locator("pre[role=status]").filter({ hasText: "current-proof" })
await expect(result).toContainText('"candidateId": "reserve"')
await expect(result).toContainText('"proofPurpose": "control-path"')
})
test("Route AI: автовосстановление блокирует активацию, но позволяет сохранить выключенный профиль", async ({ page }) => {
await setup(page)
const config = { name: "Профиль восстановления", serverId: 1, community: "65000:10", family: "ipv4", table: "main", probeVrf: "main", autoRecovery: true, candidates: [{ id: "probe", wanInterface: "wan", downstreamInterface: "down", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "exit", expectedHops: [{ serverId: 3, interface: "exit" }] } }] }
await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: true }] } }))
await page.goto("/mcp?tab=routing")
await page.getByRole("cell", { name: config.name, exact: true }).click()
await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
const dialog = page.getByRole("dialog"), save = dialog.getByRole("button", { name: "Подготовить план профиля", exact: true })
await expect(dialog.getByRole("status")).toContainText("ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE")
await expect(dialog.getByRole("status")).toContainText("подтверждённая непрерывность событий RouterOS")
await expect(save).toBeDisabled()
await dialog.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true }).uncheck()
await expect(save).toBeEnabled()
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
await save.click()
const input = (await sent).postDataJSON()
expect(input.enabled).toBe(false)
expect(input.profile.autoRecovery).toBe(true)
})
test("MCP: доступ, проверка подключения, выдача токена и состояние Route AI", async ({ page }) => {
test.setTimeout(90000)
const errors: string[] = []; page.on("pageerror", error => errors.push(error.message))
const calls = await setup(page)
await page.goto("/mcp")
await expect(page.getByRole("heading", { name: "MCP", exact: true })).toBeVisible({ timeout: 60000 })
await page.getByRole("tab", { name: "Подключения", exact: true }).click()
await expect(page.getByText("Диагностика WAN", { exact: true }).first()).toBeVisible()
await page.getByLabel("Подключение для проверки").selectOption(id)
await page.getByRole("button", { name: "Проверить готовность доступа" }).click()
await expect.poll(() => calls.includes(`POST /api/mcp/connections/${id}/check`)).toBe(true)
const readiness = page.locator("pre").filter({ hasText: "protocolProbe" })
await expect(readiness).toContainText('"protocolHandshake": true')
await expect(readiness).toContainText('"clientCredentialsVerified": false')
await expect(page.getByRole("status").filter({ hasText: "Проверочное чтение возможностей прошло." })).toBeVisible()
await page.getByRole("button", { name: "Выдать доступ", exact: true }).click()
await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
await page.getByRole("button", { name: "Далее", exact: true }).click()
await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
await page.getByRole("button", { name: "Далее", exact: true }).click()
await page.getByRole("button", { name: "Далее", exact: true }).click()
await page.getByRole("button", { name: "Сохранить доступ", exact: true }).click()
await expect(page.getByLabel("Одноразовый токен MCP")).toHaveValue("test-one-time-secret")
await page.getByRole("button", { name: "Закрыть и скрыть токен" }).click()
await expect(page.getByLabel("Одноразовый токен MCP")).toHaveCount(0)
await page.getByRole("tab", { name: "Route AI", exact: true }).click()
await expect(page.getByText("Допуск контроллера истёк", { exact: true })).toBeVisible()
await page.screenshot({ path: "test-results/mcp-route-ai.png", fullPage: true })
expect(errors).toEqual([])
})
test("MCP: временные допуски и результаты проверки привязаны к подключению", async ({ page }) => {
await setup(page)
const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3151"
const other = { ...connection, id: otherId, name: "Мониторинг LAN", policy: { ...connection.policy, id: otherId } }
let listed = [connection, other]
await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: listed } }))
let releaseOtherGrants!: () => void
let releaseIssue!: () => void
let releaseFirstCheck!: () => void
let releaseStaleCheck!: () => void
const otherGrants = new Promise<void>(resolve => { releaseOtherGrants = resolve })
const issue = new Promise<void>(resolve => { releaseIssue = resolve })
const firstCheck = new Promise<void>(resolve => { releaseFirstCheck = resolve })
const staleCheck = new Promise<void>(resolve => { releaseStaleCheck = resolve })
const grant = (id: string) => ({ id, grant: { expiresAt: at }, revoked_at: null })
await page.route(`**/api/mcp/connections/${id}/grants`, async route => {
if (route.request().method() === "GET") return route.fulfill({ json: { grants: [grant(id)] } })
await issue
return route.fulfill({ json: { token: "issued-for-wan", expiresAt: at } })
})
await page.route(`**/api/mcp/connections/${otherId}/grants`, async route => {
await otherGrants
await route.fulfill({ json: { grants: [grant(otherId)] } })
})
await page.route("**/api/mcp/grants/*", route => route.fulfill({ json: { ok: true } }))
await page.route(`**/api/mcp/connections/${id}/check`, async route => {
await firstCheck
await route.fulfill({ json: { ok: true, checks: { wan: true }, checkedAt: at } })
})
let otherChecks = 0
await page.route(`**/api/mcp/connections/${otherId}/check`, async route => {
const stale = ++otherChecks === 1
if (stale) await staleCheck
await route.fulfill({ json: { ok: true, checks: stale ? { stale: true } : { lan: true }, checkedAt: at } })
})
await page.goto("/mcp?tab=connections")
const selection = page.getByLabel("Подключение для проверки")
const revoke = page.getByRole("button", { name: "Отозвать допуск", exact: true })
const check = page.getByRole("button", { name: "Проверить готовность доступа", exact: true })
const create = page.getByRole("button", { name: "Выдать временный допуск", exact: true })
const readiness = page.locator("pre")
try {
await selection.selectOption(id)
await expect(revoke).toBeVisible()
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()])
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
await Promise.all([
page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)),
create.click(),
])
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)])
await expect(revoke).toHaveCount(0)
await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
await expect(create).toBeDisabled()
releaseOtherGrants()
await expect(revoke).toBeVisible()
const revoked = page.waitForRequest(request => request.method() === "DELETE" && request.url().includes("/api/mcp/grants/"))
await revoke.click()
expect(new URL((await revoked).url()).pathname).toBe(`/api/mcp/grants/${otherId}`)
await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/check`), check.click()])
await check.click()
await expect(readiness).toContainText('"lan": true')
const lateResponses = Promise.all([
page.waitForResponse(`**/api/mcp/connections/${id}/check`),
page.waitForResponse(`**/api/mcp/connections/${otherId}/check`),
])
releaseFirstCheck()
releaseStaleCheck()
for (const response of await lateResponses) await response.finished()
listed = [other]
releaseIssue()
const dialog = page.getByRole("dialog")
await expect(dialog).toContainText(`Подключение «${connection.name}»`)
await expect(dialog.getByLabel("Одноразовый токен MCP")).toHaveValue("issued-for-wan")
await expect(selection.locator(`option[value="${id}"]`)).toHaveCount(0)
await dialog.getByRole("button", { name: "Закрыть и скрыть токен" }).click()
await expect(selection).toHaveValue(otherId)
await expect(readiness).toContainText('"lan": true')
await expect(readiness).not.toContainText('"wan": true')
await expect(readiness).not.toContainText('"stale": true')
await expect(create).toBeEnabled()
} finally {
releaseOtherGrants()
releaseIssue()
releaseFirstCheck()
releaseStaleCheck()
}
})
test("MCP: симулятор разрешений использует область операции из каталога", async ({ page }) => {
await setup(page)
const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3158"
const capabilities = { ...operation, id: "capabilities.read", toolName: "mm_capabilities_get", title: "Доступные возможности", scope: "connection", requiredPermissions: [] }
const users = { ...operation, id: "users.list", toolName: "mm_users_list", title: "Каталог пользователей", scope: "global", requiredPermissions: ["mm:users:read"] }
const ownerPermissions = ["mm:servers:read", "mm:users:read"]
const policy = { ...connection.policy, permissions: ownerPermissions, scope: { serverIds: [1, 2], operationIds: [capabilities.id, users.id, operation.id], allowGlobal: true } } as McpPolicyPreviewRequest["policy"]
const foreign = { ...connection, ownerId: "other-owner", policy }
const other = { ...foreign, id: otherId, name: "Другой доступ", policy: { ...policy, id: otherId } }
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
await page.route("**/api/mcp/catalog", route => route.fulfill({ headers, json: { stage: "runtime", executionAvailable: true, operations: [operation, capabilities, users] } }))
await page.route("**/api/mcp/connections", route => route.fulfill({ headers, json: { connections: [foreign, other] } }))
const previews: unknown[] = [], protections: unknown[] = []
let releaseStale!: () => void
const stale = new Promise<void>(resolve => { releaseStale = resolve })
await page.route("**/api/mcp/policy/preview", async route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
const input = route.request().postDataJSON() as Pick<McpPolicyPreviewRequest, "target" | "operationId">
previews.push(input)
if (input.target.scope === "servers" && input.target.serverIds.includes(3)) await stale
const result = evaluateMcpPolicy({ operationId: input.operationId, target: input.target, policy, ownerPermissions, objects: [], protections: [], objectCount: 0, usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true })
await route.fulfill({ headers, json: { simulation: true, executionAvailable: false, evaluatedAt: at, policyVersion: 1, result } })
})
await page.route("**/api/mcp/protections", route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
if (route.request().method() === "POST") { protections.push(route.request().postDataJSON()); return route.fulfill({ headers, json: { id } }) }
return route.fulfill({ headers, json: { protections: [] } })
})
try {
await page.goto("/mcp?tab=permissions")
const selectConnection = page.getByLabel("Подключение", { exact: true })
const selectOperation = page.getByLabel("Операция", { exact: true })
const serverIds = page.getByLabel("ID серверов", { exact: true })
const preview = page.getByRole("button", { name: "Проверить", exact: true })
const allowed = page.getByText("Разрешено", { exact: true })
await selectConnection.selectOption(id)
await selectOperation.selectOption(capabilities.id)
await expect(page.getByText("Область операции — подключение")).toBeVisible()
await expect(serverIds).toHaveCount(0)
await preview.click()
await expect(allowed).toBeVisible()
expect(previews[0]).toEqual({ connectionId: id, operationId: capabilities.id, target: { scope: "connection" } })
await selectOperation.selectOption(operation.id)
await expect(allowed).toHaveCount(0)
await expect(preview).toBeDisabled()
await serverIds.fill("1,1")
await expect(preview).toBeDisabled()
await serverIds.fill("2, 1")
await preview.click()
await expect(allowed).toBeVisible()
expect(previews[1]).toEqual({ connectionId: id, operationId: operation.id, target: { scope: "servers", serverIds: [2, 1] } })
await serverIds.fill("1, 3")
await expect(allowed).toHaveCount(0)
await preview.click()
await expect.poll(() => previews.length).toBe(3)
await selectOperation.selectOption(users.id)
await expect(page.getByText("Область операции — всё приложение")).toBeVisible()
await expect(serverIds).toHaveCount(0)
await preview.click()
await expect(allowed).toBeVisible()
expect(previews[3]).toEqual({ connectionId: id, operationId: users.id, target: { scope: "global" } })
const late = page.waitForResponse(response => response.url().endsWith("/api/mcp/policy/preview") && response.request().postDataJSON().target.scope === "servers")
releaseStale()
await (await late).finished()
await expect(allowed).toBeVisible()
await expect(page.getByText("Запрещено", { exact: true })).toHaveCount(0)
await selectConnection.selectOption(otherId)
await expect(selectOperation).toHaveValue("")
await expect(allowed).toHaveCount(0)
await expect(preview).toBeDisabled()
await page.getByLabel("Тип объекта", { exact: true }).fill("ethernet")
await page.getByLabel("Стабильный ID", { exact: true }).fill("*A")
const protect = page.getByRole("button", { name: "Добавить защиту" })
await expect(protect).toBeDisabled()
await page.getByLabel("ID сервера защищаемого объекта").fill("9")
await protect.click()
await expect.poll(() => protections).toEqual([{ object: { kind: "ethernet", id: "*A", protection: "human-approval-required", serverId: 9 }, reason: "" }])
} finally { releaseStale() }
})
test("MCP: ошибки остаются видимыми, узкий экран не переполняется", async ({ page }) => {
await setup(page, true)
await page.setViewportSize({ width: 390, height: 844 })
await page.goto("/mcp")
await expect(page.getByRole("alert").filter({ hasText: "Аудит временно недоступен" })).toBeVisible()
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
})
test("Route AI: редактор создаёт план с конкретными путями и SLA", async ({ page }) => {
const calls = await setup(page)
await page.goto("/mcp?tab=routing")
await page.getByRole("button", { name: "Создать профиль", exact: true }).click()
await page.getByLabel("Подключение контроллера").selectOption(id)
await page.getByLabel("Название профиля").fill("WAN Community")
await page.getByLabel("ID домашнего сервера").fill("1")
await page.getByLabel("Community", { exact: true }).fill("65000:20")
await page.getByLabel("Таблица маршрутизации", { exact: true }).fill("customer-routes")
await page.getByLabel("VRF диагностических проб", { exact: true }).fill("probe-only")
await page.getByRole("checkbox", { name: "Привязать профиль к конкретному BGP-подключению RouterOS", exact: true }).check()
await page.getByLabel("ID BGP-подключения RouterOS", { exact: true }).fill("*A")
await page.getByLabel("Экземпляр BGP", { exact: true }).fill("edge-instance")
await page.getByLabel("Входящая цепочка BGP", { exact: true }).fill("customer-in")
await page.getByLabel("Транспортная VRF BGP", { exact: true }).fill("bgp-transport")
await expect(page.getByRole("status").filter({ hasText: "контрольную пробу с исходным адресом" })).toContainText("Профиль можно сохранить")
await page.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true }).check()
await expect(page.getByRole("button", { name: "Подготовить план профиля", exact: true })).toBeDisabled()
await page.getByLabel("WAN-интерфейс дома").fill("ether1")
await page.getByLabel("ID JumpHost").fill("2")
await page.getByLabel("ID ExitNode").fill("3")
await page.getByLabel("Интерфейс JumpHost к ExitNode").fill("gre1")
await page.getByLabel("Адрес gateway").fill("192.0.2.1")
await page.getByLabel("ID шлюза на устройстве").fill("*1")
await page.getByLabel("Максимум RTT, мс").fill("80")
await page.getByRole("checkbox", { name: "Включить контроль пути 1", exact: true }).check()
await page.getByLabel("Контрольный интерфейс ExitNode пути 1").fill("loopback")
await page.getByLabel("Исходный IP контрольной пробы пути 1").fill("192.0.2.10")
await page.getByLabel("Интерфейс hop 1 пути 1").fill("wan-in")
await page.getByLabel("Интерфейс hop 2 пути 1").fill("loopback")
await page.screenshot({ path: "test-results/mcp-route-profile-editor.png", fullPage: true })
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/routing-profiles/plan"))
await page.getByRole("button", { name: "Подготовить план профиля" }).click()
const body = (await sent).postDataJSON()
expect(body.profile.candidates[0].jumpHostId).toBe(2)
expect(body.profile.maxPingMs).toBe(80)
expect(body.profile.table).toBe("customer-routes")
expect(body.profile.probeVrf).toBe("probe-only")
expect(body.profile.bgpContext).toEqual({ connectionId: "*A", instance: "edge-instance", inputChain: "customer-in", vrf: "bgp-transport" })
expect(body.profile.candidates[0].controlProbe).toEqual({ targetInterface: "loopback", sourceAddress: "192.0.2.10", expectedHops: [{ serverId: 2, interface: "wan-in" }, { serverId: 3, interface: "loopback" }] })
expect(body.enabled).toBe(true)
await expect(page.getByText(/Создан план/)).toBeVisible()
expect(calls).toContain("POST /api/mcp/routing-profiles/plan")
})
test("Route AI: редактирование сохраняет контексты и скрытые настройки профиля", async ({ page }) => {
await setup(page)
const config = {
name: "Scoped community", serverId: 1, community: "65000:20", family: "ipv4", table: "customer-routes", probeVrf: "probe-only",
bgpContext: { connectionId: "*B", instance: "edge-instance", inputChain: "customer-in", vrf: "bgp-transport" },
pingFreshnessSec: 180, bandwidthFreshnessSec: 7200, hysteresis: 12, confirmationSamples: 4, maxSwitchesPerHour: 2,
candidates: [{ id: "edge", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3, downstreamInterface: "gre1", gateway: "192.0.2.1", gatewayRef: { resource: "gre", id: "*1" }, wanRemoteInterface: "wan-in" }],
}
await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: true }] } }))
await page.goto("/mcp?tab=routing")
await page.getByRole("cell", { name: config.name, exact: true }).click()
await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
const enableController = page.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true })
await expect(enableController).toBeChecked()
await expect(page.getByRole("button", { name: "Подготовить план профиля", exact: true })).toBeDisabled()
await enableController.uncheck()
await expect(page.getByLabel("VRF диагностических проб", { exact: true })).toHaveValue("probe-only")
await expect(page.getByLabel("Транспортная VRF BGP", { exact: true })).toHaveValue("bgp-transport")
await page.getByLabel("Название профиля", { exact: true }).fill("Renamed community")
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
const body = (await sent).postDataJSON()
expect(body.profileId).toBe(id)
expect(body.profile).toMatchObject({ ...config, name: "Renamed community" })
expect(body.enabled).toBe(false)
})
test("Route AI: неполная BGP-привязка не отправляется, снятие привязки явно удаляет контекст", async ({ page }) => {
const calls = await setup(page)
const config = { name: "BGP scope", serverId: 1, community: "65000:20", family: "ipv4", table: "main", probeVrf: "main", bgpContext: { connectionId: "*B", instance: "edge-instance", inputChain: "bgp-in", vrf: "main" }, candidates: [{ id: "edge", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3, downstreamInterface: "gre1", gateway: "192.0.2.1", gatewayRef: { resource: "gre", id: "*1" } }] }
await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: false }] } }))
await page.goto("/mcp?tab=routing")
await page.getByRole("cell", { name: config.name, exact: true }).click()
await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
await page.getByLabel("Экземпляр BGP", { exact: true }).fill("")
await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
await expect(page.getByRole("dialog").getByRole("alert")).toBeVisible()
expect(calls.filter(call => call === "POST /api/mcp/routing-profiles/plan")).toHaveLength(0)
await page.getByRole("checkbox", { name: "Привязать профиль к конкретному BGP-подключению RouterOS", exact: true }).uncheck()
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
const body = (await sent).postDataJSON()
expect(body.profile).not.toHaveProperty("bgpContext")
expect(body.profile.probeVrf).toBe("main")
expect(body.enabled).toBe(false)
})
test("MCP: независимое управление скрывает пароль после регистрации", async ({ page }) => {
await setup(page)
await page.goto("/mcp?tab=settings")
await expect(page.getByText("/api/geoip/update", { exact: true })).toBeVisible()
await expect(page.getByText("Ожидают реализации: 1", { exact: true })).toBeVisible()
await page.getByLabel("ID сервера независимого канала").fill("1")
await page.getByLabel("IP независимого управления").fill("192.0.2.25")
await page.getByLabel("Пользователь независимого канала").fill("lab")
await page.getByLabel("Пароль независимого канала").fill("fixture-no-real-secret")
await page.getByLabel("Подтверждение независимости пути").fill("Отдельный management-интерфейс и отдельная сеть лабораторного стенда")
const request = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/management-channels"))
await page.getByRole("button", { name: "Проверить и зарегистрировать канал" }).click()
expect((await request).postDataJSON().verifySsl).toBe(true)
await expect(page.getByLabel("Пароль независимого канала")).toHaveValue("")
})
test("MCP: восстановление создаёт отдельный план без автоматического применения", async ({ page }) => {
const calls = await setup(page)
const maliciousTarget = "../plans/another/apply"
await page.goto(`/mcp?${new URLSearchParams({ tab: "plans", reconcile: maliciousTarget })}`)
await expect(page.getByLabel("ID исходной операции")).toHaveValue(maliciousTarget)
await expect(page.getByRole("button", { name: "Сверить состояние операции" })).toBeDisabled()
await expect(page.getByRole("button", { name: "Подготовить обратный план" })).toBeDisabled()
await page.getByLabel("ID исходной операции").fill(id)
await page.getByRole("button", { name: "Подготовить обратный план" }).click()
await expect(page.getByRole("status").filter({ hasText: "awaiting-approval" })).toBeVisible()
expect(calls.filter(call => call.endsWith("/apply"))).toEqual([])
})
test("MCP: фильтры обращений сохраняются в URL и применяются сервером", async ({ page }) => {
await setup(page)
await page.goto("/mcp?tab=requests&requests.tool=mm_logs_query&requests.serverId=1")
await expect(page.getByLabel("Имя инструмента")).toHaveValue("mm_logs_query")
await expect(page.getByLabel("Фильтр ID сервера")).toHaveValue("1")
const filtered = page.waitForRequest(request => { const url = new URL(request.url()); return url.pathname === "/api/mcp/requests" && url.searchParams.get("userId") === "ui-admin" && url.searchParams.get("serverId") === "1" && url.searchParams.get("tool") === "mm_logs_query" })
await page.getByLabel("Фильтр пользователя").fill("ui-admin")
await filtered
expect(new URL(page.url()).searchParams.get("requests.userId")).toBe("ui-admin")
await page.reload()
await expect(page.getByLabel("Фильтр пользователя")).toHaveValue("ui-admin")
})
test("MCP: файл операции скачивается с JWT, безопасным путём и освобождением Blob URL", async ({ page }) => {
await setup(page)
const artifactPath = `/api/mcp/artifacts/${id}`
const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type", "access-control-expose-headers": "Content-Disposition" }
let downloads = 0
await page.addInitScript(() => {
const original = URL.revokeObjectURL
Object.assign(window, { artifactUrlRevoked: false })
URL.revokeObjectURL = url => { Object.assign(window, { artifactUrlRevoked: true }); original(url) }
})
await page.route("**/api/mcp/operations?*", route => route.fulfill({ headers, json: { items: [{ id, connection_id: id, state: "applied", artifactReceipts: [
{ artifactId: id, humanDownloadOnly: true, downloadPath: artifactPath },
{ artifactId: id, humanDownloadOnly: true, downloadPath: "https://unsafe.example/private" },
{ artifactId: "../unsafe", humanDownloadOnly: true },
] }], total: 1, nextCursor: null } }))
await page.route(`**${artifactPath}`, async route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
downloads++
expect(route.request().headers().authorization).toMatch(/^Bearer header\./)
await new Promise(resolve => setTimeout(resolve, 250))
return route.fulfill({ body: Buffer.from([0, 255, 128, 1]), headers: { ...headers, "content-type": "application/octet-stream", "content-disposition": 'attachment; filename="backup.rsc"' } })
})
await page.goto("/mcp?tab=plans")
const operations = page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) })
await operations.getByRole("button", { name: "Открыть", exact: true }).click()
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("heading", { name: "Детали операции", exact: true })).toBeVisible()
await expect(dialog.getByRole("button", { name: "Скачать файл", exact: true })).toHaveCount(1)
const downloaded = page.waitForEvent("download")
await dialog.getByRole("button", { name: "Скачать файл", exact: true }).click()
await expect(dialog.getByRole("button", { name: "Скачивание…", exact: true })).toBeDisabled()
expect((await downloaded).suggestedFilename()).toBe("backup.rsc")
await expect(dialog.getByRole("status")).toContainText("Файл передан браузеру")
await expect.poll(() => page.evaluate(() => Reflect.get(window, "artifactUrlRevoked"))).toBe(true)
expect(downloads).toBe(1)
expect(new URL(page.url()).pathname).toBe("/mcp")
})
test("MCP: квитанция backup БД скачивает dump через общий путь артефактов", async ({ page }) => {
await setup(page)
const artifactPath = `/api/mcp/artifacts/${id}`
const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type", "access-control-expose-headers": "Content-Disposition" }
await page.route("**/api/mcp/operations?*", route => route.fulfill({ json: { items: [{ id, connection_id: id, operationId: "database.backup", state: "applied", databaseContentReturned: false, artifactReceipts: [{ artifactId: id, humanDownloadOnly: true, downloadPath: artifactPath }] }], total: 1, nextCursor: null } }))
await page.route(`**${artifactPath}`, route => {
if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
return route.fulfill({ body: Buffer.from("PGDMPfixture"), headers: { ...headers, "content-type": "application/octet-stream", "content-disposition": 'attachment; filename="mmapp-database.dump"' } })
})
await page.goto("/mcp?tab=plans")
await page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) }).getByRole("button", { name: "Открыть", exact: true }).click()
const dialog = page.getByRole("dialog")
await expect(dialog).toContainText('"databaseContentReturned": false')
const downloaded = page.waitForEvent("download")
await dialog.getByRole("button", { name: "Скачать файл", exact: true }).click()
expect((await downloaded).suggestedFilename()).toBe("mmapp-database.dump")
await expect(dialog.getByRole("status")).toContainText("Файл передан браузеру")
})
test("MCP: ошибки файла скрывают тело ответа; без JWT скачивание не начинается", async ({ page }) => {
await setup(page)
let status = 403, requests = 0, downloads = 0
page.on("download", () => { downloads++ })
const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type" }
await page.route("**/api/mcp/operations?*", route => route.fulfill({ headers, json: { items: [{ id, connection_id: id, state: "applied", artifactReceipts: [{ artifactId: id, humanDownloadOnly: true }] }], total: 1, nextCursor: null } }))
await page.route(`**/api/mcp/artifacts/${id}`, route => { if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers }); requests++; return route.fulfill({ status, headers, json: { error: "NEVER_RENDER_PROVIDER_SECRET" } }) })
await page.goto("/mcp?tab=plans")
await page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) }).getByRole("button", { name: "Открыть", exact: true }).click()
const dialog = page.getByRole("dialog"), button = dialog.getByRole("button", { name: "Скачать файл", exact: true })
await expect(dialog.getByRole("status")).toHaveText("Доступ и срок хранения проверяются при скачивании.")
for (const [code, message] of [[403, "Доступ к файлу отозван"], [404, "срок хранения истёк"], [409, "Файл изменился"], [410, "срок хранения истёк"]] as const) {
status = code
await button.click()
await expect(dialog.getByRole("alert")).toContainText(message)
await expect(dialog.getByRole("status")).toBeEmpty()
await expect(dialog).not.toContainText("NEVER_RENDER_PROVIDER_SECRET")
await expect(button).toBeEnabled()
}
await page.evaluate(() => localStorage.removeItem("mmapp_token"))
await button.click()
await expect(dialog.getByRole("alert")).toContainText("Войдите в портал")
await expect(dialog.getByRole("status")).toBeEmpty()
expect(requests).toBe(4)
expect(downloads).toBe(0)
})
test("MCP: выгрузка проверяет SHA-256 и показывает исчезновение квитанции", async ({ page }) => {
const calls = await setup(page)
const payload = Buffer.from("PGDMP")
const artifactPath = `/api/mcp/artifacts/${id}`
const receipt = { artifactId: id, humanDownloadOnly: true, bytes: payload.length, sha256: createHash("sha256").update(payload).digest("hex") }
const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type" }
let visible = true, payloadMatches = false, downloadCount = 0
page.on("download", () => { downloadCount++ })
await page.route("**/api/mcp/operations?*", route => route.fulfill({ json: {
items: [{ id, connection_id: id, state: "applied", artifactReceipts: visible ? [receipt] : [] }], total: 1, nextCursor: null,
} }))
await page.route(`**${artifactPath}`, route => route.request().method() === "OPTIONS" ? route.fulfill({ status: 204, headers }) :
route.fulfill({ headers, body: payloadMatches ? payload : Buffer.from("OTHER") }))
await page.goto(`/mcp?tab=plans&operation=${id}`)
const dialog = page.getByRole("dialog")
const save = dialog.getByRole("button", { name: "Скачать файл", exact: true })
await save.click()
await expect(dialog.getByRole("alert")).toContainText("Файл изменился")
expect(downloadCount).toBe(0)
payloadMatches = true
const downloaded = page.waitForEvent("download")
await save.click()
await downloaded
expect(downloadCount).toBe(1)
visible = false
await dialog.getByRole("button", { name: "Обновить выполнение" }).click()
await expect(dialog.getByRole("status")).toContainText("Файл больше недоступен")
await expect(save).toHaveCount(0)
expect(calls.filter(call => call.startsWith("POST") && call.endsWith("/apply"))).toEqual([])
})
test("MCP: изменение интерфейса готовит план только с изменёнными свойствами", async ({ page }) => {
await setup(page)
await page.goto("/mcp?tab=devices")
await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
await page.getByLabel("Сервер интерфейсов").selectOption("1")
await page.getByLabel("Тип объектов устройства").selectOption("bridge")
await page.getByText("lab-bridge", { exact: true }).click()
await page.getByRole("textbox", { name: "comment", exact: true }).fill("reviewed change")
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/devices/1/bridge/plan"))
await page.getByRole("button", { name: "Подготовить план изменения", exact: true }).click()
expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*A", fields: { comment: "reviewed change" } })
await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
await page.screenshot({ path: "test-results/mcp-device-editor.png", fullPage: true })
})
test("MCP: можно добавить первый комментарий интерфейса без подстановки остальных свойств", async ({ page }) => {
await setup(page)
await page.route("**/api/mcp/devices/1/bridge?*", route => route.fulfill({ json: {
items: [{ ".id": "*A", name: "lab-bridge", disabled: "true" }], total: 1, nextOffset: null,
} }))
await page.goto("/mcp?tab=devices")
await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
await page.getByLabel("Сервер интерфейсов").selectOption("1")
await page.getByLabel("Тип объектов устройства").selectOption("bridge")
await page.getByText("lab-bridge", { exact: true }).click()
await page.getByRole("textbox", { name: "comment", exact: true }).fill("first comment")
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/devices/1/bridge/plan"))
await page.getByRole("button", { name: "Подготовить план изменения", exact: true }).click()
expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*A", fields: { comment: "first comment" } })
await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
})
test("MCP: Ethernet допускает явное изменение неизвестного disabled", async ({ page }) => {
await setup(page)
await page.route("**/api/mcp/devices/catalog?*", route => route.fulfill({ json: {
servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }],
resources: [{ id: "ethernet", title: "Ethernet", read: true, create: false, update: true, delete: false, fields: [
{ key: "name", type: "string", requiredOnCreate: false },
{ key: "disabled", type: "boolean", requiredOnCreate: false },
{ key: "auto-negotiation", type: "boolean", requiredOnCreate: false },
] }],
} }))
await page.route("**/api/mcp/devices/1/ethernet?*", route => route.fulfill({ json: {
items: [{ ".id": "*E", name: "lab-ethernet", running: "true" }], total: 1, nextOffset: null,
} }))
await page.route("**/api/mcp/devices/1/ethernet/plan", route => route.fulfill({ json: { planId: id, state: "awaiting-approval" } }))
await page.goto("/mcp?tab=devices")
await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
await page.getByLabel("Сервер интерфейсов").selectOption("1")
await page.getByLabel("Тип объектов устройства").selectOption("ethernet")
await page.getByText("lab-ethernet", { exact: true }).click()
const disabled = page.getByRole("combobox", { name: "disabled", exact: true })
const prepare = page.getByRole("button", { name: "Подготовить план изменения", exact: true })
const warning = page.getByText("Исходное состояние неизвестно. Для этого изменения обратный план недоступен.")
await expect(disabled.locator("option:checked")).toHaveText("Текущее значение неизвестно")
await expect(disabled).toHaveValue("")
await expect(prepare).toBeDisabled()
await expect(page.getByRole("combobox", { name: "auto-negotiation", exact: true })).toHaveCount(0)
await disabled.selectOption("false")
await expect(prepare).toBeEnabled()
await expect(warning).toBeVisible()
await disabled.selectOption("")
await expect(prepare).toBeDisabled()
await expect(warning).toHaveCount(0)
await disabled.selectOption("true")
const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/devices/1/ethernet/plan"))
await prepare.click()
expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*E", fields: { disabled: true } })
await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
})
test("MCP: архив БД загружает человек, подготовка плана не запускает restore", async ({ page }) => {
const calls = await setup(page)
await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: [{ ...connection, policy: { ...connection.policy, permissions: ["mm:settings:admin"], scope: { serverIds: [1], operationIds: ["database.restore"], allowGlobal: true } } }] } }))
await page.route("**/api/mcp/database/**", route => {
calls.push(route.request().method() + " " + new URL(route.request().url()).pathname)
if (route.request().url().endsWith("/archives")) return route.fulfill({ json: { archiveRef: id, sha256: "a".repeat(64), sizeBytes: 12, expiresAt: "2099-01-01T00:00:00Z" } })
if (route.request().url().endsWith("/plan")) return route.fulfill({ json: { planId: id, state: "awaiting-approval" } })
return route.fulfill({ json: { operationId: id, state: "applied", accessRevoked: true, automaticRetry: false } })
})
await page.goto("/mcp?tab=settings")
await page.getByLabel("Подключение для восстановления").selectOption(id)
await page.getByLabel("Архив PostgreSQL, до 64 МиБ").setInputFiles({ name: "test.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMPfixture") })
const uploaded = page.waitForRequest(request => request.url().endsWith("/api/mcp/database/archives"))
await page.getByRole("button", { name: "Загрузить архив", exact: true }).click()
expect((await uploaded).headers()["content-type"]).toBe("application/octet-stream")
await expect(page.getByRole("button", { name: "Подготовить план восстановления БД" })).toBeEnabled()
const plan = page.waitForRequest(request => request.url().endsWith("/api/mcp/database/plan"))
await page.getByRole("button", { name: "Подготовить план восстановления БД" }).click()
expect((await plan).postDataJSON()).toEqual({ connectionId: id, archiveRef: id, expectedSha256: "a".repeat(64) })
await expect(page.getByRole("status").filter({ hasText: "awaiting-approval" })).toBeVisible()
expect(calls.some(call => call.endsWith("/apply"))).toBe(false)
await page.getByLabel("ID операции восстановления БД").fill(id)
await page.getByRole("button", { name: "Прочитать внешнюю квитанцию" }).click()
await expect(page.getByRole("status").filter({ hasText: '"accessRevoked": true' })).toBeVisible()
})
test("MCP: архив восстановления привязан к выбранному файлу и блокируется по истечении срока", async ({ page }) => {
const calls = await setup(page)
const start = new Date("2026-11-15T03:00:00Z")
await page.clock.install({ time: start })
const secondId = "fa58fa40-4bcb-4616-9316-cb69463b3158"
const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3159"
const policy = { ...connection.policy, permissions: ["mm:settings:admin"], scope: { serverIds: [], operationIds: ["database.restore"], allowGlobal: true } }
await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: [
{ ...connection, policy }, { ...connection, id: secondId, policy: { ...policy, id: secondId }, name: "Резервный допуск" },
{ ...connection, id: otherId, policy: { ...policy, id: otherId }, ownerId: "other", name: "Чужой допуск" },
] } }))
let releaseUpload!: () => void
const heldUpload = new Promise<void>(resolve => { releaseUpload = resolve })
const plans: unknown[] = []
let uploads = 0
await page.route("**/api/mcp/database/archives", async route => {
const first = ++uploads === 1
if (first) await heldUpload
await route.fulfill({ json: { archiveRef: id, sha256: "a".repeat(64), sizeBytes: first ? 999 : 5, expiresAt: new Date(start.getTime() + 60_000).toISOString() } })
})
await page.route("**/api/mcp/database/plan", route => {
plans.push(route.request().postDataJSON())
return route.fulfill({ json: { planId: id, state: "awaiting-approval" } })
})
await page.goto("/mcp?tab=settings")
const section = page.getByRole("region", { name: "Восстановление БД через MCP" })
const selector = section.getByLabel("Подключение для восстановления")
const file = section.getByLabel("Архив PostgreSQL, до 64 МиБ")
const upload = section.getByRole("button", { name: "Загрузить архив" })
const prepare = section.getByRole("button", { name: "Подготовить план восстановления БД" })
await selector.selectOption(id)
await expect(selector.getByRole("option", { name: "Чужой допуск" })).toHaveCount(0)
await file.setInputFiles({ name: "first.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMP") })
try {
await upload.click()
await expect(selector).toBeDisabled()
await expect(file).toBeDisabled()
await expect(prepare).toBeDisabled()
} finally { releaseUpload() }
await expect(section.getByRole("alert")).toContainText("Размер загруженного архива не совпадает")
await expect(prepare).toBeDisabled()
await file.setInputFiles({ name: "another.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMP") })
await upload.click()
await expect(prepare).toBeEnabled()
await prepare.click()
await expect(section.getByRole("status")).toContainText("awaiting-approval")
await selector.selectOption(secondId)
await expect(section.getByRole("status")).toHaveCount(0)
await expect(prepare).toBeEnabled()
await page.clock.fastForward(61_000)
await expect(section.getByRole("status")).toContainText("Срок архива истёк")
await expect(prepare).toBeDisabled()
expect(plans).toEqual([{ connectionId: id, archiveRef: id, expectedSha256: "a".repeat(64) }])
expect(uploads).toBe(2)
expect(calls.filter(call => call.startsWith("POST") && call.endsWith("/apply"))).toEqual([])
})
test("MCP: обзор плана показывает исходное состояние, зависимости и шаги до подтверждения", async ({ page }) => {
await setup(page)
await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: { items: [{ id, operationId: "routing.community.switch", state: "awaiting-approval", createdAt: at, expiresAt: "2099-01-01T00:00:00Z", changes: { target: { scope: "servers", serverIds: [1, 2] }, objects: [{ kind: "gre", id: "*A", serverId: 1 }], before: { gateway: "192.0.2.1" }, steps: [{ kind: "service", service: "routing.community", input: { gateway: "192.0.2.2" } }], warnings: ["Изменится gateway выбранного Community"] } }], total: 1, nextCursor: null } }))
await page.goto("/mcp?tab=plans")
await page.getByText("routing.community.switch", { exact: true }).click()
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("heading", { name: "Исходное состояние" })).toBeVisible()
await expect(dialog.getByRole("heading", { name: "Запланированные шаги" })).toBeVisible()
await expect(dialog.getByText("Изменится gateway выбранного Community", { exact: true })).toBeVisible()
await expect(dialog.getByText("Серверы: 1, 2", { exact: true })).toBeVisible()
await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeVisible()
await dialog.screenshot({ path: "test-results/mcp-plan-review.png" })
})
test("MCP: права, аудит и ход операции связаны с выбранным подключением", async ({ page }) => {
const calls = await setup(page)
const operationId = "fa58fa40-4bcb-4616-9316-cb69463b3159"
const plan = { id, connectionId: id, operationId: "routing.profiles.save", state: "awaiting-approval", createdAt: at,
expiresAt: "2099-01-01T00:00:00Z", changes: { target: { scope: "servers", serverIds: [1] }, warnings: ["Изменится профиль WAN"] } }
const records = (items: unknown[]) => ({ items, total: items.length, nextCursor: null })
let outcome = "running"
await page.route(url => url.pathname === "/api/mcp/policy/preview", async route => {
expect(route.request().postDataJSON()).toMatchObject({ connectionId: id, operationId: operation.id, target: { scope: "servers", serverIds: [2] } })
await route.fulfill({ json: { simulation: true, executionAvailable: false, evaluatedAt: at, policyVersion: 1,
result: { decision: "denied", reasons: [{ code: "SERVER_DENIED", message: "Сервер 2 вне области доступа" }], limits: connection.policy.limits } } })
})
await page.route(url => url.pathname === "/api/mcp/requests" && url.searchParams.has("connectionId"), route => route.fulfill({
json: records([{ id, connection_id: id, tool: "mm_logs_query", status: "denied", error_code: "SERVER_DENIED", created_at: at }]),
}))
await page.route(url => url.pathname === "/api/mcp/audit" && url.searchParams.has("connectionId"), route => route.fulfill({
json: records([{ id: 1, connection_id: id, action: "connection.create", created_at: at }]),
}))
await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: records([plan]) }))
const decisions: unknown[] = [], applications: unknown[] = [], reconciliations: unknown[] = []
await page.route(`**/api/mcp/plans/${id}/decision`, async route => {
decisions.push(route.request().postDataJSON())
plan.state = "approved"
await route.fulfill({ json: { ok: true } })
})
await page.route(`**/api/mcp/plans/${id}/apply`, async route => {
applications.push(route.request().postDataJSON())
plan.state = "applied"
await route.fulfill({ json: { id: operationId, state: "pending" } })
})
await page.route(url => url.pathname === "/api/mcp/operations", route => {
const params = new URL(route.request().url()).searchParams
if (params.get("operationId") === operationId) {
expect(Object.fromEntries(params)).toEqual({ operationId, limit: "1" })
return route.fulfill({ json: records([{ id: operationId, state: outcome, steps: [{ step_index: 0, server_id: 1, state: "verified" }] }]) })
}
return route.fulfill({ json: records([]) })
})
await page.route(`**/api/mcp/operations/${operationId}/reconcile`, async route => {
reconciliations.push(route.request().postDataJSON())
await route.fulfill({ json: { operationId, state: "partial", automaticRetry: false } })
})
await page.goto("/mcp?tab=connections")
await page.getByRole("link", { name: "Проверить права", exact: true }).click()
await expect(page.getByLabel("Подключение", { exact: true })).toHaveValue(id)
await page.getByLabel("Операция", { exact: true }).selectOption(operation.id)
await page.getByLabel("ID серверов", { exact: true }).fill("2")
await page.getByRole("button", { name: "Проверить", exact: true }).click()
await expect(page.getByText("Сервер 2 вне области доступа", { exact: false })).toBeVisible()
await page.getByRole("link", { name: "Открыть обращения подключения" }).click()
await expect(page.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
await expect(page.getByRole("cell", { name: "SERVER_DENIED", exact: true })).toBeVisible()
await page.getByRole("link", { name: "Административный аудит подключения" }).click()
await expect(page.getByRole("cell", { name: "connection.create", exact: true })).toBeVisible()
await page.goBack()
await page.getByRole("link", { name: "Планы и операции подключения" }).click()
const operationsPanel = page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) })
const plansPanel = page.locator("[data-slot=frame]").filter({ has: page.getByText("Планы изменений", { exact: true }) })
await expect(plansPanel.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
await expect(operationsPanel.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
await operationsPanel.getByLabel("Фильтр состояния").fill("running")
const dialog = page.getByRole("dialog")
await page.getByText(plan.operationId, { exact: true }).click()
await expect(dialog).toContainText("Изменится профиль WAN")
await dialog.getByRole("button", { name: "Подтвердить план", exact: true }).click()
await expect(dialog).toHaveCount(0)
await expect(plansPanel.getByText("approved", { exact: true })).toBeVisible()
await page.getByText(plan.operationId, { exact: true }).click()
await dialog.getByRole("button", { name: "Применить план", exact: true }).click()
await page.getByRole("link", { name: "Открыть выполнение операции" }).click()
await expect(dialog.getByText("Выполняется", { exact: true })).toBeVisible()
outcome = "partial"
await dialog.getByRole("button", { name: "Обновить выполнение" }).click()
await expect(dialog.getByText("Выполнена частично", { exact: true })).toBeVisible()
await expect(dialog.getByRole("region", { name: "Шаги выполнения" })).toContainText("Результат проверен · сервер 1")
await dialog.getByRole("link", { name: "Перейти к сверке" }).click()
await expect(dialog).toHaveCount(0)
await expect(page.getByLabel("ID исходной операции")).toHaveValue(operationId)
expect(reconciliations).toEqual([])
await page.getByRole("button", { name: "Сверить состояние операции" }).click()
await expect(page.getByText('"automaticRetry": false', { exact: false })).toBeVisible()
expect(decisions).toEqual([{ approve: true }])
expect(applications).toEqual([{}])
expect(reconciliations).toEqual([{}])
expect(calls).not.toContain(`POST /api/mcp/operations/${operationId}/recover`)
})
test("MCP: открытый обратный план блокирует подтверждение после истечения срока", async ({ page }) => {
await setup(page)
const now = new Date("2026-11-14T09:00:00Z")
await page.clock.install({ time: new Date(now.getTime() - 1000) })
await page.clock.pauseAt(now)
const expiresAt = new Date(now.getTime() + 60_000).toISOString()
const plan = { id, operationId: "operations.recover", state: "awaiting-approval", createdAt: at, expiresAt, changes: {} }
await page.route(url => url.pathname === "/api/mcp/plans", route =>
route.fulfill({ json: { items: [plan], total: 1, nextCursor: null } }))
const writes: string[] = []
page.on("request", request => {
if (request.method() === "POST" && new URL(request.url()).pathname.startsWith("/api/mcp/plans/")) writes.push(request.url())
})
await page.goto("/mcp?tab=plans")
await page.getByText("operations.recover", { exact: true }).click()
const dialog = page.getByRole("dialog")
const approve = dialog.getByRole("button", { name: "Подтвердить план", exact: true })
await expect(approve).toBeEnabled()
await page.clock.fastForward(60_001)
await expect(dialog.getByText("Срок плана истёк. Подготовьте новый план.", { exact: true })).toBeVisible()
await expect(approve).toBeDisabled()
await expect(dialog.getByRole("button", { name: "Отклонить", exact: true })).toBeDisabled()
await approve.press("Enter")
expect(writes).toEqual([])
})
test("MCP: запоздалое решение не закрывает другой план и повторная отправка блокируется", async ({ page }) => {
await setup(page)
const secondId = "fa58fa40-4bcb-4616-9316-cb69463b3199"
const first = { id, operationId: "routing.community.switch", state: "awaiting-approval", createdAt: at, expiresAt: "2099-01-01T00:00:00Z", changes: {} }
const second = { ...first, id: secondId, operationId: "ros.ethernet.update", state: "approved" }
let finishDecision!: () => void
let finishApply!: () => void
const decisionGate = new Promise<void>(resolve => { finishDecision = resolve })
const applyGate = new Promise<void>(resolve => { finishApply = resolve })
const decisions: unknown[] = []
const applications: unknown[] = []
await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: { items: [first, second], total: 2, nextCursor: null } }))
await page.route(`**/api/mcp/plans/${id}/decision`, async route => {
decisions.push(route.request().postDataJSON())
await decisionGate
first.state = "approved"
await route.fulfill({ json: { ok: true } })
})
await page.route(`**/api/mcp/plans/${secondId}/apply`, async route => {
applications.push(route.request().postDataJSON())
await applyGate
await route.fulfill({ json: { id: secondId, state: "pending" } })
})
try {
await page.goto("/mcp?tab=plans")
await page.getByText(first.operationId, { exact: true }).click()
const dialog = page.getByRole("dialog")
await dialog.getByRole("button", { name: "Подтвердить план", exact: true }).click()
await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeDisabled()
await expect(dialog.getByRole("button", { name: "Отклонить", exact: true })).toBeDisabled()
await page.keyboard.press("Escape")
await expect(dialog).toHaveCount(0)
await page.getByText(first.operationId, { exact: true }).click()
await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeDisabled()
await page.keyboard.press("Escape")
await expect(dialog).toHaveCount(0)
await page.getByText(second.operationId, { exact: true }).click()
const apply = dialog.getByRole("button", { name: "Применить план", exact: true })
await expect(apply).toBeEnabled()
const decisionResponse = page.waitForResponse(response => response.url().endsWith(`/plans/${id}/decision`))
const refreshed = page.waitForResponse(response => new URL(response.url()).pathname === "/api/mcp/plans" && response.json().then(payload => payload.items?.some((item: { id: string; state: string }) => item.id === id && item.state === "approved")))
finishDecision()
await decisionResponse
await refreshed
await expect(apply).toBeEnabled()
expect(decisions).toEqual([{ approve: true }])
await apply.click()
await expect(apply).toBeDisabled()
await expect.poll(() => applications).toEqual([{}])
finishApply()
await expect(dialog).toHaveCount(0)
expect(applications).toEqual([{}])
} finally {
finishDecision()
finishApply()
}
})