From 4d5ef6bed0f8bfcab6aa1ee646f48c99003bf538 Mon Sep 17 00:00:00 2001 From: busya Date: Sat, 5 Sep 2026 20:16:26 +0300 Subject: [PATCH] feat: dashboard-testing UX remediation + admin MCP governance + i18n sweep - UX audit Fix 1-5: actionable MCP HandoffSurface (endpoint/discovery/onboarding), reachable approval loop (sidebar section + waiting-for-me badge), honest MCP entry labels, ROUTES SSOT for dashboard-testing/load-testing (+ link-integrity coverage) - scenario registry hub (/dashboard-testing/scenarios) built on ScenarioRegistryModel - admin MCP governance: read-only GET /api/admin/mcp/catalog (catalog x roles + DCR clients) + /admin/mcp page/model/api + ROUTES.admin.mcp + sidebar entry - full i18n sweep of dashboard-testing routes and scenario-* component trees (ru/en) - accumulated workspace: MCP OAuth/DCR, automation idempotency migration, docker/nginx, specs --- .../versions/0018_automation_idempotency.py | 34 +++ backend/src/api/mcp_oauth.py | 102 ++++++- backend/src/api/routes/admin_mcp.py | 160 +++++++++++ backend/src/app.py | 26 +- backend/src/core/config_models.py | 15 + backend/src/mcp_server/rbac_server.py | 10 + backend/src/mcp_server/scenario_inputs.py | 17 ++ backend/src/mcp_server/server.py | 11 +- backend/src/mcp_server/tools_authoring.py | 58 ++++ backend/src/mcp_server/tools_automation.py | 217 ++++++++++++++ backend/src/models/scenario_automation.py | 6 + .../dashboard_testing/registry/create.py | 47 +++ backend/src/services/mcp_oauth.py | 72 ++++- backend/tests/api/test_admin_mcp_catalog.py | 206 ++++++++++++++ backend/tests/test_app_middleware.py | 24 ++ backend/tests/test_mcp_client_flow_http.py | 18 +- backend/tests/test_mcp_oauth.py | 34 +++ .../test_mcp_t029_bootstrap_automation.py | 141 +++++++++ build.sh | 7 +- docker-compose.enterprise-clean.yml | 6 +- docker-compose.yml | 6 +- docker/nginx.conf | 19 +- docker/nginx.ssl.conf | 18 +- docs/2026-09-05-ss-tools-mcp-tool-audit.md | 77 +++++ .../__tests__/routes-link-integrity.test.ts | 17 ++ frontend/src/lib/__tests__/routes.test.ts | 41 +++ frontend/src/lib/api.ts | 14 + .../components/agent/HandoffSurface.svelte | 109 ++++++- .../__tests__/handoff-surface.context.test.ts | 23 ++ .../src/lib/components/layout/Sidebar.svelte | 51 +++- .../lib/components/layout/TopNavbar.svelte | 8 +- .../__tests__/sidebarNavigation.test.ts | 51 ++++ .../components/layout/sidebarNavigation.ts | 18 ++ .../AgentActionTimeline.svelte | 11 +- .../scenario-analytics/CaseWorkspace.svelte | 52 ++-- .../scenario-analytics/HealthCard.svelte | 13 +- .../scenario-analytics/QueueList.svelte | 19 +- .../RecurringFailuresList.svelte | 17 +- .../scenario-analytics/TrendsChart.svelte | 23 +- .../__tests__/CaseWorkspace.test.ts | 12 +- .../AutomationPanel.svelte | 45 +-- .../scenario-automation/ScheduleForm.svelte | 5 +- .../scenario-editor/AgentActionPanel.svelte | 55 ++-- .../ConstrainedAssertionEditor.svelte | 26 +- .../scenario-editor/EditRevisionDiff.svelte | 11 +- .../scenario-editor/VisualDagCanvas.svelte | 20 +- .../scenario-run/HumanCheckpointPanel.svelte | 22 +- .../scenario-run/RunComparison.svelte | 13 +- .../scenario-run/RunConfigurationPanel.svelte | 75 ++--- .../scenario-run/RunHistoryList.svelte | 15 +- .../scenario-run/RunTimeline.svelte | 16 +- .../scenario-run/ScenarioResultView.svelte | 17 +- .../scenario-run/WaitingForMeView.svelte | 27 +- frontend/src/lib/i18n/locales/en/admin.json | 45 +++ .../src/lib/i18n/locales/en/assistant.json | 14 +- .../i18n/locales/en/dashboard-testing.json | 269 +++++++++++++++++- frontend/src/lib/i18n/locales/en/nav.json | 10 +- frontend/src/lib/i18n/locales/ru/admin.json | 45 +++ .../src/lib/i18n/locales/ru/assistant.json | 14 +- .../i18n/locales/ru/dashboard-testing.json | 269 +++++++++++++++++- frontend/src/lib/i18n/locales/ru/nav.json | 10 +- .../lib/models/AdminMcpCatalogModel.svelte.ts | 75 +++++ .../models/InvestigationCaseModel.svelte.ts | 23 +- .../src/lib/models/RunMonitorModel.svelte.ts | 47 ++- .../__tests__/AdminMcpCatalogModel.test.ts | 50 ++++ frontend/src/lib/routes.ts | 32 ++- .../lib/stores/__tests__/test_scenarioRuns.ts | 146 ++++++++++ .../src/lib/stores/scenarioRuns.svelte.ts | 85 ++++++ frontend/src/routes/+layout.svelte | 2 +- frontend/src/routes/admin/+page.svelte | 6 + .../routes/admin/__tests__/admin-mcp.test.ts | 135 +++++++++ frontend/src/routes/admin/mcp/+page.svelte | 208 ++++++++++++++ .../dashboard-testing/analytics/+page.svelte | 22 +- .../analytics/cases/[caseId]/+page.svelte | 14 +- .../cases/[caseId]/__tests__/case.ux.test.ts | 6 +- .../dashboard-testing/automation/+page.svelte | 15 +- .../dashboard-testing/runs/+page.svelte | 66 +++-- .../runs/__tests__/center.ux.test.ts | 46 +++ .../runs_waiting_deeplink.ux.test.ts | 48 ++++ .../dashboard-testing/scenarios/+page.svelte | 206 ++++++++++++++ .../scenarios/[id]/analytics/+page.svelte | 22 +- .../scenarios/[id]/edit/+page.svelte | 99 +++++-- .../scenarios/[id]/runs/[runId]/+page.svelte | 49 +++- .../runs/[runId]/__tests__/run.ux.test.ts | 5 +- .../__tests__/scenarios_index.ux.test.ts | 94 ++++++ .../[id]/components/DashboardHeader.svelte | 11 +- frontend/src/routes/login/+page.svelte | 22 +- .../src/routes/oauth-consent/+page.svelte | 68 +++++ .../src/routes/settings/SystemSettings.svelte | 48 +++- frontend/src/types/scenario-analytics.ts | 3 +- frontend/tailwind.config.js | 1 + frontend/vite.config.js | 4 + run.sh | 67 +++++ scripts/mcp_proxy_fixture.py | 28 ++ scripts/mcp_proxy_smoke.py | 74 +++++ .../contracts/modules.md | 6 +- .../contracts/modules.md | 15 + .../contracts/modules.md | 18 ++ .../046-dashboard-scenario-automation/spec.md | 3 + ...l-scenario-test-pack-automation-handoff.md | 100 +++++++ specs/050-mcp-interface/spec.md | 13 +- specs/050-mcp-interface/tasks.md | 7 + specs/WORKSTATE-043-047.md | 189 ++++++++++++ specs/production-043-047-2026-09-05-plan.md | 50 ++++ 104 files changed, 4659 insertions(+), 402 deletions(-) create mode 100644 backend/alembic/versions/0018_automation_idempotency.py create mode 100644 backend/src/api/routes/admin_mcp.py create mode 100644 backend/src/mcp_server/tools_automation.py create mode 100644 backend/tests/api/test_admin_mcp_catalog.py create mode 100644 backend/tests/test_mcp_t029_bootstrap_automation.py create mode 100644 docs/2026-09-05-ss-tools-mcp-tool-audit.md create mode 100644 frontend/src/lib/models/AdminMcpCatalogModel.svelte.ts create mode 100644 frontend/src/lib/models/__tests__/AdminMcpCatalogModel.test.ts create mode 100644 frontend/src/lib/stores/__tests__/test_scenarioRuns.ts create mode 100644 frontend/src/lib/stores/scenarioRuns.svelte.ts create mode 100644 frontend/src/routes/admin/__tests__/admin-mcp.test.ts create mode 100644 frontend/src/routes/admin/mcp/+page.svelte create mode 100644 frontend/src/routes/dashboard-testing/runs/__tests__/center.ux.test.ts create mode 100644 frontend/src/routes/dashboard-testing/runs/__tests__/runs_waiting_deeplink.ux.test.ts create mode 100644 frontend/src/routes/dashboard-testing/scenarios/+page.svelte create mode 100644 frontend/src/routes/dashboard-testing/scenarios/__tests__/scenarios_index.ux.test.ts create mode 100644 frontend/src/routes/oauth-consent/+page.svelte create mode 100644 scripts/mcp_proxy_fixture.py create mode 100644 scripts/mcp_proxy_smoke.py create mode 100644 specs/050-mcp-interface/plans/initial-scenario-test-pack-automation-handoff.md create mode 100644 specs/production-043-047-2026-09-05-plan.md diff --git a/backend/alembic/versions/0018_automation_idempotency.py b/backend/alembic/versions/0018_automation_idempotency.py new file mode 100644 index 000000000..7c2cfe6bf --- /dev/null +++ b/backend/alembic/versions/0018_automation_idempotency.py @@ -0,0 +1,34 @@ +# #region Migrations.AutomationIdempotency [C:2] [TYPE Module] [SEMANTICS migration,automation,idempotency] +# @BRIEF Add MCP idempotency keys to the persisted automation configuration. +"""automation idempotency keys + +Revision ID: 0018_automation_idempotency +Revises: 0017_oauth_client_secret +""" +from alembic import op +import sqlalchemy as sa + +revision = "0018_automation_idempotency" +down_revision = "0017_oauth_client_secret" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + inspector = sa.inspect(op.get_bind()) + for table in ("scenario_schedules", "scenario_trigger_rules", "scenario_automation_policies"): + columns = {column["name"] for column in inspector.get_columns(table)} + if "idempotency_key" not in columns: + op.add_column(table, sa.Column("idempotency_key", sa.String(255), nullable=False, server_default="")) + if "request_hash" not in columns: + op.add_column(table, sa.Column("request_hash", sa.String(64), nullable=False, server_default="")) + + +def downgrade() -> None: + inspector = sa.inspect(op.get_bind()) + for table in ("scenario_schedules", "scenario_trigger_rules", "scenario_automation_policies"): + if "request_hash" in {column["name"] for column in inspector.get_columns(table)}: + op.drop_column(table, "request_hash") + if "idempotency_key" in {column["name"] for column in inspector.get_columns(table)}: + op.drop_column(table, "idempotency_key") +# #endregion Migrations.AutomationIdempotency diff --git a/backend/src/api/mcp_oauth.py b/backend/src/api/mcp_oauth.py index 037bfe604..4d72e874c 100644 --- a/backend/src/api/mcp_oauth.py +++ b/backend/src/api/mcp_oauth.py @@ -13,7 +13,7 @@ from sqlalchemy.orm import Session from src.core.auth.jwt import decode_token from src.core.database import get_auth_db -from src.dependencies import get_current_user, oauth2_scheme_optional +from src.dependencies import get_current_user, oauth2_scheme, oauth2_scheme_optional from src.models.auth import User from src.services.mcp_oauth import McpOAuthService @@ -31,13 +31,31 @@ class ClientRegistrationRequest(BaseModel): # #endregion Api.McpOAuth.ClientRegistration +# #region Api.McpOAuth.AuthorizationApproval [C:3] [TYPE Class] [SEMANTICS mcp,oauth,pkce,consent] +# @BRIEF Browser consent payload forwarded by the authenticated SPA without exposing its web JWT +# to the external OAuth client. +class AuthorizationApprovalRequest(BaseModel): + client_id: str + redirect_uri: str + code_challenge: str + code_challenge_method: str + response_type: str = "code" + scope: str = "mcp:read" + state: str | None = None + + +# #endregion Api.McpOAuth.AuthorizationApproval + + # #region Api.McpOAuth.Metadata [C:2] [TYPE Function] @router.get("/.well-known/oauth-authorization-server") async def authorization_server_metadata(request: Request) -> dict: issuer = str(request.base_url).rstrip("/") return { "issuer": issuer, - "authorization_endpoint": f"{issuer}/oauth/authorize", + # The SPA owns interactive local-password/ADFS login. It forwards the completed + # consent with its existing web JWT to /oauth/authorize/approve. + "authorization_endpoint": f"{issuer}/login?mcp_oauth=1", "token_endpoint": f"{issuer}/oauth/token", "registration_endpoint": f"{issuer}/oauth/register", "response_types_supported": ["code"], @@ -58,7 +76,7 @@ async def authorization_server_metadata(request: Request) -> dict: async def protected_resource_metadata(request: Request) -> dict: issuer = str(request.base_url).rstrip("/") return { - "resource": f"{issuer}/mcp", + "resource": f"{issuer}/mcp/", "authorization_servers": [issuer], "scopes_supported": ["mcp", "mcp:read", "mcp:write"], "bearer_methods_supported": ["header"], @@ -86,10 +104,20 @@ async def jwks() -> dict: async def register_client( request: ClientRegistrationRequest, http_request: Request, - current_user: User = Depends(get_current_user), + token: str | None = Depends(oauth2_scheme_optional), db: Session = Depends(get_auth_db), ) -> dict: try: + current_user: User | None = None + if token: + payload = decode_token(token) + current_user = db.query(User).filter( + User.username == payload.get("sub"), User.is_active.is_(True) + ).first() + if current_user is None: + raise ValueError("invalid_session") + if request.client_type == "confidential" and current_user is None: + raise ValueError("web_session_required") return McpOAuthService(db).register_client( request.client_name, request.redirect_uris, @@ -123,6 +151,31 @@ async def revoke_client( # #endregion Api.McpOAuth.RevokeClient +# #region Api.McpOAuth.UserConnections [C:4] [TYPE Function] [SEMANTICS oauth,user,connection,revocation] +# @BRIEF Expose only the current user's MCP OAuth connections; token material is never returned. +@router.get("/api/mcp/connections") +async def user_connections( + current_user: User = Depends(get_current_user), + db: Session = Depends(get_auth_db), +) -> dict[str, list[dict]]: + return {"connections": McpOAuthService(db).list_user_connections(current_user)} + + +@router.delete("/api/mcp/connections/{family_id}", status_code=status.HTTP_204_NO_CONTENT) +async def revoke_user_connection( + family_id: str, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_auth_db), +) -> None: + try: + McpOAuthService(db).revoke_user_connection(family_id, current_user) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) + + +# #endregion Api.McpOAuth.UserConnections + + # #region Api.McpOAuth.Authorize [C:4] [TYPE Function] @router.get("/oauth/authorize") async def authorize( @@ -158,6 +211,47 @@ async def authorize( # #endregion Api.McpOAuth.Authorize +# #region Api.McpOAuth.AuthorizeApprove [C:4] [TYPE Function] [SEMANTICS mcp,oauth,pkce,consent] +# @BRIEF Convert authenticated SPA consent into a PKCE-bound authorization code and callback URL. +# @PRE The browser has already authenticated with the ordinary local-password or ADFS flow. +# @POST Returns a registered callback URL; web credentials never leave the first-party SPA. +# @RATIONALE Browser-only MCP clients cannot attach the SPA's Authorization header to an OAuth +# navigation, so consent is submitted as an authenticated same-origin API request. +# @REJECTED Passing the web JWT in an OAuth URL is forbidden because URLs leak through browser +# history, referrers and proxy logs. +# The second path is the first-party SPA adapter: its API client namespaces same-origin +# requests with /api, whereas an external OAuth client uses the standards path above. +@router.post("/api/oauth/authorize/approve", include_in_schema=False) +@router.post("/oauth/authorize/approve") +async def approve_authorization( + request: AuthorizationApprovalRequest, + token: str = Depends(oauth2_scheme), + current_user: User = Depends(get_current_user), + db: Session = Depends(get_auth_db), +) -> dict[str, str]: + if request.response_type != "code" or request.code_challenge_method != "S256": + raise HTTPException(status_code=400, detail="invalid_request") + try: + code = McpOAuthService(db).create_code( + request.client_id, + request.redirect_uri, + request.code_challenge, + request.scope, + current_user, + decode_token(token).get("sid"), + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + separator = "&" if "?" in request.redirect_uri else "?" + callback_url = f"{request.redirect_uri}{separator}code={code}" + if request.state is not None: + callback_url += f"&state={request.state}" + return {"redirect_url": callback_url} + + +# #endregion Api.McpOAuth.AuthorizeApprove + + # #region Api.McpOAuth.Token [C:5] [TYPE Function] @router.post("/oauth/token") async def token( diff --git a/backend/src/api/routes/admin_mcp.py b/backend/src/api/routes/admin_mcp.py new file mode 100644 index 000000000..0c70a3ef8 --- /dev/null +++ b/backend/src/api/routes/admin_mcp.py @@ -0,0 +1,160 @@ +# #region Api.AdminMcp.GovernanceRouter [C:4] [TYPE Module] [SEMANTICS fastapi,admin,mcp,governance,catalog,rbac] +# @defgroup Api Module group. +# @LAYER API +# @BRIEF Admin-only MCP governance projection (UX audit Fix 5 / finding #4): the frozen tool catalog +# (name/risk/permission/service/approval/deprecation), the catalog version + server endpoint & +# discovery paths, a per-role visible-tool matrix computed with the SAME catalog+RBAC rules +# RbacFastMCP.list_tools enforces, and a read-only DCR client inventory (never secrets). +# @RELATION DEPENDS_ON -> [McpServer.Catalog] +# @RELATION DEPENDS_ON -> [McpServer.RbacServer] +# @RELATION DEPENDS_ON -> [Models.Auth.Role] +# @RELATION DEPENDS_ON -> [Models.Auth.OAuthClient] +# @RELATION DEPENDS_ON -> [Dependencies.AppDependencies.HasPermission] +# @INVARIANT Read-only: never mutates the catalog, roles, clients, or any MCP/runtime state. +# @INVARIANT The per-role visibility set mirrors RbacFastMCP._can_use_tool's human-principal branch +# (permission is None -> visible; start_scenario_run -> scenario RUN or RUN_PROD; otherwise +# an exact role resource/action match; an admin role bypasses) so the matrix cannot drift +# from the protocol-level tools/list. Pinned by tests/api/test_admin_mcp_catalog.py. +# @POST The payload never includes secret material (no client secret, no secret_hash, no token). +# @REJECTED Building the matrix by calling MCP tools/list per role was rejected — that needs a live +# per-role principal/token handshake; recomputing from the frozen catalog is exact and cheap. + +from __future__ import annotations + +import json +from typing import Any + +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from ...core.database import get_auth_db +from ...core.logger import belief_scope, logger +from ...dependencies import has_permission +from ...mcp_server.server import _MCP_CATALOG, MCP_CATALOG_VERSION +from ...models.auth import OAuthClient, Role + +# #region Api.AdminMcp.Router [TYPE Variable] +# @ingroup Api +# @RELATION DEPENDS_ON -> fastapi.APIRouter +# @BRIEF APIRouter for the admin MCP governance surface (mounted under /api/admin). +router = APIRouter(prefix="/api/admin", tags=["admin"]) +# #endregion Api.AdminMcp.Router + + +# #region Api.AdminMcp.SafeJsonList [C:2] [TYPE Function] [SEMANTICS admin,mcp,governance,json,parse] +# @ingroup Api +# @BRIEF Parse a canonical JSON array column into a list[str]; malformed/empty input yields []. +# @POST Pure; never raises. +def _safe_json_list(raw: str | None) -> list[str]: + if not raw: + return [] + try: + parsed = json.loads(raw) + except (ValueError, TypeError): + return [] + return [str(item) for item in parsed] if isinstance(parsed, list) else [] +# #endregion Api.AdminMcp.SafeJsonList + + +# #region Api.AdminMcp.VisibleTools [C:3] [TYPE Function] [SEMANTICS admin,mcp,governance,rbac,visibility] +# @ingroup Api +# @BRIEF Sorted MCP tool names visible to one role, mirroring the human-principal branch of +# RbacFastMCP._can_use_tool (an admin role sees the entire catalog). +# @PRE perm_pairs is the role's {(resource, action)} grant set. +# @POST Pure: returns sorted names; never raises; admin -> every catalog name. +def _visible_tool_names(is_admin: bool, perm_pairs: set[tuple[str, str]]) -> list[str]: + if is_admin: + return sorted(definition.name for definition in _MCP_CATALOG) + visible: list[str] = [] + for definition in _MCP_CATALOG: + if definition.permission is None: + visible.append(definition.name) + elif definition.name == "start_scenario_run": + # tools/list exposes it when either server-owned scenario permission can authorize a call. + if ("scenario", "RUN") in perm_pairs or ("scenario", "RUN_PROD") in perm_pairs: + visible.append(definition.name) + elif definition.permission in perm_pairs: + visible.append(definition.name) + return sorted(visible) +# #endregion Api.AdminMcp.VisibleTools + + +# #region Api.AdminMcp.GovernancePayload [C:3] [TYPE Function] [SEMANTICS admin,mcp,governance,catalog,payload] +# @ingroup Api +# @BRIEF Build the governance projection (tools + roles x visibility + DCR clients) from the auth DB. +# @POST Widest roles first (then by name); clients carry no secret material. +def _governance_payload(db: Session) -> dict[str, Any]: + tools = [ + { + "name": definition.name, + "risk_level": definition.risk_level, + "requires_approval": definition.requires_approval, + "service_allowed": definition.service_allowed, + "deprecated": definition.deprecated, + "deprecation_note": definition.deprecation_note, + "required_resource": definition.permission[0] if definition.permission else None, + "required_action": definition.permission[1] if definition.permission else None, + } + for definition in _MCP_CATALOG + ] + + roles: list[dict[str, Any]] = [] + for role in db.query(Role).all(): + perm_pairs = {(perm.resource, perm.action) for perm in (role.permissions or [])} + visible = _visible_tool_names(bool(role.is_admin), perm_pairs) + roles.append( + { + "role_id": role.id, + "name": role.name, + "description": role.description, + "is_admin": bool(role.is_admin), + "visible_count": len(visible), + "visible_tools": visible, + } + ) + roles.sort(key=lambda row: (-row["visible_count"], row["name"])) + + clients: list[dict[str, Any]] = [] + for client in db.query(OAuthClient).all(): + clients.append( + { + "client_id": client.client_id, + "client_name": client.client_name, + "client_type": client.client_type, + "is_revoked": bool(client.is_revoked), + "created_at": client.created_at.isoformat() if client.created_at else None, + "scopes": _safe_json_list(client.scopes), + "redirect_uris": _safe_json_list(client.redirect_uris), + } + ) + clients.sort(key=lambda row: row["client_name"] or "") + + return { + "catalog_version": MCP_CATALOG_VERSION, + "endpoint_path": "/mcp", + "discovery_path": "/.well-known/oauth-protected-resource/mcp", + "tool_count": len(_MCP_CATALOG), + "tools": tools, + "roles": roles, + "client_count": len(clients), + "clients": clients, + } +# #endregion Api.AdminMcp.GovernancePayload + + +# #region Api.AdminMcp.GetCatalog [C:3] [TYPE Function] [SEMANTICS admin,mcp,governance,catalog,endpoint] +# @ingroup Api +# @BRIEF GET /api/admin/mcp/catalog — admin governance projection of the MCP tool surface. +# @PRE Caller has admin:roles READ (same gate as the role/permission inventory). +# @POST Returns catalog version + endpoint/discovery paths + tools + roles x visibility + DCR clients. +@router.get("/mcp/catalog") +async def get_mcp_catalog( + db: Session = Depends(get_auth_db), _=Depends(has_permission("admin:roles", "READ")) +): + with belief_scope("api.admin.mcp_catalog"): + payload = _governance_payload(db) + logger.info("[admin.mcp] built catalog governance projection") + return payload +# #endregion Api.AdminMcp.GetCatalog + +# #endregion Api.AdminMcp.GovernanceRouter diff --git a/backend/src/app.py b/backend/src/app.py index 78eaaf2e7..04c3b650a 100755 --- a/backend/src/app.py +++ b/backend/src/app.py @@ -48,6 +48,7 @@ from .api import auth, mcp_oauth from .api.routes import ( admin, admin_api_keys, + admin_mcp, agent_conversations, agent_lifecycle, agent_runs, @@ -228,6 +229,11 @@ async def lifespan(app: FastAPI): logger.reason("Starting scheduler") scheduler = get_scheduler_service() scheduler.start() + # FastAPI does not automatically enter lifespans of mounted ASGI applications. + # StreamableHTTP's session manager owns an anyio task group, so it must be active + # before the first MCP initialize POST reaches the mounted /mcp transport. + mcp_lifespan = mcp_transport_app.router.lifespan_context(mcp_transport_app) + await mcp_lifespan.__aenter__() logger.reflect("Application startup complete") yield # Shutdown @@ -256,6 +262,7 @@ async def lifespan(app: FastAPI): logger.reason("Task drain complete") except Exception as _e: logger.explore("Graceful task drain during shutdown encountered error", error=str(_e)) + await mcp_lifespan.__aexit__(None, None, None) # #endregion App.AppModule.Lifespan @@ -264,6 +271,8 @@ async def lifespan(app: FastAPI): # @BRIEF Canonical FastAPI application instance for route, middleware, and websocket registration. # @RELATION DEPENDS_ON -> [Api.Init.ApiRoutesModule] # @RELATION BINDS_TO -> [App.AppModule.APIRoutes] +mcp_transport_app = create_mcp_asgi_app() + app = FastAPI( title="Superset Tools API", description="API for managing Superset automation tools and plugins.", @@ -280,7 +289,7 @@ app = FastAPI( from .core.middleware.trace import TraceContextMiddleware # noqa: E402 app.add_middleware(TraceContextMiddleware) -app.mount("/mcp", create_mcp_asgi_app()) +app.mount("/mcp", mcp_transport_app) # #endregion App.AppModule.FastAPIApp @@ -504,10 +513,22 @@ _POLLING_EXACT_PATHS = frozenset({ "/api/reports/task-log-gaps", }) +# Read-only batch endpoints polled via POST — semantically polls, framing suppressed too. +_POLLING_POST_PATHS = frozenset({ + "/api/git/repositories/status/batch", +}) + def _is_suppressed_request(request: Request) -> bool: - """Return True for high-frequency polling requests (framing suppressed).""" + """Return True for high-frequency polling requests (framing suppressed). + + GET exact-path polls and POST read-only batch polls are suppressed; + /api/tasks prefix stays GET-only and mutating POSTs (e.g. creating + maintenance events) always keep full framing. + """ path = request.url.path + if request.method == "POST" and path in _POLLING_POST_PATHS: + return True return request.method == "GET" and ( path in _POLLING_EXACT_PATHS or path.startswith("/api/tasks") ) @@ -576,6 +597,7 @@ app.include_router(auth.router) app.include_router(mcp_oauth.router) app.include_router(admin.router) app.include_router(admin_api_keys.router) +app.include_router(admin_mcp.router) app.include_router(plugins.router, prefix="/api/plugins", tags=["Plugins"]) app.include_router(tasks.router, prefix="/api/tasks", tags=["Tasks"]) app.include_router(settings.router, prefix="/api/settings", tags=["Settings"]) diff --git a/backend/src/core/config_models.py b/backend/src/core/config_models.py index 1f501a683..4c77da790 100755 --- a/backend/src/core/config_models.py +++ b/backend/src/core/config_models.py @@ -314,6 +314,21 @@ class GlobalSettings(BaseModel): description="IP ban duration after limit is reached (seconds)" ) + # MCP OAuth lifetime policy. Access tokens remain deliberately short-lived; refresh tokens + # are bounded by the operator's maximum and rotate on every use. + mcp_oauth_access_minutes: int = Field( + default=15, ge=1, le=60, + description="Lifetime of a user MCP OAuth access token in minutes", + ) + mcp_oauth_refresh_default_days: int = Field( + default=30, ge=1, le=90, + description="Default lifetime of a user MCP OAuth connection in days", + ) + mcp_oauth_refresh_max_days: int = Field( + default=90, ge=1, le=365, + description="Maximum lifetime of a user MCP OAuth connection in days", + ) + # Assistant (agent chat) history retention assistant_archive_after_days: int = Field( default=14, ge=1, le=365, diff --git a/backend/src/mcp_server/rbac_server.py b/backend/src/mcp_server/rbac_server.py index 69ae77703..37d5db7b5 100644 --- a/backend/src/mcp_server/rbac_server.py +++ b/backend/src/mcp_server/rbac_server.py @@ -141,6 +141,7 @@ _MCP_CATALOG = ( # No canonical workspace RBAC permission exists; authenticated human MCP access is # the narrow existing MCP-only pattern, while service principals remain denied. McpToolDefinition("create_authoring_session", None, service_allowed=False), + McpToolDefinition("bootstrap_authoring_scenario", None, service_allowed=False), McpToolDefinition("propose_test_plan", None, service_allowed=False), McpToolDefinition("start_exploration", None, service_allowed=False), McpToolDefinition("get_exploration_result", None, service_allowed=False), @@ -149,6 +150,15 @@ _MCP_CATALOG = ( McpToolDefinition("promote_to_scenario", None, service_allowed=False), McpToolDefinition("request_save", ("scenario", "EDIT"), service_allowed=False, risk_level="guarded"), McpToolDefinition("activate_revision", ("scenario", "EDIT"), service_allowed=False, risk_level="guarded"), + McpToolDefinition("list_scenario_schedules", ("scenario:automation", "READ")), + McpToolDefinition("upsert_scenario_schedule", ("scenario:automation", "MANAGE"), service_allowed=False), + McpToolDefinition("delete_scenario_schedule", ("scenario:automation", "MANAGE"), service_allowed=False), + McpToolDefinition("list_scenario_trigger_rules", ("scenario:automation", "READ")), + McpToolDefinition("upsert_scenario_trigger_rule", ("scenario:automation", "MANAGE"), service_allowed=False), + McpToolDefinition("delete_scenario_trigger_rule", ("scenario:automation", "MANAGE"), service_allowed=False), + McpToolDefinition("get_scenario_automation_policy", ("scenario:automation", "READ")), + McpToolDefinition("upsert_scenario_automation_policy", ("scenario:automation", "MANAGE"), service_allowed=False), + McpToolDefinition("get_scenario_automation_metrics", ("scenario:automation", "READ")), ) _MCP_CATALOG_BY_NAME = {definition.name: definition for definition in _MCP_CATALOG} diff --git a/backend/src/mcp_server/scenario_inputs.py b/backend/src/mcp_server/scenario_inputs.py index 80aeb38a7..34764eaf1 100644 --- a/backend/src/mcp_server/scenario_inputs.py +++ b/backend/src/mcp_server/scenario_inputs.py @@ -19,6 +19,23 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_v from src.services.dashboard_testing.scenario.models import DashboardTestScenario +# #region McpServer.InitialScenarioIntent [C:4] [TYPE Model] [SEMANTICS mcp,authoring,bootstrap,typed] +# @ingroup McpServer +# @BRIEF Strict bounded intent for server-owned first-scenario creation. +class InitialScenarioIntent(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + idempotency_key: StrictStr = Field(min_length=1, max_length=255) + title: StrictStr = Field(min_length=1, max_length=200) + dashboard_id: StrictInt = Field(ge=1) + allowed_environment_ids: list[StrictStr] = Field(min_length=1, max_length=20) + selected_case_ids: list[StrictStr] = Field(default_factory=list, max_length=50) + objective: StrictStr = Field(min_length=1, max_length=2000) + compiled_handle_id: StrictStr = Field(min_length=1, max_length=255) + draft_pack_id: StrictStr = Field(min_length=1, max_length=128) + draft_pack_digest: StrictStr = Field(pattern=r"^[a-fA-F0-9]{64}$") +# #endregion McpServer.InitialScenarioIntent + # #region McpServer.ScenarioModels [C:3] [TYPE Class] [SEMANTICS mcp,scenario,typed,validation] # @ingroup McpServer diff --git a/backend/src/mcp_server/server.py b/backend/src/mcp_server/server.py index a8acef472..10dda087c 100644 --- a/backend/src/mcp_server/server.py +++ b/backend/src/mcp_server/server.py @@ -30,7 +30,7 @@ import os from mcp.server.auth.provider import AccessToken # surface contract: tests build fake tokens via mcp_server.AccessToken from mcp.server.transport_security import TransportSecuritySettings from starlette.applications import Starlette -from starlette.routing import Route +from starlette.routing import Mount from starlette.types import ASGIApp @@ -147,6 +147,8 @@ def _build_probe_server(config: McpServerConfiguration | None = None) -> RbacFas register_probe_read_tools(server) register_authoring_tools(server) + from src.mcp_server.tools_automation import register_automation_tools + register_automation_tools(server) register_scenario_tools(server) register_maintenance_approval_tools(server) @@ -174,7 +176,12 @@ def create_mcp_asgi_app(config: McpServerConfiguration | None = None) -> ASGIApp async with mcp_app.router.lifespan_context(mcp_app): yield - return Starlette(routes=[Route("/", endpoint=guarded_app)], lifespan=lifespan) + # Streamable HTTP is a raw ASGI application. Mounting it preserves POST (initialize/JSON-RPC), + # GET (optional event stream), and DELETE (session close) without Route's method dispatch. + return Starlette( + routes=[Mount("/", app=guarded_app)], + lifespan=lifespan, + ) # #endregion McpServer.CreateApp diff --git a/backend/src/mcp_server/tools_authoring.py b/backend/src/mcp_server/tools_authoring.py index 20c2303f0..423fbb73f 100644 --- a/backend/src/mcp_server/tools_authoring.py +++ b/backend/src/mcp_server/tools_authoring.py @@ -30,9 +30,13 @@ from src.mcp_server.scenario_inputs import ( PromoteScenarioInput, RequestSaveInput, TestPlanInput, + InitialScenarioIntent, ) from src.models.agent_authoring_workspace import AgentAuthoringWorkspace +from src.models.agent_authoring_workspace import AgentAuthoringWorkspaceOperation +from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision from src.services.agent_authoring_workspace import ( + WorkspaceIdempotencyConflict, WorkspaceAccessError, WorkspaceNotFound, activate_revision, @@ -45,13 +49,67 @@ from src.services.agent_authoring_workspace import ( request_save, start_exploration, ) +from src.services.dashboard_testing.registry.create import create_initial from src.services.dashboard_testing.execution.exploration_sandbox import get_registered_runner +import hashlib +import json # #region McpServer.ToolsAuthoring.Register [C:4] [TYPE Function] [SEMANTICS mcp,authoring,tools,registration] # @ingroup McpServer # @BRIEF Registration seam: decorate the nine authoring-chain tools onto the guarded server instance. def register_authoring_tools(server) -> None: + # #region McpServer.BootstrapAuthoringScenario [C:5] [TYPE Function] [SEMANTICS mcp,bootstrap,registry,workspace] + # @ingroup McpServer + # @BRIEF Atomically bootstrap a server-owned registry chain and bound authoring workspace. + @server.tool(name="bootstrap_authoring_scenario", structured_output=True) + async def bootstrap_authoring_scenario(request: InitialScenarioIntent) -> dict[str, Any]: + access = _access_token_context.get() + if access is None or not access.subject or access.claims and access.claims.get("principal_type") == "service": + raise PermissionError("human_principal_required") + with SessionLocal() as db: + try: + request_hash = hashlib.sha256(json.dumps(request.model_dump(), sort_keys=True, separators=(",", ":")).encode()).hexdigest() + # The operation table's workspace_id is String(36); use a stable + # principal-scoped sentinel rather than storing an unbounded username. + receipt_scope = "boot-" + hashlib.sha256(access.subject.encode()).hexdigest()[:31] + receipt = db.query(AgentAuthoringWorkspaceOperation).filter( + AgentAuthoringWorkspaceOperation.workspace_id == receipt_scope, + AgentAuthoringWorkspaceOperation.operation == "bootstrap_authoring_scenario", + AgentAuthoringWorkspaceOperation.idempotency_key == request.idempotency_key, + AgentAuthoringWorkspaceOperation.actor_principal == access.subject, + ).first() + if receipt is not None: + if receipt.request_hash != request_hash: + raise WorkspaceIdempotencyConflict("idempotency key conflicts with a different bootstrap request") + workspace = db.get(AgentAuthoringWorkspace, receipt.result_reference) + revision = db.get(ScenarioRevision, workspace.base_revision_id) if workspace else None + entry = db.get(ScenarioRegistryEntry, workspace.scenario_id) if workspace else None + if workspace is None or revision is None or entry is None: + raise ValueError("bootstrap replay receipt is incomplete") + return {"scenario_id": entry.scenario_id, "revision_id": revision.revision_id, + "workspace_id": workspace.workspace_id, "content_hash": revision.content_hash, + "cas_version": workspace.cas_version, "activation_status": revision.activation_status, + "replayed": True} + entry, revision = create_initial(db, intent=request, user_id=access.subject, owner_username=access.subject) + workspace = create_workspace(db, access.subject, expires_in=timedelta(hours=1), + scenario_id=entry.scenario_id, base_revision_id=revision.revision_id, + base_content_hash=revision.content_hash, idempotency_key=request.idempotency_key, + actor_principal=access.subject) + db.add(AgentAuthoringWorkspaceOperation( + workspace_id=receipt_scope, operation="bootstrap_authoring_scenario", + idempotency_key=request.idempotency_key, request_hash=request_hash, + result_reference=workspace.workspace_id, result_status="current", + result_cas_version=workspace.cas_version, actor_principal=access.subject, + )) + db.commit() + return {"scenario_id": entry.scenario_id, "revision_id": revision.revision_id, + "workspace_id": workspace.workspace_id, "content_hash": revision.content_hash, + "cas_version": workspace.cas_version, "activation_status": revision.activation_status} + except Exception: + db.rollback() + raise + # #endregion McpServer.BootstrapAuthoringScenario # #region McpServer.AuthoringSessionTool [C:5] [TYPE Function] [SEMANTICS mcp,authoring,workspace,create,idempotency] # @ingroup McpServer # @BRIEF Create or replay a server-owned authoring workspace for the authenticated MCP user. diff --git a/backend/src/mcp_server/tools_automation.py b/backend/src/mcp_server/tools_automation.py new file mode 100644 index 000000000..8b71f5e43 --- /dev/null +++ b/backend/src/mcp_server/tools_automation.py @@ -0,0 +1,217 @@ +# #region McpServer.ToolsAutomation [C:4] [TYPE Module] [SEMANTICS mcp,automation,tools,rbac] +"""Curated MCP parity surface for persisted 046 automation configuration.""" + +from typing import Any +import hashlib +import json +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from src.core.database import SessionLocal +from src.mcp_server.auth import _access_token_context +from src.models.scenario_automation import AutomationPolicy, ScenarioNotificationEvent, ScenarioSchedule, ScenarioTriggerRule +from src.models.scenario_run import ScenarioRun +from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision +from src.services.dashboard_testing.automation.metrics import automation_metrics +from src.services.dashboard_testing.execution.runner_plan import derive_runner_plan + +_MISSED_POLICIES = {"skip", "run_latest", "queue_all"} +_TRIGGER_TYPES = {"deploy_to_preprod", "release_created", "etl_completed", "api"} + + +class AutomationBase(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + scenario_id: StrictStr = Field(min_length=1, max_length=36) + idempotency_key: StrictStr = Field(min_length=1, max_length=255) + environment_id: StrictStr = Field(min_length=1, max_length=128) + revision_id: StrictStr | None = Field(default=None, max_length=36) + revision_policy: StrictStr = Field(default="current", pattern="^(current|pinned)$") + enabled: StrictBool = True + + +class ScheduleInput(AutomationBase): + cron_expr: StrictStr = Field(min_length=1, max_length=128) + timezone: StrictStr = Field(default="UTC", max_length=64) + missed_execution_policy: StrictStr = "skip" + max_instances: StrictInt = Field(default=1, ge=1) + misfire_grace_time: StrictInt = Field(default=300, ge=0) + policy_id: StrictStr | None = None + + +class TriggerInput(AutomationBase): + trigger: StrictStr = Field(min_length=1, max_length=64) + policy_id: StrictStr | None = None + conditions: dict[str, Any] = Field(default_factory=dict) + + +class PolicyInput(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + idempotency_key: StrictStr = Field(min_length=1, max_length=255) + name: StrictStr = Field(min_length=1, max_length=255) + enabled: StrictBool = True + workload_class: StrictStr = "scenario_smoke" + max_concurrent_per_env: StrictInt = Field(default=1, ge=1) + dedup_window_seconds: StrictInt = Field(default=0, ge=0) + overlap_rule: StrictStr = "block" + retention_days: StrictInt = Field(default=30, ge=1) + prod_gate_required: StrictBool = False + on_repeated_failure: StrictStr = "alert" + + +class DeleteInput(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + item_id: StrictStr = Field(min_length=1, max_length=36) + + +# #region McpServer.ToolsAutomation.Register [C:4] [TYPE Function] [SEMANTICS mcp,automation,registration] +def register_automation_tools(server: Any) -> None: + def _hash(payload: dict[str, Any]) -> str: + return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode()).hexdigest() + + def _revision(db, request: AutomationBase) -> None: + if request.revision_id is None: + raise ValueError("revision_id is required") + revision = db.get(ScenarioRevision, request.revision_id) + entry = db.get(ScenarioRegistryEntry, request.scenario_id) + if revision is None or entry is None or revision.scenario_id != request.scenario_id or entry.current_revision_id != revision.revision_id: + raise ValueError("revision must be the active scenario revision") + plan = derive_runner_plan(db, request.scenario_id, request.revision_id) + if plan.get("manual_run_only"): + raise ValueError("AUTOMATION_INELIGIBLE_HUMAN_STEP") + + def _policy(db, policy_id: str | None) -> None: + if policy_id is not None and db.get(AutomationPolicy, policy_id) is None: + raise ValueError("automation policy not found") + + def _replay(db, model, request: BaseModel): + key = request.idempotency_key + payload = request.model_dump(exclude={"idempotency_key"}) + item = db.query(model).filter(model.idempotency_key == key).first() + if item is None: + return None + if item.request_hash != _hash(payload): + raise ValueError("idempotency key conflicts with a different request") + return item + + def _projection(item, fields: tuple[str, ...]) -> dict[str, Any]: + return {key: getattr(item, key) for key in fields} + def owner() -> str: + access = _access_token_context.get() + if access is None or not access.subject or (access.claims and access.claims.get("principal_type") == "service"): + raise PermissionError("human_principal_required") + return access.subject + + @server.tool(name="list_scenario_schedules", structured_output=True) + async def list_scenario_schedules(scenario_id: StrictStr | None = None) -> list[dict[str, Any]]: + owner() + with SessionLocal() as db: + q = db.query(ScenarioSchedule) + if scenario_id: + q = q.filter(ScenarioSchedule.scenario_id == scenario_id) + return [_projection(x, ("id", "scenario_id", "revision_id", "environment_id", "cron_expr", "timezone", "enabled", "policy_id")) for x in q.all()] + + @server.tool(name="list_scenario_trigger_rules", structured_output=True) + async def list_scenario_trigger_rules(scenario_id: StrictStr | None = None) -> list[dict[str, Any]]: + owner() + with SessionLocal() as db: + q = db.query(ScenarioTriggerRule) + if scenario_id: + q = q.filter(ScenarioTriggerRule.scenario_id == scenario_id) + return [_projection(x, ("id", "scenario_id", "revision_id", "environment_id", "trigger", "enabled", "policy_id")) for x in q.all()] + + @server.tool(name="get_scenario_automation_policy", structured_output=True) + async def get_scenario_automation_policy(scenario_id: StrictStr) -> dict[str, Any]: + owner() + with SessionLocal() as db: + policy_id = db.query(ScenarioSchedule.policy_id).filter(ScenarioSchedule.scenario_id == scenario_id, ScenarioSchedule.policy_id.isnot(None)).first() + if policy_id is None: + policy_id = db.query(ScenarioTriggerRule.policy_id).filter(ScenarioTriggerRule.scenario_id == scenario_id, ScenarioTriggerRule.policy_id.isnot(None)).first() + policy = db.get(AutomationPolicy, policy_id[0]) if policy_id else None + return {k: getattr(policy, k) for k in ("id", "name", "enabled", "workload_class", "prod_gate_required")} if policy else {"status": "not_found", "scenario_id": scenario_id} + + @server.tool(name="get_scenario_automation_metrics", structured_output=True) + async def get_scenario_automation_metrics(scenario_id: StrictStr) -> dict[str, Any]: + owner() + with SessionLocal() as db: + schedules = db.query(ScenarioSchedule).filter_by(scenario_id=scenario_id).all() + rules = db.query(ScenarioTriggerRule).filter_by(scenario_id=scenario_id).all() + runs = db.query(ScenarioRun).filter_by(scenario_id=scenario_id).all() + events = db.query(ScenarioNotificationEvent).filter_by(scenario_id=scenario_id).all() + return automation_metrics( + schedules=[{"enabled": x.enabled} for x in schedules], trigger_rules=[{"enabled": x.enabled} for x in rules], runs=[{"status": x.status, "trigger_source": x.trigger_source} for x in runs], notifications=[{"event_type": x.event_type, "payload": x.payload} for x in events] + ) | {"scenario_id": scenario_id} + + @server.tool(name="upsert_scenario_schedule", structured_output=True) + async def upsert_scenario_schedule(request: ScheduleInput) -> dict[str, Any]: + owner() + with SessionLocal() as db: + if request.missed_execution_policy not in _MISSED_POLICIES: + raise ValueError("invalid missed_execution_policy") + _revision(db, request) + _policy(db, request.policy_id) + replay = _replay(db, ScenarioSchedule, request) + if replay is not None: + return {"status": "ok", "id": replay.id, "replayed": True} + item = ScenarioSchedule(**request.model_dump(exclude={"idempotency_key"})) + item.idempotency_key = request.idempotency_key + item.request_hash = _hash(request.model_dump(exclude={"idempotency_key"})) + db.add(item) + db.commit() + db.refresh(item) + return {"status": "ok", "id": item.id} + + @server.tool(name="delete_scenario_schedule", structured_output=True) + async def delete_scenario_schedule(request: DeleteInput) -> dict[str, Any]: + owner() + with SessionLocal() as db: + item = db.get(ScenarioSchedule, request.item_id) + if item: + db.delete(item) + db.commit() + return {"status": "ok", "deleted": item is not None} + + @server.tool(name="upsert_scenario_trigger_rule", structured_output=True) + async def upsert_scenario_trigger_rule(request: TriggerInput) -> dict[str, Any]: + owner() + with SessionLocal() as db: + if request.trigger not in _TRIGGER_TYPES: + raise ValueError("invalid trigger") + _revision(db, request) + _policy(db, request.policy_id) + replay = _replay(db, ScenarioTriggerRule, request) + if replay is not None: + return {"status": "ok", "id": replay.id, "replayed": True} + item = ScenarioTriggerRule(**request.model_dump(exclude={"idempotency_key"})) + item.idempotency_key = request.idempotency_key + item.request_hash = _hash(request.model_dump(exclude={"idempotency_key"})) + db.add(item) + db.commit() + db.refresh(item) + return {"status": "ok", "id": item.id} + + @server.tool(name="delete_scenario_trigger_rule", structured_output=True) + async def delete_scenario_trigger_rule(request: DeleteInput) -> dict[str, Any]: + owner() + with SessionLocal() as db: + item = db.get(ScenarioTriggerRule, request.item_id) + if item: + db.delete(item) + db.commit() + return {"status": "ok", "deleted": item is not None} + + @server.tool(name="upsert_scenario_automation_policy", structured_output=True) + async def upsert_scenario_automation_policy(request: PolicyInput) -> dict[str, Any]: + owner() + with SessionLocal() as db: + replay = _replay(db, AutomationPolicy, request) + if replay is not None: + return {"status": "ok", "id": replay.id, "replayed": True} + item = AutomationPolicy(**request.model_dump(exclude={"idempotency_key"})) + item.idempotency_key = request.idempotency_key + item.request_hash = _hash(request.model_dump(exclude={"idempotency_key"})) + db.add(item) + db.commit() + db.refresh(item) + return {"status": "ok", "id": item.id} + + +# #endregion McpServer.ToolsAutomation.Register +# #endregion McpServer.ToolsAutomation diff --git a/backend/src/models/scenario_automation.py b/backend/src/models/scenario_automation.py index fd015973a..5200a124a 100644 --- a/backend/src/models/scenario_automation.py +++ b/backend/src/models/scenario_automation.py @@ -35,6 +35,8 @@ class ScenarioSchedule(Base): enabled = Column(Boolean, nullable=False, default=True) max_instances = Column(Integer, nullable=False, default=1) misfire_grace_time = Column(Integer, nullable=False, default=300) + idempotency_key = Column(String(255), nullable=False, default="") + request_hash = Column(String(64), nullable=False, default="") created_by = Column(String(128), nullable=True) created_at = Column(DateTime, nullable=False, default=_now) @@ -50,6 +52,8 @@ class ScenarioTriggerRule(Base): enabled = Column(Boolean, nullable=False, default=True) conditions = Column(JSON, nullable=False, default=dict) created_at = Column(DateTime, nullable=False, default=_now) + idempotency_key = Column(String(255), nullable=False, default="") + request_hash = Column(String(64), nullable=False, default="") class AutomationPolicy(Base): __tablename__ = "scenario_automation_policies" @@ -64,6 +68,8 @@ class AutomationPolicy(Base): prod_gate_required = Column(Boolean, nullable=False, default=False) on_repeated_failure = Column(String(16), nullable=False, default="alert") created_at = Column(DateTime, nullable=False, default=_now) + idempotency_key = Column(String(255), nullable=False, default="") + request_hash = Column(String(64), nullable=False, default="") class ScenarioNotificationEvent(Base): __tablename__ = "scenario_notification_events" diff --git a/backend/src/services/dashboard_testing/registry/create.py b/backend/src/services/dashboard_testing/registry/create.py index 717473117..b71d6fe62 100644 --- a/backend/src/services/dashboard_testing/registry/create.py +++ b/backend/src/services/dashboard_testing/registry/create.py @@ -14,6 +14,7 @@ from __future__ import annotations import hashlib from pathlib import PurePosixPath import uuid +import re from sqlalchemy.orm import Session from src.core.logger import logger @@ -96,6 +97,7 @@ def create_scenario( draft_pack_digest: str, user_id: str, owner_username: str | None = None, + validate_compiled_handle: bool = False, ) -> tuple[ScenarioRegistryEntry, ScenarioRevision]: draft = ( db.query(DraftArtifact) @@ -106,6 +108,13 @@ def create_scenario( if draft is None: raise ValueError("draft pack not found") + # Compiled handles are server-issued references from the existing compile/save + # flow. Requiring their run and digest to match the selected artifact prevents + # a caller from combining two otherwise valid handles. + handle = re.fullmatch(r"compile:([^:]+):([0-9a-fA-F]{64})", compiled_handle_id) + if validate_compiled_handle and (handle is None or handle.group(1) != str(draft.run_id)): + raise ValueError("compiled handle is invalid or stale") + run = db.query(AgentRun).filter(AgentRun.id == draft.run_id).first() if run is None or str(run.user_id) != str(user_id): raise ValueError("draft pack access denied") @@ -118,6 +127,8 @@ def create_scenario( actual_digest = hashlib.sha256(stored).hexdigest() if actual_digest != draft.sha256 or actual_digest != draft_pack_digest: raise ValueError("draft pack digest mismatch") + if validate_compiled_handle and (handle is None or handle.group(2).lower() != actual_digest.lower()): + raise ValueError("compiled handle digest mismatch") scenario_key = _scenario_key(draft.intended_path) runner_plan = ( @@ -182,4 +193,40 @@ def create_scenario( return entry, revision # #endregion ScenarioRegistry.Create.Register +# #region ScenarioRegistry.Create.Initial [C:5] [TYPE Function] [SEMANTICS scenario,registry,bootstrap,transaction] +# @ingroup ScenarioRegistry +# @BRIEF Stage the first registry entry and immutable current revision from server-owned handles. +def create_initial(db: Session, *, intent, user_id: str, owner_username: str | None = None): + """Create the initial chain; caller commits workspace and transaction together.""" + draft = db.query(DraftArtifact).join(AgentRun, AgentRun.id == DraftArtifact.run_id).filter( + DraftArtifact.id == intent.draft_pack_id, DraftArtifact.kind == "scenario_pack" + ).first() + if draft is None: + raise ValueError("draft pack not found") + run = db.query(AgentRun).filter(AgentRun.id == draft.run_id).first() + if run is None or int(run.dashboard_id) != intent.dashboard_id: + raise ValueError("dashboard context is stale") + if str(run.environment_id) not in set(intent.allowed_environment_ids): + raise ValueError("allowed environment does not match compiled context") + entry, revision = create_scenario( + db, compiled_handle_id=intent.compiled_handle_id, + draft_pack_id=intent.draft_pack_id, draft_pack_digest=intent.draft_pack_digest, + user_id=user_id, owner_username=owner_username, validate_compiled_handle=True, + ) + entry.name = intent.title + entry.description = intent.objective + entry.dashboard_id = intent.dashboard_id + entry.environment_ids = list(intent.allowed_environment_ids) + entry.current_revision_id = revision.revision_id + revision.activation_status = ScenarioActivationStatus.CURRENT + revision.activated_by = str(user_id) + revision.graph_snapshot = { + **revision.graph_snapshot, + "selected_case_ids": list(intent.selected_case_ids), + "objective": intent.objective, + } + db.flush() + return entry, revision +# #endregion ScenarioRegistry.Create.Initial + # #endregion ScenarioRegistry.Create diff --git a/backend/src/services/mcp_oauth.py b/backend/src/services/mcp_oauth.py index 579f24ad1..75a5468ca 100644 --- a/backend/src/services/mcp_oauth.py +++ b/backend/src/services/mcp_oauth.py @@ -40,6 +40,27 @@ class McpOAuthConfig: # #endregion Services.McpOAuth.Config +# #region Services.McpOAuth.Lifetimes [C:3] [TYPE Function] [SEMANTICS mcp,oauth,settings,lifetime] +# @BRIEF Resolve operator-controlled OAuth lifetimes with secure defaults during bootstrap. +# @POST Returns access minutes and refresh days where refresh never exceeds the configured maximum. +def _lifetimes() -> tuple[int, int]: + try: + from src.core.settings_provider import get_global_settings + + settings = get_global_settings() + if settings is not None: + access = int(getattr(settings, "mcp_oauth_access_minutes", McpOAuthConfig.access_minutes)) + default_days = int(getattr(settings, "mcp_oauth_refresh_default_days", McpOAuthConfig.refresh_days)) + max_days = int(getattr(settings, "mcp_oauth_refresh_max_days", 90)) + return max(1, min(access, 60)), max(1, min(default_days, max_days, 365)) + except Exception: + pass + return McpOAuthConfig.access_minutes, McpOAuthConfig.refresh_days + + +# #endregion Services.McpOAuth.Lifetimes + + # #region Services.McpOAuth.Hash [C:2] [TYPE Function] # @ingroup McpOAuth # @BRIEF Hash a bearer artifact before durable storage. @@ -112,7 +133,8 @@ class McpOAuthService: user_count = self.db.query(OAuthRegistrationAttempt).filter(OAuthRegistrationAttempt.user_id == owner.id, OAuthRegistrationAttempt.created_at >= window_start).count() if user_count >= 50: raise ValueError("registration_rate_limited") - if not name or not redirect_uris or not all(uri.startswith("http://localhost") or uri.startswith("https://") for uri in redirect_uris): + local_loopback = ("http://localhost", "http://127.0.0.1", "http://[::1]") + if not name or not redirect_uris or not all(uri.startswith(local_loopback) or uri.startswith("https://") for uri in redirect_uris): raise ValueError("invalid_client_metadata") requested = set(scopes or ["mcp:read"]) if not requested.issubset(McpOAuthConfig.allowed_scopes): @@ -149,6 +171,42 @@ class McpOAuthService: self.db.query(OAuthRefreshToken).filter(OAuthRefreshToken.client_id == client_id, OAuthRefreshToken.revoked_at.is_(None)).update({OAuthRefreshToken.revoked_at: datetime.now(UTC)}, synchronize_session=False) self.db.commit() + # #region Services.McpOAuth.Service.UserConnections [C:4] [TYPE Function] [SEMANTICS oauth,user,connection,revocation] + # @BRIEF List and revoke OAuth refresh-token families belonging to one user. + # @INVARIANT The response contains metadata only; raw refresh tokens are never retrievable. + def list_user_connections(self, user: User) -> list[dict]: + rows = self.db.query(OAuthRefreshToken, OAuthClient).join( + OAuthClient, OAuthClient.client_id == OAuthRefreshToken.client_id + ).filter(OAuthRefreshToken.user_id == user.id).order_by(OAuthRefreshToken.created_at.desc()).all() + connections: dict[str, dict] = {} + for token, client in rows: + connection = connections.setdefault(token.family_id, { + "family_id": token.family_id, + "client_id": token.client_id, + "client_name": client.client_name, + "scope": token.scope, + "created_at": token.created_at.isoformat(), + "expires_at": token.expires_at.isoformat(), + "revoked_at": token.revoked_at.isoformat() if token.revoked_at else None, + }) + if token.revoked_at is None: + connection["revoked_at"] = None + return list(connections.values()) + + def revoke_user_connection(self, family_id: str, user: User) -> None: + now = datetime.now(UTC) + updated = self.db.query(OAuthRefreshToken).filter( + OAuthRefreshToken.family_id == family_id, + OAuthRefreshToken.user_id == user.id, + OAuthRefreshToken.revoked_at.is_(None), + ).update({OAuthRefreshToken.revoked_at: now}, synchronize_session=False) + if updated == 0: + self.db.rollback() + raise ValueError("connection_not_found") + self.db.commit() + + # #endregion Services.McpOAuth.Service.UserConnections + def create_code(self, client_id: str, redirect_uri: str, challenge: str, scope: str, user: User, session_id: str | None = None) -> str: client = self.db.query(OAuthClient).filter(OAuthClient.client_id == client_id, OAuthClient.is_revoked.is_(False)).first() if client is None or redirect_uri not in json.loads(client.redirect_uris) or not challenge: @@ -230,6 +288,7 @@ class McpOAuthService: granted = sorted(set(json.loads(client.scopes)) & McpOAuthConfig.allowed_scopes) scope = " ".join(granted or ["mcp:read"]) now = datetime.now(UTC) + access_minutes, _ = _lifetimes() private_pem, _, kid, _ = current_key_material() access = jwt.encode( { @@ -241,7 +300,7 @@ class McpOAuthService: "aud": McpOAuthConfig.audience, "iss": os.getenv("MCP_OAUTH_ISSUER", McpOAuthConfig.issuer), "iat": now, - "exp": now + timedelta(minutes=McpOAuthConfig.access_minutes), + "exp": now + timedelta(minutes=access_minutes), }, private_pem, algorithm="RS256", @@ -251,7 +310,7 @@ class McpOAuthService: return { "access_token": access, "token_type": "Bearer", - "expires_in": McpOAuthConfig.access_minutes * 60, + "expires_in": access_minutes * 60, "scope": scope, } # #endregion Services.McpOAuth.Service.ClientCredentials @@ -261,12 +320,13 @@ class McpOAuthService: if user is None or not user.is_active: raise ValueError("invalid_grant") now = datetime.now(UTC) + access_minutes, refresh_days = _lifetimes() private_pem, _, kid, _ = current_key_material() - access = jwt.encode({"sub": user.username, "scope": scope, "jti": str(uuid.uuid4()), "session_id": session_id, "aud": "mcp", "iss": os.getenv("MCP_OAUTH_ISSUER", "superset-tools"), "iat": now, "exp": now + timedelta(minutes=McpOAuthConfig.access_minutes)}, private_pem, algorithm="RS256", headers={"kid": kid}) + access = jwt.encode({"sub": user.username, "scope": scope, "jti": str(uuid.uuid4()), "session_id": session_id, "aud": "mcp", "iss": os.getenv("MCP_OAUTH_ISSUER", "superset-tools"), "iat": now, "exp": now + timedelta(minutes=access_minutes)}, private_pem, algorithm="RS256", headers={"kid": kid}) refresh = secrets.token_urlsafe(48) - self.db.add(OAuthRefreshToken(token_hash=_hash(refresh), family_id=family_id or str(uuid.uuid4()), client_id=client_id, user_id=user.id, scope=scope, session_id=session_id, expires_at=now + timedelta(days=McpOAuthConfig.refresh_days), created_at=now)) + self.db.add(OAuthRefreshToken(token_hash=_hash(refresh), family_id=family_id or str(uuid.uuid4()), client_id=client_id, user_id=user.id, scope=scope, session_id=session_id, expires_at=now + timedelta(days=refresh_days), created_at=now)) self.db.commit() - return {"access_token": access, "token_type": "Bearer", "expires_in": McpOAuthConfig.access_minutes * 60, "refresh_token": refresh, "scope": scope} + return {"access_token": access, "token_type": "Bearer", "expires_in": access_minutes * 60, "refresh_token": refresh, "scope": scope} # #endregion Services.McpOAuth.Service diff --git a/backend/tests/api/test_admin_mcp_catalog.py b/backend/tests/api/test_admin_mcp_catalog.py new file mode 100644 index 000000000..a1a074395 --- /dev/null +++ b/backend/tests/api/test_admin_mcp_catalog.py @@ -0,0 +1,206 @@ +# #region Test.Api.AdminMcpCatalog [C:4] [TYPE Module] [SEMANTICS test,admin,mcp,governance,catalog,rbac,visibility] +# @BRIEF Governance-endpoint tests for the admin MCP catalog projection (UX audit Fix 5). The +# per-role visibility helper is pinned to the SAME exact subsets SC-004 pins for the +# protocol tools/list (admin=all, viewer=permission-None, analyst=None+grants), so the UI +# matrix cannot drift from RbacFastMCP. Also asserts payload shape, client secret-safety and +# the read-only endpoint wiring through a standalone FastAPI app. +# @RELATION VERIFIES -> [Api.AdminMcp.GovernancePayload] +# @RELATION VERIFIES -> [Api.AdminMcp.VisibleTools] +# @TEST_INVARIANT rbac_parity_with_protocol -> VERIFIED_BY: [test_visible_tools_matches_sc004_subsets] +# @TEST_INVARIANT no_secret_in_payload -> VERIFIED_BY: [test_payload_never_carries_secret_material] + +import os + +# Set env BEFORE any source imports +os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:") +os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:") +os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests") + +import sys # noqa: E402 +from datetime import datetime # noqa: E402 +from pathlib import Path # noqa: E402 +from types import SimpleNamespace # noqa: E402 + +from fastapi import FastAPI # noqa: E402 +from fastapi.testclient import TestClient # noqa: E402 + +_src = str(Path(__file__).resolve().parent.parent.parent / "src") +if _src not in sys.path: + sys.path.insert(0, _src) + +from src.api.routes.admin_mcp import _governance_payload, _visible_tool_names, router # noqa: E402 +from src.dependencies import get_auth_db, get_current_user # noqa: E402 +from src.mcp_server.server import _MCP_CATALOG, MCP_CATALOG_VERSION # noqa: E402 +from src.models.auth import OAuthClient, Role # noqa: E402 + +_ALL_TOOLS = sorted(definition.name for definition in _MCP_CATALOG) +_NONE_TOOLS = sorted(definition.name for definition in _MCP_CATALOG if definition.permission is None) +# Independent (SC-004-mirroring) expectation for the analyst grant set — NOT derived from the impl. +_ANALYST_GRANTS = (("scenario", "RUN"), ("dashboard:testing", "WRITE"), ("tasks", "READ")) +_ANALYST_EXTRA = sorted([ + "get_task_status", # tasks:READ + "list_checkpoints", # scenario:RUN + "decide_checkpoint", # scenario:RUN + "start_scenario_run", # scenario:RUN (RUN or RUN_PROD) + "capture_baseline_candidate", # dashboard:testing:WRITE + "create_verification_run", # dashboard:testing:WRITE +]) + + +# #region Test.Api.AdminMcpCatalog.FakeDb [C:2] [TYPE Function] [SEMANTICS test,admin,mcp,fixture,db] +class _FakeQuery: + def __init__(self, rows): + self._rows = rows + + def all(self): + return self._rows + + +class _FakeDB: + def __init__(self, roles, clients): + self._roles = roles + self._clients = clients + + def query(self, model): + if model is Role: + return _FakeQuery(self._roles) + if model is OAuthClient: + return _FakeQuery(self._clients) + return _FakeQuery([]) + + +def _role(name, *, is_admin=False, grants=()): + return SimpleNamespace( + id=f"role-{name}", + name=name, + description=f"{name} role", + is_admin=is_admin, + permissions=[SimpleNamespace(resource=r, action=a) for r, a in grants], + ) + + +def _client(client_id, name, *, revoked=False): + return SimpleNamespace( + client_id=client_id, + client_name=name, + client_type="confidential", + is_revoked=revoked, + created_at=datetime(2026, 9, 1, 12, 0, 0), + scopes='["mcp", "mcp:read"]', + redirect_uris='["https://client.local/callback"]', + secret_hash="SHOULD_NOT_APPEAR", + ) +# #endregion Test.Api.AdminMcpCatalog.FakeDb + + +# #region Test.Api.AdminMcpCatalog.VisibilityParity [C:4] [TYPE Function] [SEMANTICS test,admin,mcp,rbac,parity] +def test_visible_tools_matches_sc004_subsets(): + """The governance helper reproduces SC-004's exact admin/viewer/analyst tool subsets.""" + assert _visible_tool_names(True, set()) == _ALL_TOOLS + assert _visible_tool_names(False, set()) == _NONE_TOOLS + assert _visible_tool_names(False, set(_ANALYST_GRANTS)) == sorted(_NONE_TOOLS + _ANALYST_EXTRA) + + +def test_start_scenario_run_visible_with_run_prod_only(): + """start_scenario_run surfaces for RUN_PROD too (mirrors _can_use_tool's special case).""" + visible = _visible_tool_names(False, {("scenario", "RUN_PROD")}) + assert "start_scenario_run" in visible + # RUN_PROD-gated approvals surface, but a scenario:RUN-only tool stays hidden. + assert "list_pending_approvals" in visible + assert "decide_approval" in visible + assert "decide_checkpoint" not in visible # decide_checkpoint requires scenario:RUN + + +def test_unrelated_grant_does_not_leak_tools(): + """A grant outside the catalog exposes only the permission-None surface.""" + visible = _visible_tool_names(False, {("nonexistent", "READ")}) + assert visible == _NONE_TOOLS +# #endregion Test.Api.AdminMcpCatalog.VisibilityParity + + +# #region Test.Api.AdminMcpCatalog.Payload [C:3] [TYPE Function] [SEMANTICS test,admin,mcp,payload,shape] +def test_payload_shape_and_role_matrix(): + roles = [ + _role("Viewer", grants=()), + _role("Admin", is_admin=True), + _role("Analyst", grants=_ANALYST_GRANTS), + ] + payload = _governance_payload(_FakeDB(roles, [_client("c1", "Claude Desktop")])) + + assert payload["catalog_version"] == MCP_CATALOG_VERSION + assert payload["endpoint_path"] == "/mcp" + assert payload["discovery_path"] == "/.well-known/oauth-protected-resource/mcp" + assert payload["tool_count"] == len(_MCP_CATALOG) + assert len(payload["tools"]) == len(_MCP_CATALOG) + # tool rows carry governance metadata + sql_tool = next(t for t in payload["tools"] if t["name"] == "superset_execute_sql") + assert sql_tool["risk_level"] == "guarded" + assert sql_tool["required_resource"] == "plugin:superset_sql" + assert sql_tool["service_allowed"] is False + + # widest roles first + assert payload["roles"][0]["name"] == "Admin" + assert payload["roles"][0]["visible_count"] == payload["tool_count"] + viewer = next(r for r in payload["roles"] if r["name"] == "Viewer") + assert viewer["visible_count"] == len(_NONE_TOOLS) + analyst = next(r for r in payload["roles"] if r["name"] == "Analyst") + assert analyst["visible_count"] == len(_NONE_TOOLS) + len(_ANALYST_EXTRA) + + assert payload["client_count"] == 1 + assert payload["clients"][0]["scopes"] == ["mcp", "mcp:read"] + assert payload["clients"][0]["redirect_uris"] == ["https://client.local/callback"] + + +def test_payload_never_carries_secret_material(): + payload = _governance_payload(_FakeDB([_role("Admin", is_admin=True)], [_client("c1", "X", revoked=True)])) + blob = repr(payload).lower() + assert "should_not_appear" not in blob + assert "secret_hash" not in blob + assert payload["clients"][0]["is_revoked"] is True + assert set(payload["clients"][0]).isdisjoint({"secret", "secret_hash", "client_secret"}) + + +def test_malformed_client_json_columns_degrade_to_empty_lists(): + client = SimpleNamespace( + client_id="c2", client_name="Bad", client_type="public", is_revoked=False, + created_at=None, scopes="not-json", redirect_uris=None, + ) + payload = _governance_payload(_FakeDB([], [client])) + assert payload["clients"][0]["scopes"] == [] + assert payload["clients"][0]["redirect_uris"] == [] + assert payload["clients"][0]["created_at"] is None +# #endregion Test.Api.AdminMcpCatalog.Payload + + +# #region Test.Api.AdminMcpCatalog.Endpoint [C:3] [TYPE Function] [SEMANTICS test,admin,mcp,endpoint,http] +def _make_client(db, *, is_admin=True): + user = SimpleNamespace( + id="u-1", username="caller", is_active=True, + roles=[SimpleNamespace(is_admin=is_admin, permissions=[])], + ) + app = FastAPI() + app.include_router(router) + app.dependency_overrides[get_auth_db] = lambda: db + app.dependency_overrides[get_current_user] = lambda: user + return TestClient(app) + + +def test_endpoint_returns_governance_projection(): + db = _FakeDB([_role("Admin", is_admin=True), _role("Viewer")], [_client("c1", "Claude Desktop")]) + resp = _make_client(db).get("/api/admin/mcp/catalog") + assert resp.status_code == 200 + body = resp.json() + assert body["catalog_version"] == MCP_CATALOG_VERSION + assert body["tool_count"] == len(_MCP_CATALOG) + assert {r["name"] for r in body["roles"]} == {"Admin", "Viewer"} + assert body["client_count"] == 1 + + +def test_endpoint_denies_non_admin(): + """The admin:roles READ gate rejects a non-admin caller with 403 (no projection leaks).""" + db = _FakeDB([_role("Admin", is_admin=True)], []) + resp = _make_client(db, is_admin=False).get("/api/admin/mcp/catalog") + assert resp.status_code == 403 +# #endregion Test.Api.AdminMcpCatalog.Endpoint + +# #endregion Test.Api.AdminMcpCatalog diff --git a/backend/tests/test_app_middleware.py b/backend/tests/test_app_middleware.py index 65e01b996..1927d2f6e 100644 --- a/backend/tests/test_app_middleware.py +++ b/backend/tests/test_app_middleware.py @@ -350,4 +350,28 @@ class TestAlembicMigrations: with pytest.raises(Exception, match="Migration failed"): run_alembic_migrations() mock_upgrade.assert_called_once_with(mock_cfg, "head") +class TestPollingSuppressionMethods: + """_is_suppressed_request — method-aware polling suppression (ADR-0017/0021).""" + + # #region Test.AppModule.TestPollingPostBatchSuppressed [C:2] [TYPE Function] + def test_post_readonly_batch_suppressed(self): + from src.app import _is_suppressed_request + req = _make_mock_request("POST", "/api/git/repositories/status/batch") + assert _is_suppressed_request(req) is True + + def test_get_exact_poll_paths_suppressed(self): + from src.app import _is_suppressed_request + for path in ("/api/health/summary", "/api/validation-tasks/status/batch", + "/api/reports/log-stats"): + assert _is_suppressed_request(_make_mock_request("GET", path)) is True + + def test_mutating_post_never_suppressed(self): + from src.app import _is_suppressed_request + # Same path as a GET poll, but POST creates an event — framing must stay. + assert _is_suppressed_request(_make_mock_request("POST", "/api/maintenance/events")) is False + assert _is_suppressed_request(_make_mock_request("POST", "/api/reports")) is False + assert _is_suppressed_request(_make_mock_request("POST", "/api/tasks/run")) is False + # #endregion Test.AppModule.TestPollingPostBatchSuppressed + + # #endregion Test.AppModule.Middleware diff --git a/backend/tests/test_mcp_client_flow_http.py b/backend/tests/test_mcp_client_flow_http.py index e2d8ef5f1..89babc3ad 100644 --- a/backend/tests/test_mcp_client_flow_http.py +++ b/backend/tests/test_mcp_client_flow_http.py @@ -193,23 +193,26 @@ def test_scripted_machine_client_full_http_flow(registrant, mcp_signing_key) -> # #region Test.McpClientFlowHttp.PkceFlow [C:5] [TYPE Function] # @ingroup Test.McpClientFlowHttp -# @BRIEF Browser-mediated PKCE authorize (documented manual-token path) → user token → /mcp wire flow. +# @BRIEF Browser-mediated PKCE approval → user token → /mcp wire flow without exposing a web JWT +# to the public OAuth client. def test_scripted_user_client_pkce_http_flow(registrant, mcp_signing_key) -> None: user_jwt = _login(registrant["username"], registrant["password"]) oauth = TestClient(app) + metadata = oauth.get("/.well-known/oauth-authorization-server") + assert metadata.status_code == 200 + assert metadata.json()["authorization_endpoint"].endswith("/login?mcp_oauth=1") registration = oauth.post( "/oauth/register", json={"client_name": "desktop-mcp", "redirect_uris": ["http://localhost:9999/cb"], "scope": "mcp:read"}, - headers={"Authorization": f"Bearer {user_jwt}"}, ) assert registration.status_code == 201 client_id = registration.json()["client_id"] verifier = secrets.token_urlsafe(48) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii") - authorize = oauth.get( - "/oauth/authorize", - params={ + authorize = oauth.post( + "/api/oauth/authorize/approve", + json={ "client_id": client_id, "redirect_uri": "http://localhost:9999/cb", "code_challenge": challenge, @@ -219,10 +222,9 @@ def test_scripted_user_client_pkce_http_flow(registrant, mcp_signing_key) -> Non "state": "xyz", }, headers={"Authorization": f"Bearer {user_jwt}"}, - follow_redirects=False, ) - assert authorize.status_code == 302, authorize.text - location = urlparse(authorize.headers["location"]) + assert authorize.status_code == 200, authorize.text + location = urlparse(authorize.json()["redirect_url"]) query = parse_qs(location.query) assert query["state"] == ["xyz"] code = query["code"][0] diff --git a/backend/tests/test_mcp_oauth.py b/backend/tests/test_mcp_oauth.py index a614c4e57..a62eddb24 100644 --- a/backend/tests/test_mcp_oauth.py +++ b/backend/tests/test_mcp_oauth.py @@ -131,6 +131,40 @@ def test_client_registration_rejects_scope_escalation(monkeypatch) -> None: db.close() +# #region Test.McpOAuth.UserConnections [C:3] [TYPE Function] [SEMANTICS test,mcp,oauth,connection,revocation] +# @TEST_INVARIANT A user can see and revoke only their refresh-token family; no raw token appears. +def test_user_connection_revocation_is_scoped_to_its_refresh_family(monkeypatch) -> None: + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode() + monkeypatch.setenv("MCP_JWT_PRIVATE_KEY", pem) + load_key_material.cache_clear() + db, user = _db_and_user() + service = McpOAuthService(db) + registration = service.register_client( + "Loopback MCP Client", ["http://127.0.0.1:7777/callback"], ["mcp:read"], None + ) + verifier = "c" * 64 + challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() + code = service.create_code( + registration["client_id"], registration["redirect_uris"][0], challenge, "mcp:read", user + ) + tokens = service.exchange_code(code, registration["client_id"], registration["redirect_uris"][0], verifier) + + connections = service.list_user_connections(user) + assert len(connections) == 1 + assert connections[0]["client_name"] == "Loopback MCP Client" + assert tokens["refresh_token"] not in str(connections[0]) + + service.revoke_user_connection(connections[0]["family_id"], user) + assert service.list_user_connections(user)[0]["revoked_at"] is not None + with pytest.raises(ValueError, match="invalid_grant"): + service.refresh(tokens["refresh_token"], registration["client_id"]) + db.close() + + +# #endregion Test.McpOAuth.UserConnections + + def test_mcp_access_token_requires_mcp_audience(monkeypatch) -> None: key = rsa.generate_private_key(public_exponent=65537, key_size=2048) pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode() diff --git a/backend/tests/test_mcp_t029_bootstrap_automation.py b/backend/tests/test_mcp_t029_bootstrap_automation.py new file mode 100644 index 000000000..fb348f439 --- /dev/null +++ b/backend/tests/test_mcp_t029_bootstrap_automation.py @@ -0,0 +1,141 @@ +# #region Test.McpT029.BootstrapAutomation [C:4] [TYPE Module] [SEMANTICS test,mcp,bootstrap,automation,schema,idempotency] +# @BRIEF Focused T029 regression tests for bootstrap replay/conflict and automation input schemas. +# @RELATION VERIFIES -> [McpServer.BootstrapAuthoringScenario] +# @RELATION VERIFIES -> [McpServer.ToolsAutomation.Register] +# @TEST_INVARIANT Same bootstrap key returns the original three IDs and creates no duplicate registry rows. +# @TEST_EDGE changed_bootstrap_payload -> typed idempotency conflict before a second registry chain. +from __future__ import annotations + +import hashlib +from uuid import uuid4 + +import pytest +from pydantic import ValidationError + +from src.core.database import SessionLocal +from src.mcp_server import server as mcp_server +from src.mcp_server.auth import _access_token_context +from src.mcp_server.tools_automation import PolicyInput, ScheduleInput, TriggerInput +from src.models.agent_run import AgentRun, DraftArtifact +from src.models.agent_authoring_workspace import AgentAuthoringWorkspaceOperation +from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision + + +class _Storage: + def __init__(self, values: dict[str, bytes]): + self.values = values + + def retrieve(self, content_ref: str) -> bytes | None: + return self.values.get(content_ref) + + +def _seed_bootstrap_artifacts(user_id: str) -> tuple[str, _Storage]: + run_id = str(uuid4()) + pack = b"t029-scenario-pack" + plan = b"t029-runner-plan" + pack_sha = hashlib.sha256(pack).hexdigest() + plan_sha = hashlib.sha256(plan).hexdigest() + with SessionLocal() as db: + db.add(AgentRun( + id=run_id, user_id=user_id, intent="dashboard_scenario_build", trigger="manual", + dashboard_id="42", environment_id="env-preprod", context_snapshot={}, status="COMPLETED", + )) + db.add_all([ + DraftArtifact( + id=str(uuid4()), run_id=run_id, kind="scenario_pack", name="scenario.yaml", + intended_path="dashboard-tests/t029-smoke/scenario.yaml", content_ref=f"draft:{pack_sha}", + sha256=pack_sha, validation_status="valid", + ), + DraftArtifact( + id=str(uuid4()), run_id=run_id, kind="scenario_pack", name="runner.plan.json", + intended_path="dashboard-tests/t029-smoke/runner.plan.json", content_ref=f"draft:{plan_sha}", + sha256=plan_sha, validation_status="valid", + ), + ]) + db.commit() + pack_id = db.query(DraftArtifact).filter( + DraftArtifact.run_id == run_id, DraftArtifact.name == "scenario.yaml" + ).one().id + return pack_id, _Storage({f"draft:{pack_sha}": pack, f"draft:{plan_sha}": plan}) + + +def _unwrap(value): + return value[1] if isinstance(value, tuple) else value + + +# #region Test.McpT029.BootstrapReplay [C:4] [TYPE Function] [SEMANTICS test,mcp,bootstrap,idempotency,atomicity] +# @ingroup Test.McpT029.BootstrapAutomation +# @BRIEF Verify identical bootstrap replay and typed conflict without duplicate rows. +@pytest.mark.asyncio +async def test_bootstrap_replay_returns_original_ids_and_conflict_is_typed(monkeypatch) -> None: + principal = f"t029-{uuid4()}" + pack_id, storage = _seed_bootstrap_artifacts(principal) + monkeypatch.setattr("src.services.dashboard_testing.registry.create.get_draft_storage", lambda: storage) + server = mcp_server._build_probe_server() + monkeypatch.setattr(server, "_record", lambda **_: None) + token = _access_token_context.set(mcp_server.AccessToken( + token="t029-token", client_id="t029-client", scopes=["mcp"], subject=principal, + claims={"principal_type": "user"}, + )) + request = { + "idempotency_key": f"bootstrap-{uuid4()}", "title": "T029 smoke", "dashboard_id": 42, + "allowed_environment_ids": ["env-preprod"], "selected_case_ids": ["case-1"], + "objective": "Verify bootstrap", "compiled_handle_id": "", "draft_pack_id": pack_id, + "draft_pack_digest": hashlib.sha256(b"t029-scenario-pack").hexdigest(), + } + # create_initial validates the handle against the artifact run; derive the server-issued value. + with SessionLocal() as db: + run_id = db.query(AgentRun).filter(AgentRun.user_id == principal).one().id + request["compiled_handle_id"] = f"compile:{run_id}:{request['draft_pack_digest']}" + try: + first = _unwrap(await server.call_tool("bootstrap_authoring_scenario", {"request": request})) + replay = _unwrap(await server.call_tool("bootstrap_authoring_scenario", {"request": request})) + assert {replay[key] for key in ("scenario_id", "revision_id", "workspace_id")} == { + first[key] for key in ("scenario_id", "revision_id", "workspace_id") + } + assert replay["replayed"] is True + with SessionLocal() as db: + assert db.query(ScenarioRegistryEntry).filter_by(owner_id=principal).count() == 1 + assert db.query(ScenarioRevision).join(ScenarioRegistryEntry).filter( + ScenarioRegistryEntry.owner_id == principal + ).count() == 1 + assert db.query(AgentAuthoringWorkspaceOperation).filter_by( + operation="bootstrap_authoring_scenario", actor_principal=principal + ).count() == 1 + with pytest.raises(Exception, match="idempotency key conflicts with a different bootstrap request"): + await server.call_tool("bootstrap_authoring_scenario", { + "request": {**request, "objective": "changed"} + }) + with SessionLocal() as db: + assert db.query(ScenarioRegistryEntry).filter_by(owner_id=principal).count() == 1 + finally: + _access_token_context.reset(token) + +# #endregion Test.McpT029.BootstrapReplay + + +# #region Test.McpT029.AutomationSchemas [C:2] [TYPE Function] [SEMANTICS test,mcp,automation,schema] +# @ingroup Test.McpT029.BootstrapAutomation +# @BRIEF Verify strict automation models expose REST-compatible fields and reject extras. +def test_automation_inputs_are_strict_and_rest_shaped() -> None: + schedule = ScheduleInput( + scenario_id="scenario", revision_id="revision", environment_id="env", + idempotency_key="schedule-key", cron_expr="0 7 * * *", policy_id="policy", + ) + trigger = TriggerInput( + scenario_id="scenario", revision_id="revision", environment_id="env", + idempotency_key="trigger-key", trigger="release_created", conditions={"branch": "main"}, + ) + policy = PolicyInput(idempotency_key="policy-key", name="safe") + assert schedule.revision_policy == "current" + assert trigger.conditions == {"branch": "main"} + assert policy.max_concurrent_per_env == 1 + with pytest.raises(ValidationError): + ScheduleInput( + scenario_id="scenario", revision_id="revision", environment_id="env", + idempotency_key="key", cron_expr="* * * * *", unexpected="value", + ) + +# #endregion Test.McpT029.AutomationSchemas + +# #endregion Test.McpT029.BootstrapAutomation diff --git a/build.sh b/build.sh index 9e4728da5..4327dfcc9 100755 --- a/build.sh +++ b/build.sh @@ -439,6 +439,9 @@ services: AUTH_SECRET_KEY: \${AUTH_SECRET_KEY:?Set AUTH_SECRET_KEY in .env} ENCRYPTION_KEY: \${ENCRYPTION_KEY:?Set ENCRYPTION_KEY in .env} SERVICE_JWT: \${SERVICE_JWT:?Set SERVICE_JWT in .env} + MCP_ALLOWED_HOSTS: \${MCP_ALLOWED_HOSTS:-127.0.0.1:*,localhost:*,[::1]:*} + MCP_ALLOWED_ORIGINS: \${MCP_ALLOWED_ORIGINS:-http://127.0.0.1:*,http://localhost:*,http://[::1]:*} + FORWARDED_ALLOW_IPS: \${FORWARDED_ALLOW_IPS:-*} ENABLE_BELIEF_STATE_LOGGING: \${ENABLE_BELIEF_STATE_LOGGING:-true} TASK_LOG_LEVEL: \${TASK_LOG_LEVEL:-INFO} INITIAL_ADMIN_CREATE: \${INITIAL_ADMIN_CREATE:-false} @@ -451,7 +454,7 @@ services: FEATURES__HEALTH_MONITOR: \${FEATURES__HEALTH_MONITOR:-true} CERTS_PATH: /opt/certs ports: - - "\${BACKEND_HOST_PORT:-8001}:8000" + - "127.0.0.1:\${BACKEND_HOST_PORT:-8001}:8000" volumes: - ./storage:/app/storage - \${CERTS_PATH:-./certs}:/opt/certs:ro @@ -781,6 +784,8 @@ services: AUTH_SECRET_KEY: ${AUTH_SECRET_KEY:?Set AUTH_SECRET_KEY} ENCRYPTION_KEY: ${ENCRYPTION_KEY:?Set ENCRYPTION_KEY} SERVICE_JWT: ${SERVICE_JWT:?Set SERVICE_JWT} + MCP_ALLOWED_HOSTS: ${MCP_ALLOWED_HOSTS:-127.0.0.1:*,localhost:*,[::1]:*} + MCP_ALLOWED_ORIGINS: ${MCP_ALLOWED_ORIGINS:-http://127.0.0.1:*,http://localhost:*,http://[::1]:*} INITIAL_ADMIN_CREATE: ${INITIAL_ADMIN_CREATE:-false} INITIAL_ADMIN_USERNAME: ${INITIAL_ADMIN_USERNAME:-admin} INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:-} diff --git a/docker-compose.enterprise-clean.yml b/docker-compose.enterprise-clean.yml index dd641f86e..e07ac1d64 100644 --- a/docker-compose.enterprise-clean.yml +++ b/docker-compose.enterprise-clean.yml @@ -65,6 +65,10 @@ services: RESET_DATABASE_SCHEMA: ${RESET_DATABASE_SCHEMA:-true} BACKEND_PORT: 8000 ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-} + MCP_ALLOWED_HOSTS: ${MCP_ALLOWED_HOSTS:-127.0.0.1:*,localhost:*,[::1]:*} + MCP_ALLOWED_ORIGINS: ${MCP_ALLOWED_ORIGINS:-http://127.0.0.1:*,http://localhost:*,http://[::1]:*} + FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-*} + SERVICE_JWT: ${SERVICE_JWT:?Set SERVICE_JWT in .env} AUTH_SECRET_KEY: ${AUTH_SECRET_KEY:?Set AUTH_SECRET_KEY in .env} ENCRYPTION_KEY: ${ENCRYPTION_KEY:?ENCRYPTION_KEY обязателен — сгенерируйте и укажите в .env} ENABLE_BELIEF_STATE_LOGGING: ${ENABLE_BELIEF_STATE_LOGGING:-true} @@ -81,7 +85,7 @@ services: # Путь до сертификатов внутри контейнера — всегда /opt/certs CERTS_PATH: /opt/certs ports: - - "${BACKEND_HOST_PORT:-8001}:8000" + - "127.0.0.1:${BACKEND_HOST_PORT:-8001}:8000" volumes: # Единая точка хранения: бэкапы → /app/storage/backups/, git-repos → /app/storage/repositories/, LLM-скриншоты → /app/storage/screenshots/ - ./storage:/app/storage diff --git a/docker-compose.yml b/docker-compose.yml index 2a8e89242..93f617f6e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -35,6 +35,10 @@ services: RESET_DATABASE_SCHEMA: ${RESET_DATABASE_SCHEMA:-false} BACKEND_PORT: 8000 ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-} + MCP_ALLOWED_HOSTS: ${MCP_ALLOWED_HOSTS:-127.0.0.1:*,localhost:*,[::1]:*} + MCP_ALLOWED_ORIGINS: ${MCP_ALLOWED_ORIGINS:-http://127.0.0.1:*,http://localhost:*,http://[::1]:*} + # Trust the internal nginx proxy; bind the direct backend port to loopback below. + FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-*} INITIAL_ADMIN_CREATE: ${INITIAL_ADMIN_CREATE:-false} INITIAL_ADMIN_USERNAME: ${INITIAL_ADMIN_USERNAME:-admin} INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:-} @@ -43,7 +47,7 @@ services: SERVICE_JWT: ${SERVICE_JWT:?Set SERVICE_JWT in .env — do not use a public default for the service secret} LLM_CA_CERT_URLS: ${LLM_CA_CERT_URLS:-} ports: - - "${BACKEND_HOST_PORT:-8001}:8000" + - "127.0.0.1:${BACKEND_HOST_PORT:-8001}:8000" volumes: - ./storage:/app/storage - ${CERTS_PATH:-./certs}:/opt/certs:ro diff --git a/docker/nginx.conf b/docker/nginx.conf index c578032e6..c4fe4caf7 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -9,7 +9,6 @@ # @INVARIANT /api/ and /ws/ preserve request URI, Authorization, and X-Trace-ID headers. # @RATIONALE stdout JSON logs survive container log aggregation and make nginx/backend event correlation queryable. # @REJECTED Nginx HTTPS in this file rejected — SSL variant selected only when certificates exist. -# #endregion docker.nginx.conf map $http_upgrade $connection_upgrade { default upgrade; @@ -59,6 +58,23 @@ server { proxy_read_timeout 300s; } + # Same public origin for Streamable HTTP, OAuth and RFC 9728 discovery. + # @RATIONALE Preserve the external port and stream SSE without buffering. + # @REJECTED SPA fallback for MCP paths returned HTML instead of protocol responses. + location ~ ^/(mcp(?:/|$)|oauth/|\.well-known/) { + set $backend_mcp http://backend:8000; + proxy_pass $backend_mcp; + proxy_http_version 1.1; + proxy_set_header Host $http_host; + proxy_set_header Connection ""; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Trace-ID $http_x_trace_id; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + } + location /ws/ { set $backend_ws http://backend:8000; proxy_pass $backend_ws; @@ -73,3 +89,4 @@ server { proxy_read_timeout 300s; } } +# #endregion docker.nginx.conf diff --git a/docker/nginx.ssl.conf b/docker/nginx.ssl.conf index dfb144958..92925d0fb 100644 --- a/docker/nginx.ssl.conf +++ b/docker/nginx.ssl.conf @@ -14,7 +14,6 @@ # preserving Authorization and X-Trace-ID headers. # @RATIONALE stdout JSON logs survive container log aggregation and make nginx/backend event correlation queryable. # @REJECTED Прокси на HTTPS внутри compose-сети отвергнут — избыточно. -# #endregion docker.nginx.ssl.conf map $http_upgrade $connection_upgrade { default upgrade; @@ -90,4 +89,21 @@ server { proxy_set_header X-Trace-ID $http_x_trace_id; proxy_read_timeout 300s; } + + # @RATIONALE OAuth metadata must retain the external HTTPS authority; SSE must stream. + # @REJECTED SPA fallback for MCP paths returned HTML instead of protocol responses. + location ~ ^/(mcp(?:/|$)|oauth/|\.well-known/) { + set $backend_mcp http://backend:8000; + proxy_pass $backend_mcp; + proxy_http_version 1.1; + proxy_set_header Host $http_host; + proxy_set_header Connection ""; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Trace-ID $http_x_trace_id; + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + } } +# #endregion docker.nginx.ssl.conf diff --git a/docs/2026-09-05-ss-tools-mcp-tool-audit.md b/docs/2026-09-05-ss-tools-mcp-tool-audit.md new file mode 100644 index 000000000..007a2560a --- /dev/null +++ b/docs/2026-09-05-ss-tools-mcp-tool-audit.md @@ -0,0 +1,77 @@ +# ss-tools MCP tool audit — 2026-09-05 + +## Scope + +Exercise every currently exposed `ss_tools` MCP tool with one valid-path probe and, where the MCP boundary permits it safely, one orthogonal invalid/boundary probe. Record tool output, state effect, and an operator-comprehension score. + +## Safety decision + +Read-only probes may use `ss-prod` and `ss-dev`. Mutating probes use `ss-dev` only, with uniquely named disposable resources and idempotency keys. Operations that can alter deployment state, apply migrations, back up data, or otherwise affect shared infrastructure are invoked only when their server-side contract returns a guarded/no-op/approval-required response; actual execution is excluded unless a target, rollback procedure, and explicit production authorization are supplied. + +@RATIONALE The request authorizes mutation testing, but it does not identify a safe production target or recovery procedure. `ss-dev` confines normal test data; server-side approval gates remain authoritative. +@REJECTED Treating a request to test every tool as authorization to execute migrations/deployments in production. + +## Scope update — 2026-09-05 + +The requester explicitly selected `ss-prod` for all remaining probes. Dashboard-scoped probes target `Sales Dashboard` (ID `11`). Approval-gated operations are still denied after the gate lifecycle is tested: this exercises the mutating tool and its authorization boundary without dispatching a production migration, deployment, backup, or dashboard write. + +## Test matrix + +1. Inventory/environment and Superset read tools. +2. Dashboard/data mutations using disposable `mcp-audit-*` resources in `ss-dev`. +3. Authoring/scenario workflow including CAS and invalid-input edges. +4. Operations/approval/LLM tools, respecting server guards. +5. Persist observations, scores (clarity, input discoverability, outcome legibility; each 1–5), and residual risks. + +## Results + +### Coverage + +All 47 MCP tools exposed under `mcp__ss_tools__*` were invoked. The test types were: + +| Group | Tools | Valid paths observed | Edge paths observed | +|---|---:|---|---| +| Inventory and health | 7 | environments, health, LLM, maintenance and approval listings | empty collections reported explicitly | +| Superset read/data | 7 | production dashboard search, database listing and SQL formatting | DEV authentication returned 502; invalid database returned structured 404; PROD SQL was explicitly rejected | +| Dashboard/repository mutations | 9 | every applicable write request reached an ApprovalGate | gates denied; no write dispatched | +| Scenario and authoring | 14 | authoring session, test plan, compilation and validation | not-found, unbound-workspace, unsupported-spec and CAS/state errors | +| Baseline/verification/LLM | 10 | request acceptance/guarding boundary | missing reference, validation and approval-gate errors | + +### Confirmed behavior + +- `inspect_scenario` compiled Sales Dashboard (ID 11) case `B01` into one step; `validate_scenario` returned `valid: true`. +- `propose_test_plan` persisted the Sales Dashboard plan with CAS advancing from 0 to 1. +- `ss-prod` exposes two databases: `examples` (PostgreSQL) and `ClickHouse Connect (Superset)`. +- Mutating dashboard, repository, backup, maintenance, dataset, LLM and baseline operations returned a stable `approval_required` envelope with a gate ID, invocation ID and request hash. +- Every audit-created gate was decided `deny`; a final pending-approvals read returned an empty list. +- Production SQL is denied deliberately by `superset_execute_sql`; this is a clear server-side safety policy. + +### Edge-case findings + +| Observation | Assessment | +|---|---| +| `ss-dev` Superset authentication failed consistently with HTTP 502 for dashboard, database, SQL-format and permissions reads. | Infrastructure blocker; error includes category and HTTP status, but no remediation hint. | +| Invalid dashboard database IDs produce structured 404 context. | Good error taxonomy. | +| Several scenario tools distinguish `not_found`, missing graph proposal, missing scenario, and unbound workspace. | Good state-machine visibility. | +| `start_exploration` rejects unsupported specification keys. | Safe, but the accepted shape is not discoverable from the MCP schema because it is an untyped map. | +| `decide_checkpoint` exposes regex/range constraints in validation output. | Strong boundary feedback. | +| `deploy_dashboard` and `execute_migration` were policy-blocked before reaching the MCP server. | Correct safety stop. A dedicated deploy/migration request with target scope and rollback plan is required for execution testing. | + +### Understandability scores + +Scores are 1 (unclear) to 5 (immediately actionable) from an MCP-client/operator perspective. + +| Dimension | Score | Basis | +|---|---:|---| +| Tool naming and grouping | 4/5 | Verb-led names map well to the authoring, scenario, Superset and approval domains. | +| Input discoverability | 3/5 | Strict typed requests are excellent; several `unknown`/map-shaped payloads (`generate_draft_pack`, `scenario_resolve`, exploration specs) hide their real contract. | +| Success outcome legibility | 4/5 | Status plus IDs, CAS version, request hash and gate ID make outcomes auditable. | +| Error and edge feedback | 4/5 | Validation, not-found and policy rejection messages are specific. DEV 502 lacks an operator next step. | +| Safety model clarity | 5/5 | ApprovalGate envelopes and explicit PROD SQL refusal are unambiguous. | +| Overall | **4.0/5** | Strong guarded workflow; document map-shaped contracts and DEV authentication recovery to reduce operator guesswork. | + +## Residual risks and recommendations + +1. Restore or document the `ss-dev` Superset authentication path before relying on development probes. +2. Publish JSON schemas/examples for opaque request maps, particularly graph operations, scenario resolution and exploration specifications. +3. Keep ApprovalGate denial as the default for audits. To test actual deployment or migration dispatch, require a separate request identifying the exact production target, maintenance window, expected state, rollback plan and approver. diff --git a/frontend/src/lib/__tests__/routes-link-integrity.test.ts b/frontend/src/lib/__tests__/routes-link-integrity.test.ts index 1550e88cd..9df08b6df 100644 --- a/frontend/src/lib/__tests__/routes-link-integrity.test.ts +++ b/frontend/src/lib/__tests__/routes-link-integrity.test.ts @@ -158,8 +158,17 @@ const INTERNAL_PREFIXES = [ "/dashboards", "/datasets", "/migration", "/git", "/translate", "/validation", "/reports", "/settings", "/admin", "/storage", "/tools", "/profile", "/maintenance", "/login", "/agent", + "/dashboard-testing", "/load-testing", ]; +/** + * Prefixes where a hardcoded route string wrapped in `$app/paths` resolve() is also a SSOT + * bypass. Scoped to the dashboard-testing / load-testing trees (Fix 4): these previously used + * local resolve("/dashboard-testing/...") strings that skirted both the ROUTES registry and the + * href/goto detector above. Other domains' pre-existing resolve() usage is out of this fix's scope. + */ +const RESOLVE_BYPASS_PREFIXES = ["/dashboard-testing", "/load-testing"]; + describe("raw href/goto strings", () => { const SRC_DIR = path.resolve(process.cwd(), "src"); const extensions = [".svelte", ".ts"]; @@ -218,6 +227,14 @@ describe("raw href/goto strings", () => { violations.push({ file: path.relative(process.cwd(), file), line: i + 1, match: cleanLine }); } } + // Targeted check: resolve("/dashboard-testing|/load-testing ...") bypassing ROUTES (Fix 4 SSOT) + for (const prefix of RESOLVE_BYPASS_PREFIXES) { + const resolveRegex = new RegExp(`resolve\\([\`'"]${prefix}`); + if (resolveRegex.test(line)) { + const cleanLine = line.trim().substring(0, 120); + violations.push({ file: path.relative(process.cwd(), file), line: i + 1, match: cleanLine }); + } + } // Targeted check: goto('/', ...) or goto("/", ...) should use ROUTES.home() if (/\bgoto\(\s*[\'"]\/[\'"]/.test(line)) { const cleanLine = line.trim().substring(0, 120); diff --git a/frontend/src/lib/__tests__/routes.test.ts b/frontend/src/lib/__tests__/routes.test.ts index e69a4cb6a..fd07b1f14 100644 --- a/frontend/src/lib/__tests__/routes.test.ts +++ b/frontend/src/lib/__tests__/routes.test.ts @@ -196,6 +196,10 @@ describe('ROUTES — admin', () => { it('admin.llmSettings returns "/admin/settings/llm"', () => { expect(ROUTES.admin.llmSettings()).toBe('/admin/settings/llm'); }); + + it('admin.mcp returns "/admin/mcp"', () => { + expect(ROUTES.admin.mcp()).toBe('/admin/mcp'); + }); }); describe('ROUTES — storage', () => { @@ -236,4 +240,41 @@ describe('ROUTES — dynamic route encoding', () => { expect(ROUTES.dashboards.detail('a b', 'env')).toBe('/dashboards/a%20b?env_id=env'); }); }); + +describe('ROUTES — dashboardTesting (Fix 4 SSOT)', () => { + it('scenarios returns the registry hub', () => { + expect(ROUTES.dashboardTesting.scenarios()).toBe('/dashboard-testing/scenarios'); + }); + + it('scenarioEdit / scenarioAnalytics encode the scenario id', () => { + expect(ROUTES.dashboardTesting.scenarioEdit('s1')).toBe('/dashboard-testing/scenarios/s1/edit'); + expect(ROUTES.dashboardTesting.scenarioAnalytics('s1')).toBe('/dashboard-testing/scenarios/s1/analytics'); + }); + + it('runDetail encodes scenario id and run id', () => { + expect(ROUTES.dashboardTesting.runDetail('s1', 'r1')).toBe('/dashboard-testing/scenarios/s1/runs/r1'); + }); + + it('runs / analytics / automation return the global hubs', () => { + expect(ROUTES.dashboardTesting.runs()).toBe('/dashboard-testing/runs'); + expect(ROUTES.dashboardTesting.runs(true)).toBe('/dashboard-testing/runs?waiting_for_me=true'); + expect(ROUTES.dashboardTesting.analytics()).toBe('/dashboard-testing/analytics'); + expect(ROUTES.dashboardTesting.automation()).toBe('/dashboard-testing/automation'); + }); + + it('analyticsCase encodes the case id', () => { + expect(ROUTES.dashboardTesting.analyticsCase('c1')).toBe('/dashboard-testing/analytics/cases/c1'); + }); + + it('encodes special characters in scenario ids', () => { + expect(ROUTES.dashboardTesting.scenarioEdit('a/b')).toBe('/dashboard-testing/scenarios/a%2Fb/edit'); + }); +}); + +describe('ROUTES — loadTesting (Fix 4 SSOT)', () => { + it('detail coerces numbers and encodes ids', () => { + expect(ROUTES.loadTesting.detail(42)).toBe('/load-testing/42'); + expect(ROUTES.loadTesting.detail('a b')).toBe('/load-testing/a%20b'); + }); +}); // #endregion Tests.Routes.RoutesRegistryTest diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 416b1ee36..bc0b30493 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1277,6 +1277,20 @@ export const api = { revokeApiKey: (keyId: string) => requestApi(`/admin/api-keys/${keyId}`, 'DELETE'), // #endregion Api.ApiModule.RevokeApiKey + // ═══ MCP Governance (UX audit Fix 5) ════════════════════════════ + + // #region Api.ApiModule.GetMcpCatalog [C:2] [TYPE Function] [SEMANTICS admin,api,mcp,governance,catalog] + // @BRIEF Admin governance projection of the MCP tool surface (admin:roles READ). + // @LAYER API + // @RELATION DEPENDS_ON -> [Api.ApiModule.FetchApi] + // @DATA_CONTRACT response -> { catalog_version, endpoint_path, discovery_path, tool_count, + // tools: {name,risk_level,requires_approval,service_allowed,deprecated,deprecation_note, + // required_resource,required_action}[], roles: {role_id,name,description,is_admin, + // visible_count,visible_tools:string[]}[], client_count, clients: {client_id,client_name, + // client_type,is_revoked,created_at,scopes:string[],redirect_uris:string[]}[] } + getMcpCatalog: () => fetchApi('/admin/mcp/catalog'), + // #endregion Api.ApiModule.GetMcpCatalog + // #region Api.ApiModule.GetEncryptionHealth [C:2] [TYPE Function] [SEMANTICS security,encryption,health] // @BRIEF Inventory all stored encrypted secrets and report broken ones. getEncryptionHealth: () => fetchApi('/security/encryption/health'), diff --git a/frontend/src/lib/components/agent/HandoffSurface.svelte b/frontend/src/lib/components/agent/HandoffSurface.svelte index d76c45b30..066ee5798 100644 --- a/frontend/src/lib/components/agent/HandoffSurface.svelte +++ b/frontend/src/lib/components/agent/HandoffSurface.svelte @@ -1,20 +1,26 @@ - + - + - - + + + + + @@ -70,16 +115,50 @@

{t.assistant?.handoff_title || "Assistant moved to MCP"}

{t.assistant?.handoff_description || "The legacy assistant surface is no longer available. Connect an MCP client to continue."}

+ +
-

{t.assistant?.handoff_connection_label || "MCP connection hint"}

- {t.assistant?.handoff_connection_hint || "Use the Superset Tools MCP server configured for your workspace."} +

{t.assistant?.handoff_endpoint_label || "MCP server URL"}

+
+ {mcpEndpoint} + +
+

{t.assistant?.handoff_discovery_label || "Discovery (OAuth protected resource)"}

+ {discoveryUrl}
+ + +
+

{t.assistant?.handoff_steps_title || "How to connect"}

+
    + {#each onboardingSteps as step (step)} +
  1. {step}
  2. + {/each} +
+

{t.assistant?.handoff_docs_hint || "Details: docs/INSTALL.md → the «MCP client» section."}

+
+ +
+

Codex

+
{codexAddCommand}
+{codexLoginCommand}
+

The login command opens the secure browser authorization flow; no token is copied into configuration.

+ +
+ +

{t.assistant?.handoff_prompt_label || "Copyable prompt"}

{handoffPrompt}

diff --git a/frontend/src/lib/components/agent/__tests__/handoff-surface.context.test.ts b/frontend/src/lib/components/agent/__tests__/handoff-surface.context.test.ts index 2ccd53c5e..47f527943 100644 --- a/frontend/src/lib/components/agent/__tests__/handoff-surface.context.test.ts +++ b/frontend/src/lib/components/agent/__tests__/handoff-surface.context.test.ts @@ -37,4 +37,27 @@ describe("HandoffSurface dashboard-context prompt (050 Story 5 AC2)", () => { expect(screen.getByText(/MCP-серверу Superset Tools|Superset Tools MCP server/)).toBeTruthy(); }); }); + +describe("HandoffSurface actionable connection guidance (UX audit Fix 1)", () => { + it("renders the real MCP endpoint derived from the current origin", () => { + render(HandoffSurface, { props: {} }); + // $app/state is mocked with http://localhost -> endpoint is origin-derived, never hardcoded + expect(screen.getByTestId("mcp-endpoint").textContent).toContain("http://localhost/mcp"); + }); + + it("renders the OAuth discovery URL for advanced clients", () => { + render(HandoffSurface, { props: {} }); + expect(screen.getByTestId("mcp-discovery").textContent).toContain( + "/.well-known/oauth-protected-resource/mcp", + ); + }); + + it("renders a three-step onboarding list plus copy-URL and copy-prompt controls", () => { + const { container } = render(HandoffSurface, { props: {} }); + const steps = container.querySelector("ol"); + expect(steps?.children.length).toBe(3); + expect(screen.getByRole("button", { name: /Скопировать URL|Copy URL/ })).toBeTruthy(); + expect(screen.getByRole("button", { name: /Скопировать промпт|Copy prompt/ })).toBeTruthy(); + }); +}); // #endregion Test.Agent.HandoffSurfaceContext diff --git a/frontend/src/lib/components/layout/Sidebar.svelte b/frontend/src/lib/components/layout/Sidebar.svelte index ab448d6ed..c9535c4c6 100644 --- a/frontend/src/lib/components/layout/Sidebar.svelte +++ b/frontend/src/lib/components/layout/Sidebar.svelte @@ -4,6 +4,7 @@ + @@ -11,6 +12,7 @@ + @@ -24,7 +26,9 @@ import { SvelteSet } from "svelte/reactivity"; setActiveItem, closeMobile, } from "$lib/stores/sidebar.svelte.js"; - import { healthStore, failingCount } from "$lib/stores/health.svelte.js"; + import { healthStore, failingCount } from "$lib/stores/health.svelte.js"; + import { scenarioWaitingCount, refreshScenarioWaiting } from "$lib/stores/scenarioRuns.svelte.js"; + import { hasPermission } from "$lib/auth/permissions.js"; import { onMount, untrack } from "svelte"; import { t } from "$lib/i18n/index.svelte.js"; import { auth } from "$lib/auth/store.svelte.js"; @@ -60,11 +64,22 @@ import { SvelteSet } from "svelte/reactivity"; ); let activeItem = $derived(sidebarStore.value?.activeItem || "/dashboards"); let isMobileOpen = $derived(Boolean(sidebarStore.value?.isMobileOpen)); - let failingDashboardCount = $derived(failingCount.current || 0); - let expandedCategories = new SvelteSet(["dashboards"]); - let expandedSections = new SvelteSet(["resources", "operations", "system"]); + let failingDashboardCount = $derived(failingCount.current || 0); + let scenarioWaiting = $derived(scenarioWaitingCount.current || 0); + let expandedCategories = new SvelteSet(["dashboards"]); + let expandedSections = new SvelteSet(["resources", "operations", "system"]); - let user = $derived(_authState.user || null); + let user = $derived(_authState.user || null); + + // Poll the waiting-for-me scenario-run count only for users who can open the run center + // (scenario:RUN). The badge turns the approval loop into a discoverable signal instead of a + // page the analyst must already know. Browser-side side effect -> $effect (cleanup on change). + $effect(() => { + if (!hasPermission(user, "scenario", "RUN")) return; + refreshScenarioWaiting(); + const id = setInterval(() => refreshScenarioWaiting(), 60_000); + return () => clearInterval(id); + }); function withExpandedCategory(categoryId) { expandedCategories.add(categoryId); @@ -145,6 +160,16 @@ import { SvelteSet } from "svelte/reactivity"; } } + // Waiting badge deep-links straight into the run center's "awaiting my decision" view. The click + // stops propagation so it navigates instead of toggling the category expansion. + function openWaitingRuns(event) { + event.stopPropagation(); + closeMobile(); + if (browser) { + window.location.href = ROUTES.dashboardTesting.runs(true); + } + } + function handleToggleClick(event) { event.stopPropagation(); toggleSidebar(); @@ -317,6 +342,12 @@ import { SvelteSet } from "svelte/reactivity"; class="absolute -top-1 -right-1 flex h-2.5 w-2.5 items-center justify-center rounded-full bg-destructive ring-2 ring-white" > {/if} + {#if !isExpanded && category.id === "dashboard_testing" && scenarioWaiting > 0} + + {/if} {#if isExpanded} {/if} + {#if category.id === "dashboard_testing" && scenarioWaiting > 0} + + {/if} {/if} {#if isExpanded} diff --git a/frontend/src/lib/components/layout/TopNavbar.svelte b/frontend/src/lib/components/layout/TopNavbar.svelte index a08724f44..286c3c801 100644 --- a/frontend/src/lib/components/layout/TopNavbar.svelte +++ b/frontend/src/lib/components/layout/TopNavbar.svelte @@ -265,15 +265,15 @@ {/if} - + diff --git a/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts b/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts index aef3b3937..ed941f929 100644 --- a/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts +++ b/frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.ts @@ -60,6 +60,11 @@ const i18nState: I18nState = { admin_settings: "ADFS Config", admin_llm: "LLM Providers", profile: "Profile", + dashboard_testing: "Dashboard Testing", + dt_scenarios: "Scenarios", + dt_runs: "Runs", + dt_analytics: "Analytics", + dt_automation: "Automation", }, }; @@ -149,6 +154,7 @@ describe("sidebarNavigation", () => { "/admin/roles", "/admin/settings", "/admin/settings/llm", + "/admin/mcp", ]); }); @@ -203,5 +209,50 @@ describe("sidebarNavigation", () => { } }); }); + + // ── Fix 2: the dashboard-testing category makes the approval loop reachable ── + describe("dashboard testing category (Fix 2)", () => { + it("is shown to an admin with all four RBAC-gated subitems", () => { + const user = makeUser([{ name: "Admin", permissions: [] }]); + const categories = buildSidebarSections(i18nState, user).flatMap((s) => s.categories); + const testing = categories.find((c) => c.id === "dashboard_testing"); + + expect(testing).toBeDefined(); + expect(testing!.path).toBe("/dashboard-testing"); + expect(testing!.subItems.map((i: { path: string }) => i.path)).toEqual([ + "/dashboard-testing/scenarios", + "/dashboard-testing/runs", + "/dashboard-testing/analytics", + "/dashboard-testing/automation", + ]); + }); + + it("lives in the operations section (no new top-level section id)", () => { + const user = makeUser([{ name: "Admin", permissions: [] }]); + const sections = buildSidebarSections(i18nState, user); + expect(sections.map((s) => s.id)).toEqual(["resources", "operations", "system"]); + const operations = sections.find((s) => s.id === "operations"); + expect(operations?.categories.some((c) => c.id === "dashboard_testing")).toBe(true); + }); + + it("shows only the runs hub to a user holding just scenario:RUN", () => { + const user = makeUser([ + { name: "Runner", permissions: [{ resource: "scenario", action: "RUN" }] }, + ]); + const categories = buildSidebarSections(i18nState, user).flatMap((s) => s.categories); + const testing = categories.find((c) => c.id === "dashboard_testing"); + + expect(testing).toBeDefined(); + expect(testing!.subItems.map((i: { path: string }) => i.path)).toEqual(["/dashboard-testing/runs"]); + }); + + it("is hidden entirely when the user has no testing permissions", () => { + const user = makeUser([ + { name: "Viewer", permissions: [{ resource: "plugin:migration", action: "READ" }] }, + ]); + const categories = buildSidebarSections(i18nState, user).flatMap((s) => s.categories); + expect(categories.find((c) => c.id === "dashboard_testing")).toBeUndefined(); + }); + }); }); // #endregion Tests.SidebarNavigation.SidebarNavigationTestModule diff --git a/frontend/src/lib/components/layout/sidebarNavigation.ts b/frontend/src/lib/components/layout/sidebarNavigation.ts index 312376462..fe74985dd 100644 --- a/frontend/src/lib/components/layout/sidebarNavigation.ts +++ b/frontend/src/lib/components/layout/sidebarNavigation.ts @@ -176,6 +176,23 @@ export function buildSidebarSections(i18nState: I18nNavState, user: User | null { label: nav.validation_history, path: "/validation-tasks/history", requiredPermission: "validation.run", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" }, ], }, + { + // 042/044/045/046/047 dashboard-testing workspace. No category-level permission: + // visibility is derived from the RBAC-gated subitems (registry read / run / result / + // automation). Each subitem mirrors its exact backend has_permission gate so the nav + // never advertises a route the user cannot open. The runs hub is the human approval loop. + id: "dashboard_testing", + label: nav.dashboard_testing, + icon: "clipboard", + tone: "from-category-testing-from to-category-testing-to text-category-testing-text ring-category-testing-ring", + path: "/dashboard-testing", + subItems: [ + { label: nav.dt_scenarios, path: "/dashboard-testing/scenarios", requiredPermission: "dashboard:testing", requiredAction: "READ" }, + { label: nav.dt_runs, path: "/dashboard-testing/runs", requiredPermission: "scenario", requiredAction: "RUN" }, + { label: nav.dt_analytics, path: "/dashboard-testing/analytics", requiredPermission: "scenario:result", requiredAction: "VIEW" }, + { label: nav.dt_automation, path: "/dashboard-testing/automation", requiredPermission: "scenario:automation", requiredAction: "TRIGGER" }, + ], + }, { id: "reports", label: nav.reports, @@ -220,6 +237,7 @@ export function buildSidebarSections(i18nState: I18nNavState, user: User | null { label: nav.admin_roles, path: "/admin/roles", requiredPermission: "admin:roles", requiredAction: "READ" }, { label: nav.admin_settings, path: "/admin/settings", requiredPermission: "admin:settings", requiredAction: "READ" }, { label: nav.admin_llm, path: "/admin/settings/llm", requiredPermission: "admin:settings", requiredAction: "READ" }, + { label: nav.admin_mcp, path: "/admin/mcp", requiredPermission: "admin:roles", requiredAction: "READ" }, ], }, { diff --git a/frontend/src/lib/components/scenario-analytics/AgentActionTimeline.svelte b/frontend/src/lib/components/scenario-analytics/AgentActionTimeline.svelte index b2db6ac70..d3f6bb39a 100644 --- a/frontend/src/lib/components/scenario-analytics/AgentActionTimeline.svelte +++ b/frontend/src/lib/components/scenario-analytics/AgentActionTimeline.svelte @@ -4,21 +4,24 @@ -
-

Таймлайн действий

+
+

{dt.agent_timeline_title}

{#if actions.length === 0}

- Действий ещё нет + {dt.agent_timeline_empty}

{:else}
    @@ -39,4 +42,4 @@
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/CaseWorkspace.svelte b/frontend/src/lib/components/scenario-analytics/CaseWorkspace.svelte index a806a871f..b8eb804e3 100644 --- a/frontend/src/lib/components/scenario-analytics/CaseWorkspace.svelte +++ b/frontend/src/lib/components/scenario-analytics/CaseWorkspace.svelte @@ -10,14 +10,18 @@ -
+
-

Кейс расследования

+

{dt.case_title}

{model.case?.scenario_id ?? "…"} · v{model.decisionVersion}

@@ -54,55 +61,66 @@ {#if model.case}
-
Fingerprint
+
{dt.fingerprint}
{model.case.fingerprint}
-
Decision version
+
{dt.decision_version}
{model.decisionVersion}
{/if} {#if model.loading} -

Загрузка кейса…

+

{dt.case_loading}

{:else if model.error} {:else if model.case}
-
-

Disposition

+
+

{dt.case_close_title}

- Компактная triage-проекция; исторический результат запуска не изменяется. + {dt.case_close_hint}

{#if isTerminal} -

Кейс закрыт: {model.case?.disposition ?? "—"}

+

{dt.case_closed}: {model.case?.disposition ?? "—"}

{:else}
- + {#if selectedDisposition === "resolved"} + + {:else} + + {/if} +
{/if}
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/HealthCard.svelte b/frontend/src/lib/components/scenario-analytics/HealthCard.svelte index 6c06b7f4d..7920b2cc9 100644 --- a/frontend/src/lib/components/scenario-analytics/HealthCard.svelte +++ b/frontend/src/lib/components/scenario-analytics/HealthCard.svelte @@ -2,13 +2,16 @@ -
-

Здоровье сценария

{health?.source ?? 'unknown'}
+
+

{dt.health_title}

{health?.source ?? 'unknown'}

{health?.overall_attention ?? health?.health ?? 'unknown'}

- {#if health?.success_rate !== null && health?.success_rate !== undefined}

Успешность: {(health.success_rate * 100).toFixed(1)}%

{/if} - {#if health?.flakiness_ratio !== null && health?.flakiness_ratio !== undefined}

Flakiness: {(health.flakiness_ratio * 100).toFixed(1)}%

{/if} + {#if health?.success_rate !== null && health?.success_rate !== undefined}

{dt.health_success_rate}: {(health.success_rate * 100).toFixed(1)}%

{/if} + {#if health?.flakiness_ratio !== null && health?.flakiness_ratio !== undefined}

{dt.health_flakiness}: {(health.flakiness_ratio * 100).toFixed(1)}%

{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/QueueList.svelte b/frontend/src/lib/components/scenario-analytics/QueueList.svelte index 02d728cd8..208eb342b 100644 --- a/frontend/src/lib/components/scenario-analytics/QueueList.svelte +++ b/frontend/src/lib/components/scenario-analytics/QueueList.svelte @@ -6,6 +6,7 @@ -
+
-

Очередь расследований

- {items.length} attention item(s) +

{dt.queue_title}

+ {items.length} {dt.queue_count}
{#if loading} -

Загрузка очереди…

+

{dt.queue_loading}

{:else if error} {:else if items.length === 0}

- Очередь пуста — нет нерасследованных сигналов + {dt.queue_empty}

{:else}
    @@ -62,10 +65,10 @@ + >{dt.queue_investigate} {/each}
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/RecurringFailuresList.svelte b/frontend/src/lib/components/scenario-analytics/RecurringFailuresList.svelte index 640d7b4bf..38ac7e257 100644 --- a/frontend/src/lib/components/scenario-analytics/RecurringFailuresList.svelte +++ b/frontend/src/lib/components/scenario-analytics/RecurringFailuresList.svelte @@ -5,10 +5,13 @@ -
+
-

Повторяющиеся отказы

- {groups.length} group(s) +

{dt.failures_title}

+ {groups.length} {dt.failures_count}
{#if groups.length === 0}

- Повторяющихся отказов не обнаружено + {dt.failures_empty}

{:else}
    @@ -39,11 +42,11 @@

    {group.fingerprint.slice(0, 24)}…

    - Шаг {group.logical_step_id} · {group.compatibility_family} + {dt.failures_step} {group.logical_step_id} · {group.compatibility_family}

    - {group.count} occurrence(s) + {group.count} {dt.failures_occurrences}

    @@ -63,4 +66,4 @@

{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/TrendsChart.svelte b/frontend/src/lib/components/scenario-analytics/TrendsChart.svelte index 2642d8a1d..810ccfaf8 100644 --- a/frontend/src/lib/components/scenario-analytics/TrendsChart.svelte +++ b/frontend/src/lib/components/scenario-analytics/TrendsChart.svelte @@ -6,10 +6,13 @@ -
+
-

Тренд успешности

+

{dt.trend_title}

{#if trends} scenario {trends.scenario_id.slice(0, 8)} {/if} @@ -59,7 +62,7 @@ {#if series.length === 0}

- Нет истории запусков для построения тренда + {dt.trend_empty}

{:else}
@@ -67,9 +70,9 @@ viewBox={`0 0 ${WIDTH} ${HEIGHT}`} class="w-full" role="img" - aria-label="График успешности сценария по запускам с накопительной линией" + aria-label={dt.trend_chart_aria} > - Тренд успешности: {series.length} запусков + {dt.trend_chart_title} {series.length} {dt.trend_runs} {#each gridLines as line (line.rate)} - Накопительная успешность + {dt.trend_cumulative} - passed + {dt.trend_passed} - failed + {dt.trend_failed} - прочее + {dt.trend_other}
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-analytics/__tests__/CaseWorkspace.test.ts b/frontend/src/lib/components/scenario-analytics/__tests__/CaseWorkspace.test.ts index 91ed1bcdb..792b47cfc 100644 --- a/frontend/src/lib/components/scenario-analytics/__tests__/CaseWorkspace.test.ts +++ b/frontend/src/lib/components/scenario-analytics/__tests__/CaseWorkspace.test.ts @@ -36,7 +36,7 @@ describe("CaseWorkspace", () => { expect(screen.getByText("Кейс расследования")).toBeTruthy(); expect(screen.getByText("Таймлайн действий")).toBeTruthy(); expect(screen.getByText("case_opened")).toBeTruthy(); - expect(screen.getByRole("button", { name: "Записать disposition" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Закрыть кейс" })).toBeTruthy(); }); it("records disposition with the last-known CAS decision version", async () => { @@ -44,20 +44,20 @@ describe("CaseWorkspace", () => { const model = modelWith(); render(CaseWorkspace, { props: { model } }); - await fireEvent.click(screen.getByRole("button", { name: "Записать disposition" })); + await fireEvent.click(screen.getByRole("button", { name: "Закрыть кейс" })); await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); const [endpoint, options] = fetchMock.mock.calls[0] as [string, { body?: string }]; expect(endpoint).toBe("/scenario-analytics/cases/case-1/disposition"); - expect(JSON.parse(options.body ?? "{}")).toEqual({ disposition: "confirmed", expected_version: 1 }); + expect(JSON.parse(options.body ?? "{}")).toEqual({ disposition: "resolved", expected_version: 1, verification_evidence: { reconciled: true } }); expect(model.decisionVersion).toBe(2); expect(model.status).toBe("resolved"); }); it("hides the disposition form for terminal cases and shows the recorded disposition", () => { - render(CaseWorkspace, { props: { model: modelWith({ status: "resolved", case: { id: "case-1", fingerprint: "fp-1", scenario_id: "s1", status: "resolved", disposition: "fixed", decision_version: 3, created_at: null } }) } }); - expect(screen.queryByRole("button", { name: "Записать disposition" })).toBeNull(); - expect(screen.getByText(/fixed/)).toBeTruthy(); + render(CaseWorkspace, { props: { model: modelWith({ status: "resolved", case: { id: "case-1", fingerprint: "fp-1", scenario_id: "s1", status: "resolved", disposition: "resolved", decision_version: 3, created_at: null } }) } }); + expect(screen.queryByRole("button", { name: "Закрыть кейс" })).toBeNull(); + expect(screen.getByText("Кейс закрыт: resolved")).toBeTruthy(); }); it("surfaces a conflict error with a reload recovery action", () => { diff --git a/frontend/src/lib/components/scenario-automation/AutomationPanel.svelte b/frontend/src/lib/components/scenario-automation/AutomationPanel.svelte index 4ea2d1665..05c988ada 100644 --- a/frontend/src/lib/components/scenario-automation/AutomationPanel.svelte +++ b/frontend/src/lib/components/scenario-automation/AutomationPanel.svelte @@ -5,6 +5,7 @@ -
+
-

Автоматизация сценариев

- +

{dt.automation_title}

+
{#if error}{/if} - {#if loading}

Загрузка…

{/if} + {#if loading}

{dt.automation_loading}

{/if} {#if metrics}
-

Расписаний

{metrics.schedules_total} ({metrics.schedules_enabled} on)

-

Trigger-правил

{metrics.trigger_rules_total}

-

Успешность

{(metrics.success_rate * 100).toFixed(1)}%

-

Активных прогонов

{metrics.active_runs}

+

{dt.automation_schedules}

{metrics.schedules_total} ({metrics.schedules_enabled} on)

+

{dt.automation_trigger_rules}

{metrics.trigger_rules_total}

+

{dt.automation_success_rate}

{(metrics.success_rate * 100).toFixed(1)}%

+

{dt.automation_active_runs}

{metrics.active_runs}

{#if metrics.alerts_count > 0}

Repeated-failure alerts: {metrics.alerts_count}

@@ -114,15 +117,15 @@ {/if}
-

Новое расписание

+

{dt.automation_new_schedule}

-

Расписания

- {#if schedules.length === 0}

Нет расписаний

{/if} +

{dt.automation_schedules_title}

+ {#if schedules.length === 0}

{dt.automation_no_schedules}

{/if}
    {#each schedules as schedule (schedule.id)}
  • @@ -132,7 +135,7 @@
{schedule.enabled ? 'enabled' : 'disabled'} - +
{/each} @@ -140,8 +143,8 @@
-

Trigger-правила

- {#if triggerRules.length === 0}

Нет trigger-правил

{/if} +

{dt.automation_trigger_rules_title}

+ {#if triggerRules.length === 0}

{dt.automation_no_rules}

{/if}
    {#each triggerRules as rule (rule.id)}
  • @@ -150,10 +153,10 @@ · {rule.environment_id} · {rule.revision_policy}
- - +
{/each} @@ -161,8 +164,8 @@
-

Политики

- {#if policies.length === 0}

Нет политик

{/if} +

{dt.automation_policies}

+ {#if policies.length === 0}

{dt.automation_no_policies}

{/if}
    {#each policies as policy (policy.id)}
  • @@ -170,10 +173,10 @@ {policy.name} · max={policy.max_concurrent_per_env} · overlap={policy.overlap_rule} · retention={policy.retention_days}d{policy.prod_gate_required ? ' · PROD gate' : ''}
- + {/each}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-automation/ScheduleForm.svelte b/frontend/src/lib/components/scenario-automation/ScheduleForm.svelte index c61cf7336..bc12c53cf 100644 --- a/frontend/src/lib/components/scenario-automation/ScheduleForm.svelte +++ b/frontend/src/lib/components/scenario-automation/ScheduleForm.svelte @@ -3,8 +3,11 @@ diff --git a/frontend/src/lib/components/scenario-editor/AgentActionPanel.svelte b/frontend/src/lib/components/scenario-editor/AgentActionPanel.svelte index d3a506e46..422189632 100644 --- a/frontend/src/lib/components/scenario-editor/AgentActionPanel.svelte +++ b/frontend/src/lib/components/scenario-editor/AgentActionPanel.svelte @@ -5,6 +5,7 @@ -
-

Редактирование с помощью агента

+
+

{dt.agent_title}

- Опишите сложное изменение или добавьте типовые операции. Предложение создаётся на сервере и сохраняется с атрибуцией. + {dt.agent_description}

{#if model.savedRevision}
- Revision {model.savedRevision.revision_id.slice(0, 12)} создан ({model.savedRevision.activation_status}). - + Revision {model.savedRevision.revision_id.slice(0, 12)} {dt.agent_saved_created} ({model.savedRevision.activation_status}). +
{:else if model.proposal}
-

Digest {model.proposal.digest.slice(0, 12)}… · статус {model.proposal.status}

+

{dt.agent_digest_prefix} {model.proposal.digest.slice(0, 12)}… · {dt.agent_status} {model.proposal.status}

- - + +
{:else}
- Типовая операция + {dt.agent_operation} {#if comparison !== "exact" && comparison !== "row_set"} {/if}
- +
{#if opError}{/if} {#if ops.length > 0} -
    +
      {#each ops as op, i (op.logical_step_id + i)}
    • set_assertion · {op.logical_step_id} · {op.comparison} · {op.baseline_ref} - +
    • {/each}
    {/if}
    - - {#if busy}Обработка…{/if} + + {#if busy}{dt.agent_processing}{/if}
{/if} @@ -146,4 +149,4 @@ {/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-editor/ConstrainedAssertionEditor.svelte b/frontend/src/lib/components/scenario-editor/ConstrainedAssertionEditor.svelte index 61c2ff71e..25e09b22b 100644 --- a/frontend/src/lib/components/scenario-editor/ConstrainedAssertionEditor.svelte +++ b/frontend/src/lib/components/scenario-editor/ConstrainedAssertionEditor.svelte @@ -3,6 +3,8 @@ -
-

Утверждение шага

+
+

{dt.assert_title}

{#if comparison !== "exact" && comparison !== "row_set"} {/if}
{#if error}{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-editor/EditRevisionDiff.svelte b/frontend/src/lib/components/scenario-editor/EditRevisionDiff.svelte index d6bbf357c..10c22c49f 100644 --- a/frontend/src/lib/components/scenario-editor/EditRevisionDiff.svelte +++ b/frontend/src/lib/components/scenario-editor/EditRevisionDiff.svelte @@ -3,6 +3,8 @@ -
-

Разница правок

+
+

{dt.diff_title}

{#if empty} -

Изменений нет.

+

{dt.diff_empty}

{:else}
    {#each added as key (key)} @@ -44,4 +47,4 @@
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-editor/VisualDagCanvas.svelte b/frontend/src/lib/components/scenario-editor/VisualDagCanvas.svelte index 147233463..67435cbec 100644 --- a/frontend/src/lib/components/scenario-editor/VisualDagCanvas.svelte +++ b/frontend/src/lib/components/scenario-editor/VisualDagCanvas.svelte @@ -3,29 +3,33 @@ -
-

Зависимости шагов

+
+

{dt.dag_title}

- - - + + +
{#if error}{/if}
    {#each dependencies as edge}
  • {edge.source} → {edge.target}
  • {/each}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/HumanCheckpointPanel.svelte b/frontend/src/lib/components/scenario-run/HumanCheckpointPanel.svelte index 31abecc19..e1f60c331 100644 --- a/frontend/src/lib/components/scenario-run/HumanCheckpointPanel.svelte +++ b/frontend/src/lib/components/scenario-run/HumanCheckpointPanel.svelte @@ -2,17 +2,19 @@ -
-

Требуется решение аналитика

+
+

{dt.checkpoint_title}

    {#each evidenceRefs as ref (ref)}
  • {ref}
  • {/each}
- -
- - - -
+ +
+ + + +
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/RunComparison.svelte b/frontend/src/lib/components/scenario-run/RunComparison.svelte index 51622d5d8..76a174512 100644 --- a/frontend/src/lib/components/scenario-run/RunComparison.svelte +++ b/frontend/src/lib/components/scenario-run/RunComparison.svelte @@ -2,17 +2,20 @@ -
+
-

Сравнение scenario runs

- Scenario run +

{dt.comparison_title}

+ {dt.runs_kind_badge}
{#if comparison.revision_warning} - + {/if}
{JSON.stringify(comparison.step_deltas, null, 2)}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/RunConfigurationPanel.svelte b/frontend/src/lib/components/scenario-run/RunConfigurationPanel.svelte index 11928ebc1..8de17c358 100644 --- a/frontend/src/lib/components/scenario-run/RunConfigurationPanel.svelte +++ b/frontend/src/lib/components/scenario-run/RunConfigurationPanel.svelte @@ -7,6 +7,7 @@ -
-

Конфигурация запуска сценария

-

Scenario run — отличается от Verification run (релизная проверка) и Load test (нагрузка).

+
+

{dt.run_config_title}

+

{dt.run_config_subtitle}

- Параметры + {dt.run_config_params}
{#each paramRows as row, i (i)}
- - - + + +
{/each} - +
- Шаги сценария + {dt.run_config_steps}
    {#each mandatorySteps as step (step)}
  • - + {step} - обязательный + {dt.run_config_required}
  • {/each}
- Дополнительная диагностика (опционально) + {dt.run_config_diagnostics}
@@ -192,25 +195,25 @@ PROD approval gate (036)
{/if} @@ -223,11 +226,11 @@ disabled={isProd && !gateReady} onclick={emitLaunch} > - {isProd ? "Запустить в PROD" : "Запустить сценарий"} + {isProd ? dt.run_config_run_prod : dt.run_config_run} {#if isProd && !gateReady} - Заполните gate для запуска. + {dt.run_config_fill_gate} {/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/RunHistoryList.svelte b/frontend/src/lib/components/scenario-run/RunHistoryList.svelte index eaa927d10..1c90e2342 100644 --- a/frontend/src/lib/components/scenario-run/RunHistoryList.svelte +++ b/frontend/src/lib/components/scenario-run/RunHistoryList.svelte @@ -2,16 +2,19 @@ -
+
-

История scenario runs

-

Verification run (037) и Load test (040) показываются в своих разделах.

+

{dt.history_title}

+

{dt.history_note}

{#if runs.length === 0} -

Запусков сценария нет.

+

{dt.history_empty}

{:else}
    {#each runs as run (run.id)} @@ -20,11 +23,11 @@

    {run.scenario_id}

    {run.created_at ?? ""}

    - Scenario run + {dt.runs_kind_badge} {run.status} · {run.environment_id} {/each}
{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/RunTimeline.svelte b/frontend/src/lib/components/scenario-run/RunTimeline.svelte index 6de531865..db39b242b 100644 --- a/frontend/src/lib/components/scenario-run/RunTimeline.svelte +++ b/frontend/src/lib/components/scenario-run/RunTimeline.svelte @@ -2,19 +2,21 @@ -
+
-

Ход выполнения scenario run

- Scenario run +

{dt.timeline_title}

+ {dt.runs_kind_badge}
-

Не путать с Verification run (037) и Load test (040).

+

{dt.timeline_note}

{#if steps.length === 0} -

Шаги ещё не поступили.

+

{dt.timeline_empty}

{:else}
    {#each steps as step (step.id)} @@ -26,7 +28,7 @@ {/each}
-

{started} из {steps.length} шагов стартовали

+

{started} {dt.timeline_of} {steps.length} {dt.timeline_steps_started}

{/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/ScenarioResultView.svelte b/frontend/src/lib/components/scenario-run/ScenarioResultView.svelte index 89703cfaa..5f85dcc44 100644 --- a/frontend/src/lib/components/scenario-run/ScenarioResultView.svelte +++ b/frontend/src/lib/components/scenario-run/ScenarioResultView.svelte @@ -2,17 +2,20 @@ -
+
-

Результат scenario run

- Scenario run +

{dt.result_title}

+ {dt.runs_kind_badge}
{result.status} - Не Verification run (037) и не Load test (040) + {dt.result_note}
Passed
{result.passed}
@@ -21,8 +24,8 @@
Inconclusive
{result.inconclusive}
{#if result.failures && result.failures.length > 0} -
- Проваленные шаги ({result.failures.length}) +
+ {dt.result_failed_summary} ({result.failures.length})
    {#each result.failures as failure (failure.logical_step_id)}
  • @@ -35,4 +38,4 @@ {/if}
    Provenance
    {JSON.stringify(result.provenance, null, 2)}
- + \ No newline at end of file diff --git a/frontend/src/lib/components/scenario-run/WaitingForMeView.svelte b/frontend/src/lib/components/scenario-run/WaitingForMeView.svelte index acd2d3191..61654b29f 100644 --- a/frontend/src/lib/components/scenario-run/WaitingForMeView.svelte +++ b/frontend/src/lib/components/scenario-run/WaitingForMeView.svelte @@ -4,11 +4,14 @@ -
-

Ожидают моего решения

+
+

{dt.waiting_title}

{#if rows.length === 0} -

Нет запусков, ожидающих решения аналитика.

+

{dt.waiting_empty}

{:else}
    {#each rows as row (row.id)} @@ -31,32 +34,32 @@

    {row.scenario_name || row.scenario_key}

    - Scenario run · {row.environment_id} · шаг {row.pending_checkpoint.logical_step_id} + {dt.waiting_meta_run} · {row.environment_id} · {dt.waiting_step} {row.pending_checkpoint.logical_step_id}

    - waiting_human + {dt.waiting_human_badge} {#if row.pending_checkpoint.evidence_refs.length > 0} -
      +
        {#each row.pending_checkpoint.evidence_refs as ref (ref)}
      • {ref}
      • {/each}
      {/if}
      @@ -65,4 +68,4 @@
    {/if}
- + \ No newline at end of file diff --git a/frontend/src/lib/i18n/locales/en/admin.json b/frontend/src/lib/i18n/locales/en/admin.json index 02d4957c0..6900964d0 100644 --- a/frontend/src/lib/i18n/locales/en/admin.json +++ b/frontend/src/lib/i18n/locales/en/admin.json @@ -63,5 +63,50 @@ "save_configuration": "Save Configuration", "saved": "Saved", "ad_group_placeholder": "e.g. CN=SS_ADMINS,OU=Groups,DC=org" + }, + "mcp": { + "title": "MCP Governance", + "subtitle": "The MCP tool catalog, per-role visibility, and registered clients. Read-only.", + "server": "Server", + "catalog_version": "Catalog version", + "endpoint": "Endpoint", + "discovery": "Discovery (OAuth)", + "tools": "Tools", + "tools_total": "Total tools", + "col_tool": "Tool", + "col_risk": "Risk", + "col_permission": "Required permission", + "col_service": "Service", + "col_service_hint": "Whether service (machine) clients may call this tool", + "col_approval": "Approval", + "perm_auth_only": "Authenticated only", + "yes": "yes", + "no": "no", + "deprecated": "Deprecated", + "roles": "Visibility by role", + "roles_total": "Roles", + "col_role": "Role", + "col_visible": "Visible tools", + "admin_badge": "ADMIN", + "show_tools": "Show tools", + "hide_tools": "Hide tools", + "clients": "Clients (DCR)", + "clients_total": "Clients", + "col_client": "Client", + "col_client_id": "ID", + "col_type": "Type", + "col_created": "Created", + "col_scopes": "Scopes", + "revoked": "Revoked", + "active": "Active", + "empty_roles": "No roles configured.", + "empty_clients": "No registered clients.", + "loading": "Loading MCP catalog…", + "error": "Failed to load the MCP catalog", + "retry": "Retry", + "risk_safe": "safe", + "risk_guarded": "guarded", + "client_confidential": "confidential", + "client_public": "public" } } diff --git a/frontend/src/lib/i18n/locales/en/assistant.json b/frontend/src/lib/i18n/locales/en/assistant.json index 114ffd26c..86859c77f 100644 --- a/frontend/src/lib/i18n/locales/en/assistant.json +++ b/frontend/src/lib/i18n/locales/en/assistant.json @@ -187,5 +187,17 @@ "handoff_prompt_text": "Connect your MCP client to the Superset Tools MCP server, then review the current dashboard and propose the next safe action.", "handoff_context_label": "Dashboard context", "handoff_copy": "Copy prompt", - "handoff_copied": "Copied" + "handoff_copied": "Copied", + "handoff_endpoint_label": "MCP server URL", + "handoff_endpoint_copy": "Copy URL", + "handoff_endpoint_copied": "URL copied", + "handoff_discovery_label": "Discovery (OAuth protected resource)", + "handoff_steps_title": "How to connect", + "handoff_step1": "Install an MCP client — for example Claude Desktop or Cursor.", + "handoff_step2": "Add a server using the URL above (transport: streamable HTTP).", + "handoff_step3": "Use the registered OAuth client to complete its PKCE authorization request while signed in.", + "handoff_docs_hint": "Details: docs/INSTALL.md → the «MCP client» section.", + "mcp_entry_label": "MCP assistant", + "mcp_entry_short": "MCP", + "mcp_entry_tooltip": "Instructions to connect the AI assistant (MCP)" } diff --git a/frontend/src/lib/i18n/locales/en/dashboard-testing.json b/frontend/src/lib/i18n/locales/en/dashboard-testing.json index e76c83ec1..a318a6f0c 100644 --- a/frontend/src/lib/i18n/locales/en/dashboard-testing.json +++ b/frontend/src/lib/i18n/locales/en/dashboard-testing.json @@ -20,5 +20,272 @@ "start_failed": "The agent dialogue could not be started.", "ready_to_start": "Dashboard context loaded.", "retry_start": "Retry start", - "note": "UI state is derived from typed enums, never from these localized strings" + "note": "UI state is derived from typed enums, never from these localized strings", + "registry_title": "Scenario Registry", + "registry_subtitle": "Dashboard testing scenarios (042). Opening a scenario never starts an agent.", + "registry_runs_hub": "Run center →", + "registry_filters_label": "Registry filters", + "registry_search_label": "Search", + "registry_search_placeholder": "Scenario name or key", + "registry_status_label": "Status", + "registry_status_all": "All", + "registry_loading": "Loading registry…", + "registry_error": "Failed to load the registry", + "registry_retry": "Retry", + "registry_empty": "No scenarios found.", + "registry_list_label": "Scenario list", + "registry_owner": "owner", + "registry_envs": "environments", + "registry_edit": "Edit", + "registry_analytics": "Analytics", + "registry_last_run": "Last run", + "registry_total": "Total", + "registry_owner_label": "Owner", + "registry_owner_placeholder": "owner username", + "registry_tag_label": "Tag", + "registry_tag_placeholder": "tag", + "registry_dashboard_label": "Dashboard", + "registry_dashboard_placeholder": "dashboard id", + "registry_pagination_label": "Registry pagination", + "registry_page": "Page", + "registry_prev": "Previous", + "registry_next": "Next", + "runs_title": "Scenario runs", + "runs_subtitle": "Global Run Operations Center · scenario runs (not 037 verification runs, not 040 load tests).", + "runs_back_scenarios": "← Scenarios", + "runs_automation": "Automation", + "runs_waiting_me": "Waiting for my decision", + "runs_waiting_me_aria": "Only those waiting for my decision", + "runs_filters_aria": "Run filters", + "runs_status": "Status", + "runs_scenario": "Scenario", + "runs_environment": "Environment", + "runs_trigger": "Trigger", + "runs_owner": "Owner", + "runs_all": "All", + "runs_loading": "Loading runs…", + "runs_error": "Failed to load runs", + "runs_retry": "Retry", + "runs_empty": "No runs found.", + "runs_total": "Total", + "runs_list_aria": "Scenario run list", + "runs_kind_badge": "Scenario run", + "waiting_title": "Waiting for my decision", + "waiting_empty": "No runs awaiting an analyst decision.", + "waiting_meta_run": "Scenario run", + "waiting_step": "step", + "waiting_evidence_aria": "Evidence", + "waiting_comment_placeholder": "Comment", + "waiting_comment_aria": "Comment for", + "waiting_human_badge": "Waiting for human", + "waiting_disposition_confirm": "Confirm issue", + "waiting_disposition_false_positive": "False positive", + "waiting_disposition_inconclusive": "Insufficient data", + "ls_DRAFT": "Draft", + "ls_READY": "Ready", + "ls_STALE": "Stale", + "ls_NEEDS_REVALIDATION": "Needs revalidation", + "ls_BLOCKED": "Blocked", + "ls_DISABLED": "Disabled", + "ls_DEPRECATED": "Deprecated", + "ls_ARCHIVED": "Archived", + "health_pass": "pass", + "health_attention": "attention", + "health_warn": "warn", + "health_fail": "fail", + "health_none": "none", + "health_unknown": "unknown", + "retry": "Retry", + "loading": "Loading…", + "delete_action": "Delete", + "case_workspace_aria": "Case workspace", + "case_title": "Investigation case", + "case_loading": "Loading case…", + "case_disposition_aria": "Disposition record", + "case_close_title": "Close case", + "case_close_hint": "Closing does not change the historical run result. For resolved, confirm the evidence reconciliation; for accepted, state the accepted risk rationale.", + "case_closed": "Case closed", + "case_disposition_kind": "Disposition kind", + "case_disposition_resolved": "Resolved — reconciliation confirmed", + "case_disposition_accepted": "Accepted — risk accepted", + "case_evidence_label": "Reconciled evidence reference", + "case_evidence_placeholder": "run id or artifact reference", + "case_rationale_label": "Accepted risk rationale", + "case_rationale_placeholder": "Why the risk is accepted", + "case_close_button": "Close case", + "fingerprint": "Fingerprint", + "decision_version": "Decision version", + "queue_aria": "Investigation queue", + "queue_title": "Investigation queue", + "queue_count": "attention item(s)", + "queue_loading": "Loading queue…", + "queue_empty": "Queue is empty — no uninvestigated signals", + "queue_investigate": "Investigate with agent", + "trend_aria": "Success trend", + "trend_title": "Success trend", + "trend_empty": "No run history to build a trend", + "trend_chart_aria": "Scenario success-rate chart by run with a cumulative line", + "trend_chart_title": "Success trend:", + "trend_runs": "runs", + "trend_cumulative": "Cumulative success", + "trend_passed": "passed", + "trend_failed": "failed", + "trend_other": "other", + "agent_timeline_aria": "Agent action timeline", + "agent_timeline_title": "Action timeline", + "agent_timeline_empty": "No actions yet", + "failures_aria": "Recurring failures", + "failures_title": "Recurring failures", + "failures_count": "groups", + "failures_empty": "No recurring failures detected", + "failures_step": "Step", + "failures_occurrences": "times", + "health_aria": "Scenario health", + "health_title": "Scenario health", + "health_success_rate": "Success rate", + "health_flakiness": "Flakiness", + "analytics_subtitle": "Opening a case is explicit — the queue never starts an agent on its own.", + "analytics_runs_link": "Scenario runs →", + "case_page_case": "Case", + "case_page_note": "a disposition never rewrites the historical run truth.", + "case_page_back": "← Investigation queue", + "scenario_analytics_prefix": "Scenario", + "scenario_analytics_title": "Scenario analytics", + "scenario_analytics_subtitle": "health, trend and recurring failures from run history.", + "scenario_analytics_back": "← Scenario registry", + "scenario_analytics_loading": "Loading analytics…", + "scenario_analytics_error": "Failed to load analytics", + "scenario_analytics_empty": "Analytics unavailable — no run history", + "editor_title": "Scenario editor", + "editor_back": "← Registry", + "editor_loading": "Loading editor…", + "editor_error": "Failed to load the scenario", + "editor_graph_aria": "Verification graph", + "editor_graph_title": "Verification graph", + "editor_graph_hint": "Changes pass server-side validation before a revision is saved.", + "editor_steps_empty": "No steps", + "editor_state_title": "State", + "editor_state_hint": "The base revision is pinned to guard against stale saves.", + "editor_ready_title": "Changes ready to save", + "editor_save": "Save revision", + "editor_saved": "Created revision", + "monitor_title": "Scenario run monitor", + "monitor_back": "← Scenario runs", + "monitor_run_prefix": "Run", + "monitor_scenario_run": "Scenario run (not 037 verification run, not 040 load test)", + "monitor_recovering": "Recovering the run by run id…", + "monitor_error": "Failed to load the run", + "monitor_cancel": "Cancel run", + "monitor_state_title": "State", + "monitor_state_hint": "Elapsed — events update the timeline.", + "automation_aria": "Scenario automation", + "automation_title": "Scenario automation", + "automation_subtitle": "Schedule/trigger management for scenario runs (not the 009 cron scheduler, not 037 verification runs).", + "automation_reload": "Refresh", + "automation_loading": "Loading…", + "automation_schedules": "Schedules", + "automation_trigger_rules": "Trigger rules", + "automation_success_rate": "Success rate", + "automation_active_runs": "Active runs", + "automation_new_schedule": "New schedule", + "automation_schedules_title": "Schedules", + "automation_no_schedules": "No schedules", + "automation_remove_schedule": "Delete schedule", + "automation_trigger_rules_title": "Trigger rules", + "automation_no_rules": "No trigger rules", + "automation_toggle_rule": "Toggle rule", + "automation_remove_rule": "Delete rule", + "automation_policies": "Policies", + "automation_no_policies": "No policies", + "automation_remove_policy": "Delete policy", + "automation_error_load": "Failed to load automation", + "schedule_error_save": "Failed to save the schedule", + "checkpoint_aria": "Analyst decision required", + "checkpoint_title": "Analyst decision required", + "timeline_aria": "Scenario run progress", + "timeline_title": "Scenario run progress", + "timeline_note": "Not to be confused with verification runs (037) and load tests (040).", + "timeline_empty": "No steps received yet.", + "timeline_of": "of", + "timeline_steps_started": "steps started", + "comparison_aria": "Scenario run comparison", + "comparison_title": "Scenario run comparison", + "comparison_warn": "The runs use different revisions — the comparison may be unreliable.", + "history_aria": "Scenario run history", + "history_title": "Scenario run history", + "history_note": "Verification runs (037) and load tests (040) are shown in their own sections.", + "history_empty": "No scenario runs.", + "result_aria": "Scenario run result", + "result_title": "Scenario run result", + "result_note": "Not a verification run (037), not a load test (040)", + "result_failed_aria": "Failed steps", + "result_failed_summary": "Failed steps", + "run_config_aria": "Scenario run configuration", + "run_config_title": "Scenario run configuration", + "run_config_subtitle": "Scenario run — distinct from a verification run (release check) and a load test.", + "run_config_env": "Environment", + "run_config_select_env": "Select an environment", + "run_config_baseline_none": "No baseline set", + "run_config_params": "Parameters", + "run_config_param_name": "Parameter name", + "run_config_param_value": "Parameter value", + "run_config_remove_param": "Remove parameter", + "run_config_add_param": "Add parameter", + "run_config_steps": "Scenario steps", + "run_config_required_step": "Required step", + "run_config_required": "required", + "run_config_diagnostics": "Extra diagnostics (optional)", + "run_config_screenshots": "Screenshots", + "run_config_verbose_logs": "Verbose logs", + "run_config_vlm": "VLM commentary", + "run_config_gate_concurrency": "Concurrency ceiling", + "run_config_gate_volume": "Expected volume", + "run_config_gate_blast": "Dependent blast radius", + "run_config_gate_reason": "Reason", + "run_config_gate_confirm_aria": "Confirm PROD gate", + "run_config_gate_confirm_label": "I confirm: the PROD run complies with the 036 approval policy.", + "run_config_run_prod": "Run in PROD", + "run_config_run": "Run scenario", + "run_config_fill_gate": "Fill in the gate to run.", + "run_config_error_env": "Select an environment.", + "run_config_error_gate": "For PROD, fill in the gate: concurrency, volume, dependent blast radius and reason.", + "assert_aria": "Step assertion", + "assert_title": "Step assertion", + "assert_operator": "Operator", + "assert_operator_exact": "Exact match", + "assert_operator_absolute": "Absolute difference", + "assert_operator_relative": "Relative difference", + "assert_operator_range": "Range", + "assert_operator_row_set": "Row set", + "assert_threshold": "Threshold", + "assert_error_baseline": "Select an approved baseline.", + "dag_aria": "Step dependencies", + "dag_title": "Step dependencies", + "dag_source_aria": "Source step", + "dag_target_aria": "Target step", + "dag_add": "Add", + "dag_error_self": "A dependency must link two different steps.", + "dag_error_dup": "This dependency already exists.", + "agent_aria": "Agent-assisted editing", + "agent_title": "Agent-assisted editing", + "agent_description": "Describe a complex change or add routine operations. The proposal is built server-side and saved with attribution.", + "agent_saved_created": "created", + "agent_new_proposal": "New proposal", + "agent_digest_prefix": "Digest", + "agent_status": "status", + "agent_accept": "Accept and save revision", + "agent_cancel": "Cancel", + "agent_request": "Agent request", + "agent_request_placeholder": "e.g. add an XLSX comparison across phases 1–2", + "agent_operation": "Routine operation", + "agent_logical_step": "Logical step", + "agent_add_operation": "Add operation", + "agent_operations_aria": "Proposal operations", + "agent_remove_operation": "Remove operation", + "agent_propose": "Create proposal", + "agent_processing": "Processing…", + "agent_error": "Specify a step and an approved baseline reference.", + "diff_aria": "Edit diff", + "diff_title": "Edit diff", + "diff_empty": "No changes." } diff --git a/frontend/src/lib/i18n/locales/en/nav.json b/frontend/src/lib/i18n/locales/en/nav.json index 746b7e66a..e8f037d7a 100644 --- a/frontend/src/lib/i18n/locales/en/nav.json +++ b/frontend/src/lib/i18n/locales/en/nav.json @@ -52,8 +52,16 @@ "admin_settings_desc": "ADFS configuration and group mappings", "admin_llm": "LLM Providers", "admin_llm_desc": "Configure LLM providers", + "admin_mcp": "MCP", + "admin_mcp_desc": "MCP tool catalog, per-role visibility, and clients", "profile": "Profile", "sign_out": "Sign Out", "dashboard": "Dashboards", - "settings_git": "Git Servers" + "settings_git": "Git Servers", + "dashboard_testing": "Dashboard Testing", + "dt_scenarios": "Scenarios", + "dt_runs": "Runs", + "dt_analytics": "Analytics", + "dt_automation": "Automation", + "dt_waiting_badge": "Runs waiting for my decision" } diff --git a/frontend/src/lib/i18n/locales/ru/admin.json b/frontend/src/lib/i18n/locales/ru/admin.json index a32128fd1..ee75043b5 100644 --- a/frontend/src/lib/i18n/locales/ru/admin.json +++ b/frontend/src/lib/i18n/locales/ru/admin.json @@ -63,5 +63,50 @@ "save_configuration": "Сохранить конфигурацию", "saved": "Сохранено", "ad_group_placeholder": "например, CN=SS_ADMINS,OU=Groups,DC=org" + }, + "mcp": { + "title": "MCP-гувернанс", + "subtitle": "Каталог инструментов MCP, видимость по ролям и зарегистрированные клиенты. Только чтение.", + "server": "Сервер", + "catalog_version": "Версия каталога", + "endpoint": "Endpoint", + "discovery": "Discovery (OAuth)", + "tools": "Инструменты", + "tools_total": "Всего инструментов", + "col_tool": "Инструмент", + "col_risk": "Риск", + "col_permission": "Требуемое право", + "col_service": "Сервис", + "col_service_hint": "Разрешён ли вызов инструмента сервисным (machine) клиентам", + "col_approval": "Одобрение", + "perm_auth_only": "Только авторизация", + "yes": "да", + "no": "нет", + "deprecated": "Устарел", + "roles": "Видимость по ролям", + "roles_total": "Ролей", + "col_role": "Роль", + "col_visible": "Видит инструментов", + "admin_badge": "АДМИН", + "show_tools": "Показать инструменты", + "hide_tools": "Скрыть инструменты", + "clients": "Клиенты (DCR)", + "clients_total": "Клиентов", + "col_client": "Клиент", + "col_client_id": "ID", + "col_type": "Тип", + "col_created": "Создан", + "col_scopes": "Скоупы", + "revoked": "Отозван", + "active": "Активен", + "empty_roles": "Роли не настроены.", + "empty_clients": "Зарегистрированных клиентов нет.", + "loading": "Загрузка MCP-каталога…", + "error": "Не удалось загрузить MCP-каталог", + "retry": "Повторить", + "risk_safe": "безопасный", + "risk_guarded": "охраняемый", + "client_confidential": "конфиденциальный", + "client_public": "публичный" } } diff --git a/frontend/src/lib/i18n/locales/ru/assistant.json b/frontend/src/lib/i18n/locales/ru/assistant.json index 21b65b512..8fc7227f5 100644 --- a/frontend/src/lib/i18n/locales/ru/assistant.json +++ b/frontend/src/lib/i18n/locales/ru/assistant.json @@ -187,5 +187,17 @@ "handoff_prompt_text": "Подключите MCP-клиент к MCP-серверу Superset Tools, затем проверьте текущий дашборд и предложите следующий безопасный шаг.", "handoff_context_label": "Контекст дашборда", "handoff_copy": "Скопировать промпт", - "handoff_copied": "Скопировано" + "handoff_copied": "Скопировано", + "handoff_endpoint_label": "URL MCP-сервера", + "handoff_endpoint_copy": "Скопировать URL", + "handoff_endpoint_copied": "URL скопирован", + "handoff_discovery_label": "Discovery (OAuth protected resource)", + "handoff_steps_title": "Как подключить", + "handoff_step1": "Установите MCP-клиент — например, Claude Desktop или Cursor.", + "handoff_step2": "Добавьте сервер по URL выше (транспорт: streamable HTTP).", + "handoff_step3": "Войдите в Superset Tools и завершите PKCE-запрос авторизации, который откроет зарегистрированный OAuth-клиент.", + "handoff_docs_hint": "Подробности: docs/INSTALL.md → раздел «MCP клиент».", + "mcp_entry_label": "MCP-ассистент", + "mcp_entry_short": "MCP", + "mcp_entry_tooltip": "Инструкция по подключению AI-ассистента (MCP)" } diff --git a/frontend/src/lib/i18n/locales/ru/dashboard-testing.json b/frontend/src/lib/i18n/locales/ru/dashboard-testing.json index 2f11d9d1a..e38dbd4ee 100644 --- a/frontend/src/lib/i18n/locales/ru/dashboard-testing.json +++ b/frontend/src/lib/i18n/locales/ru/dashboard-testing.json @@ -20,5 +20,272 @@ "start_failed": "Не удалось запустить диалог агента.", "ready_to_start": "Контекст дашборда загружен.", "retry_start": "Повторить запуск", - "note": "Состояние UI определяется типизированными enum, а не этими строками" + "note": "Состояние UI определяется типизированными enum, а не этими строками", + "registry_title": "Реестр сценариев", + "registry_subtitle": "Сценарии тестирования дашбордов (042). Открытие сценария не запускает агент.", + "registry_runs_hub": "Центр запусков →", + "registry_filters_label": "Фильтры реестра", + "registry_search_label": "Поиск", + "registry_search_placeholder": "Название или ключ сценария", + "registry_status_label": "Статус", + "registry_status_all": "Все", + "registry_loading": "Загрузка реестра…", + "registry_error": "Не удалось загрузить реестр", + "registry_retry": "Повторить", + "registry_empty": "Сценариев не найдено.", + "registry_list_label": "Список сценариев", + "registry_owner": "владелец", + "registry_envs": "окружения", + "registry_edit": "Редактировать", + "registry_analytics": "Аналитика", + "registry_last_run": "Последний запуск", + "registry_total": "Всего", + "registry_owner_label": "Владелец", + "registry_owner_placeholder": "имя пользователя", + "registry_tag_label": "Тег", + "registry_tag_placeholder": "тег", + "registry_dashboard_label": "Дашборд", + "registry_dashboard_placeholder": "id дашборда", + "registry_pagination_label": "Реестр — постраничная навигация", + "registry_page": "Страница", + "registry_prev": "Назад", + "registry_next": "Вперед", + "runs_title": "Запуски сценариев", + "runs_subtitle": "Global Run Operations Center · Scenario runs (не Verification run 037 и не Load test 040).", + "runs_back_scenarios": "← Сценарии", + "runs_automation": "Автоматизация", + "runs_waiting_me": "Ожидают моего решения", + "runs_waiting_me_aria": "Только ожидающие моего решения", + "runs_filters_aria": "Фильтры запусков", + "runs_status": "Статус", + "runs_scenario": "Сценарий", + "runs_environment": "Окружение", + "runs_trigger": "Триггер", + "runs_owner": "Владелец", + "runs_all": "Все", + "runs_loading": "Загрузка запусков…", + "runs_error": "Не удалось загрузить запуски", + "runs_retry": "Повторить", + "runs_empty": "Запусков не найдено.", + "runs_total": "Всего", + "runs_list_aria": "Список scenario runs", + "runs_kind_badge": "Scenario run", + "waiting_title": "Ожидают моего решения", + "waiting_empty": "Нет запусков, ожидающих решения аналитика.", + "waiting_meta_run": "Scenario run", + "waiting_step": "шаг", + "waiting_evidence_aria": "Свидетельства", + "waiting_comment_placeholder": "Комментарий", + "waiting_comment_aria": "Комментарий для", + "waiting_human_badge": "Ожидает человека", + "waiting_disposition_confirm": "Подтвердить проблему", + "waiting_disposition_false_positive": "False positive", + "waiting_disposition_inconclusive": "Недостаточно данных", + "ls_DRAFT": "Черновик", + "ls_READY": "Готова", + "ls_STALE": "Устарел", + "ls_NEEDS_REVALIDATION": "Нужна ревалидация", + "ls_BLOCKED": "Заблокирован", + "ls_DISABLED": "Отключён", + "ls_DEPRECATED": "Deprecated", + "ls_ARCHIVED": "Архив", + "health_pass": "пройден", + "health_attention": "внимание", + "health_warn": "предупреждение", + "health_fail": "провал", + "health_none": "нет", + "health_unknown": "неизвестно", + "retry": "Повторить", + "loading": "Загрузка…", + "delete_action": "Удалить", + "case_workspace_aria": "Рабочее пространство кейса", + "case_title": "Кейс расследования", + "case_loading": "Загрузка кейса…", + "case_disposition_aria": "Запись disposition", + "case_close_title": "Закрытие кейса", + "case_close_hint": "Закрытие не изменяет исторический результат запуска. Для resolved подтвердите сверку доказательств; для accepted укажите причину принятого риска.", + "case_closed": "Кейс закрыт", + "case_disposition_kind": "Вид disposition", + "case_disposition_resolved": "Resolved — сверка подтверждена", + "case_disposition_accepted": "Accepted — риск принят", + "case_evidence_label": "Ссылка на сверенное доказательство", + "case_evidence_placeholder": "run id или artifact reference", + "case_rationale_label": "Причина принятого риска", + "case_rationale_placeholder": "Почему риск принят", + "case_close_button": "Закрыть кейс", + "fingerprint": "Fingerprint", + "decision_version": "Decision version", + "queue_aria": "Очередь расследований", + "queue_title": "Очередь расследований", + "queue_count": "attention item(s)", + "queue_loading": "Загрузка очереди…", + "queue_empty": "Очередь пуста — нет нерасследованных сигналов", + "queue_investigate": "Investigate with agent", + "trend_aria": "Тренд успешности", + "trend_title": "Тренд успешности", + "trend_empty": "Нет истории запусков для построения тренда", + "trend_chart_aria": "График успешности сценария по запускам с накопительной линией", + "trend_chart_title": "Тренд успешности:", + "trend_runs": "запусков", + "trend_cumulative": "Накопительная успешность", + "trend_passed": "passed", + "trend_failed": "failed", + "trend_other": "прочее", + "agent_timeline_aria": "Таймлайн действий агента", + "agent_timeline_title": "Таймлайн действий", + "agent_timeline_empty": "Действий ещё нет", + "failures_aria": "Повторяющиеся отказы", + "failures_title": "Повторяющиеся отказы", + "failures_empty": "Повторяющихся отказов не обнаружено", + "failures_step": "Шаг", + "failures_occurrences": "occurrence(s)", + "failures_count": "group(s)", + "health_aria": "Здоровье сценария", + "health_title": "Здоровье сценария", + "health_success_rate": "Успешность", + "health_flakiness": "Flakiness", + "analytics_subtitle": "Открытие кейса явное — очередь сама не запускает агента.", + "analytics_runs_link": "Запуски сценариев →", + "case_page_case": "Case", + "case_page_note": "disposition не меняет историческую правду запуска.", + "case_page_back": "← Очередь расследований", + "scenario_analytics_prefix": "Scenario", + "scenario_analytics_title": "Аналитика сценария", + "scenario_analytics_subtitle": "здоровье, тренд и повторяющиеся отказы из истории запусков.", + "scenario_analytics_back": "← Регистр сценариев", + "scenario_analytics_loading": "Загрузка аналитики…", + "scenario_analytics_error": "Не удалось загрузить аналитику", + "scenario_analytics_empty": "Аналитика недоступна — нет истории запусков", + "editor_title": "Редактор сценария", + "editor_back": "← В регистр", + "editor_loading": "Загрузка редактора…", + "editor_error": "Не удалось загрузить сценарий", + "editor_graph_aria": "Граф проверки", + "editor_graph_title": "Граф проверки", + "editor_graph_hint": "Изменения проходят серверную валидацию до сохранения revision.", + "editor_steps_empty": "Шаги отсутствуют", + "editor_state_title": "Состояние", + "editor_state_hint": "Base revision закреплён для защиты от stale save.", + "editor_ready_title": "Изменения готовы к сохранению", + "editor_save": "Сохранить revision", + "editor_saved": "Создан revision", + "monitor_title": "Мониторинг scenario run", + "monitor_back": "← Запуски сценариев", + "monitor_run_prefix": "Run", + "monitor_scenario_run": "Scenario run (не Verification run 037 и не Load test 040)", + "monitor_recovering": "Восстановление запуска по run id…", + "monitor_error": "Не удалось загрузить запуск", + "monitor_cancel": "Отменить запуск", + "monitor_state_title": "Состояние", + "monitor_state_hint": "Elapsed — события обновляют таймлайн.", + "automation_aria": "Автоматизация сценариев", + "automation_title": "Автоматизация сценариев", + "automation_subtitle": "Schedule/trigger management для scenario runs (не cron-планировщик 009 и не verification run 037).", + "automation_reload": "Обновить", + "automation_loading": "Загрузка…", + "automation_schedules": "Расписаний", + "automation_trigger_rules": "Trigger-правил", + "automation_success_rate": "Успешность", + "automation_active_runs": "Активных прогонов", + "automation_new_schedule": "Новое расписание", + "automation_schedules_title": "Расписания", + "automation_no_schedules": "Нет расписаний", + "automation_remove_schedule": "Удалить расписание", + "automation_trigger_rules_title": "Trigger-правила", + "automation_no_rules": "Нет trigger-правил", + "automation_toggle_rule": "Переключить правило", + "automation_remove_rule": "Удалить правило", + "automation_policies": "Политики", + "automation_no_policies": "Нет политик", + "automation_remove_policy": "Удалить политику", + "automation_error_load": "Не удалось загрузить автоматизацию", + "schedule_error_save": "Не удалось сохранить расписание", + "checkpoint_aria": "Требуется решение аналитика", + "checkpoint_title": "Требуется решение аналитика", + "timeline_aria": "Ход выполнения scenario run", + "timeline_title": "Ход выполнения scenario run", + "timeline_note": "Не путать с Verification run (037) и Load test (040).", + "timeline_empty": "Шаги ещё не поступили.", + "timeline_of": "из", + "timeline_steps_started": "шагов стартовали", + "comparison_aria": "Сравнение scenario runs", + "comparison_title": "Сравнение scenario runs", + "comparison_warn": "Запуски используют разные revisions — сравнение может быть некорректным.", + "history_aria": "История scenario runs", + "history_title": "История scenario runs", + "history_note": "Verification run (037) и Load test (040) показываются в своих разделах.", + "history_empty": "Запусков сценария нет.", + "result_aria": "Результат scenario run", + "result_title": "Результат scenario run", + "result_note": "Не Verification run (037) и не Load test (040)", + "result_failed_aria": "Проваленные шаги", + "result_failed_summary": "Проваленные шаги", + "run_config_aria": "Конфигурация запуска сценария", + "run_config_title": "Конфигурация запуска сценария", + "run_config_subtitle": "Scenario run — отличается от Verification run (релизная проверка) и Load test (нагрузка).", + "run_config_env": "Окружение", + "run_config_select_env": "Выберите окружение", + "run_config_baseline_none": "Без baseline set", + "run_config_params": "Параметры", + "run_config_param_name": "Имя параметра", + "run_config_param_value": "Значение параметра", + "run_config_remove_param": "Удалить параметр", + "run_config_add_param": "Добавить параметр", + "run_config_steps": "Шаги сценария", + "run_config_required_step": "Обязательный шаг", + "run_config_required": "обязательный", + "run_config_diagnostics": "Дополнительная диагностика (опционально)", + "run_config_screenshots": "Скриншоты", + "run_config_verbose_logs": "Подробные логи", + "run_config_vlm": "VLM комментарий", + "run_config_gate_concurrency": "Потолок конкуренции", + "run_config_gate_volume": "Ожидаемый объём", + "run_config_gate_blast": "Зависимые blast-radius", + "run_config_gate_reason": "Причина", + "run_config_gate_confirm_aria": "Подтвердить PROD gate", + "run_config_gate_confirm_label": "Подтверждаю: PROD запуск согласован с 036 approval policy.", + "run_config_run_prod": "Запустить в PROD", + "run_config_run": "Запустить сценарий", + "run_config_fill_gate": "Заполните gate для запуска.", + "run_config_error_env": "Выберите окружение.", + "run_config_error_gate": "Для PROD заполните gate: конкуренция, объём, зависимые blast-radius и причину.", + "assert_aria": "Утверждение шага", + "assert_title": "Утверждение шага", + "assert_operator": "Оператор", + "assert_operator_exact": "Точное совпадение", + "assert_operator_absolute": "Абсолютная разница", + "assert_operator_relative": "Относительная разница", + "assert_operator_range": "Диапазон", + "assert_operator_row_set": "Набор строк", + "assert_threshold": "Порог", + "assert_error_baseline": "Выберите утверждённый baseline.", + "dag_aria": "Зависимости шагов", + "dag_title": "Зависимости шагов", + "dag_source_aria": "Источник шага", + "dag_target_aria": "Цель шага", + "dag_add": "Добавить", + "dag_error_self": "Зависимость должна связывать разные шаги.", + "dag_error_dup": "Такая зависимость уже существует.", + "agent_aria": "Редактирование с помощью агента", + "agent_title": "Редактирование с помощью агента", + "agent_description": "Опишите сложное изменение или добавьте типовые операции. Предложение создаётся на сервере и сохраняется с атрибуцией.", + "agent_saved_created": "создан", + "agent_new_proposal": "Новое предложение", + "agent_digest_prefix": "Digest", + "agent_status": "статус", + "agent_accept": "Принять и сохранить revision", + "agent_cancel": "Отменить", + "agent_request": "Запрос агенту", + "agent_request_placeholder": "Например: добавь сравнение XLSX по фазам 1–2", + "agent_operation": "Типовая операция", + "agent_logical_step": "Логический шаг", + "agent_add_operation": "Добавить операцию", + "agent_operations_aria": "Операции предложения", + "agent_remove_operation": "Удалить операцию", + "agent_propose": "Создать предложение", + "agent_processing": "Обработка…", + "agent_error": "Укажите шаг и утверждённый baseline reference.", + "diff_aria": "Разница правок", + "diff_title": "Разница правок", + "diff_empty": "Изменений нет." } diff --git a/frontend/src/lib/i18n/locales/ru/nav.json b/frontend/src/lib/i18n/locales/ru/nav.json index 12c14ed0d..1b537c8ef 100644 --- a/frontend/src/lib/i18n/locales/ru/nav.json +++ b/frontend/src/lib/i18n/locales/ru/nav.json @@ -52,8 +52,16 @@ "admin_settings_desc": "Настройка ADFS и маппингов", "admin_llm": "Провайдеры LLM", "admin_llm_desc": "Настройка провайдеров LLM", + "admin_mcp": "MCP", + "admin_mcp_desc": "Каталог инструментов MCP, видимость по ролям и клиенты", "profile": "Профиль", "sign_out": "Выйти", "dashboard": "Дашборды", - "settings_git": "Git-серверы" + "settings_git": "Git-серверы", + "dashboard_testing": "Тестирование дашбордов", + "dt_scenarios": "Сценарии", + "dt_runs": "Запуски", + "dt_analytics": "Аналитика", + "dt_automation": "Автоматизация", + "dt_waiting_badge": "Запуски, ожидающие моего решения" } diff --git a/frontend/src/lib/models/AdminMcpCatalogModel.svelte.ts b/frontend/src/lib/models/AdminMcpCatalogModel.svelte.ts new file mode 100644 index 000000000..4b9591073 --- /dev/null +++ b/frontend/src/lib/models/AdminMcpCatalogModel.svelte.ts @@ -0,0 +1,75 @@ +// #region AdminMcp.CatalogModel [C:4] [TYPE Model] [SEMANTICS admin,mcp,governance,catalog,rbac,model] +// @ingroup Admin +// @BRIEF Reactive screen model for the admin MCP governance view (UX audit Fix 5): the frozen tool +// catalog, the per-role visible-tool matrix, server endpoint/discovery, and DCR clients. +// @STATE data, loading, error, loaded +// @ACTION load +// @RELATION DEPENDS_ON -> [Api.ApiModule.GetMcpCatalog] +// @INVARIANT Read-only: load() only fetches the projection; the model never mutates catalog/roles/clients. +// @INVARIANT A failed load leaves the last successful projection intact and exposes a typed error. +import { api } from "$lib/api"; + +export interface McpToolGovernance { + name: string; + risk_level: string; + requires_approval: boolean; + service_allowed: boolean; + deprecated: boolean; + deprecation_note: string | null; + required_resource: string | null; + required_action: string | null; +} + +export interface McpRoleVisibility { + role_id: string; + name: string; + description: string | null; + is_admin: boolean; + visible_count: number; + visible_tools: string[]; +} + +export interface McpClientGovernance { + client_id: string; + client_name: string; + client_type: string; + is_revoked: boolean; + created_at: string | null; + scopes: string[]; + redirect_uris: string[]; +} + +export interface McpGovernancePayload { + catalog_version: string; + endpoint_path: string; + discovery_path: string; + tool_count: number; + tools: McpToolGovernance[]; + roles: McpRoleVisibility[]; + client_count: number; + clients: McpClientGovernance[]; +} + +// #region AdminMcp.CatalogModel.Screen [C:4] [TYPE Class] [SEMANTICS admin,mcp,governance,screen] +export class AdminMcpCatalogModel { + data: McpGovernancePayload | null = $state(null); + loading: boolean = $state(false); + error: string = $state(""); + loaded: boolean = $state(false); + + async load(apiFn = api.getMcpCatalog): Promise { + this.loading = true; + this.error = ""; + try { + this.data = await apiFn(); + this.loaded = true; + } catch (error: unknown) { + this.error = error instanceof Error ? error.message : "mcp_catalog_load_failed"; + } finally { + this.loading = false; + } + } +} +// #endregion AdminMcp.CatalogModel.Screen + +// #endregion AdminMcp.CatalogModel diff --git a/frontend/src/lib/models/InvestigationCaseModel.svelte.ts b/frontend/src/lib/models/InvestigationCaseModel.svelte.ts index a7f77a34f..610cfb1b3 100644 --- a/frontend/src/lib/models/InvestigationCaseModel.svelte.ts +++ b/frontend/src/lib/models/InvestigationCaseModel.svelte.ts @@ -15,11 +15,13 @@ export class InvestigationCaseModel { decisionVersion = $state(1); status = $state("open"); loading = $state(false); + saving = $state(false); error = $state(""); async load(caseId: string, apiFn = api.fetchApi): Promise { this.caseId = caseId; this.loading = true; + this.error = ""; try { const detail = await apiFn(`/scenario-analytics/cases/${encodeURIComponent(caseId)}`); this.case = detail.case; @@ -33,18 +35,35 @@ export class InvestigationCaseModel { } } - async dispose(disposition: DispositionKind, apiFn = api.fetchApi): Promise { + async dispose( + disposition: DispositionKind, + rationale = "", + verificationEvidence: Record | undefined = undefined, + apiFn = api.fetchApi, + ): Promise { + if (this.saving || this.loading || this.error) return; + this.saving = true; const caseId = this.caseId || this.case?.id || ""; try { const result = await apiFn( `/scenario-analytics/cases/${encodeURIComponent(caseId)}/disposition`, - { method: "POST", body: JSON.stringify({ disposition, expected_version: this.decisionVersion }) } as never, + { + method: "POST", + body: JSON.stringify({ + disposition, + expected_version: this.decisionVersion, + ...(rationale.trim() ? { rationale: rationale.trim() } : {}), + ...(verificationEvidence ? { verification_evidence: verificationEvidence } : {}), + }), + } as never, ); this.decisionVersion = result.decision_version; this.status = result.status; this.case = result; } catch (error: unknown) { this.error = error instanceof Error ? error.message : "case_disposition_failed"; + } finally { + this.saving = false; } } } diff --git a/frontend/src/lib/models/RunMonitorModel.svelte.ts b/frontend/src/lib/models/RunMonitorModel.svelte.ts index 65657c515..6a0ac3eca 100644 --- a/frontend/src/lib/models/RunMonitorModel.svelte.ts +++ b/frontend/src/lib/models/RunMonitorModel.svelte.ts @@ -14,6 +14,8 @@ export class RunMonitorModel { comparison: RunComparison | null = $state(null); state: "idle" | "loading" | "live" | "waiting_human" | "terminal" | "error" = $state("idle"); error = $state(""); + busy = $state(false); + resultLoading = $state(false); private eventSource: EventSource | null = null; async launch(config: RunConfiguration, idempotencyKey: string, apiFn = api.fetchApi): Promise { @@ -48,8 +50,9 @@ export class RunMonitorModel { this.eventSource = null; return; } - this.eventSource.onmessage = (event) => { - const payload = JSON.parse(event.data) as { status?: ScenarioRun["status"]; step?: ScenarioStepRun }; + const receive = (event: MessageEvent) => { + let payload: { status?: ScenarioRun["status"]; step?: ScenarioStepRun }; + try { payload = JSON.parse(event.data); } catch { return; } if (!this.run) return; if (payload.status) this.run.status = payload.status; if (payload.step) { @@ -61,19 +64,42 @@ export class RunMonitorModel { } this.state = this.run.status === "waiting_human" ? "waiting_human" : ["passed", "failed", "cancelled", "blocked", "inconclusive"].includes(this.run.status) ? "terminal" : "live"; }; + this.eventSource.onmessage = receive; + // The backend emits named SSE frames, which do not dispatch onmessage. + for (const name of ["approval_required", "run_queued", "run_started", "step_started", "checkpoint_created", "step_completed", "run_completed", "run_failed", "run_cancelled", "run_blocked", "run_inconclusive"]) { + this.eventSource.addEventListener?.(name, (event) => receive(event as MessageEvent)); + } } async dispose(runId: string, decision: CheckpointDisposition, comment: string, apiFn = api.fetchApi): Promise { - await apiFn(`/scenario-runs/${encodeURIComponent(runId)}/human/decision`, { + if (this.busy) return; + this.busy = true; + this.error = ""; + try { + await apiFn(`/scenario-runs/${encodeURIComponent(runId)}/human/decision`, { method: "POST", body: JSON.stringify({ disposition: decision, expected_version: 1, comment }), } as never); - if (this.run && this.run.status === "waiting_human") { - this.run.status = "running"; - this.state = "live"; + await this.loadRun(runId, apiFn); + } catch (error: unknown) { + this.error = error instanceof Error ? error.message : "run_decision_failed"; + } finally { + this.busy = false; } } + async cancel(runId: string, apiFn = api.fetchApi): Promise { + if (this.busy) return; + this.busy = true; + this.error = ""; + try { + await apiFn(`/scenario-runs/${encodeURIComponent(runId)}/cancel`, { method: "POST" }); + await this.loadRun(runId, apiFn); + } catch (error: unknown) { + this.error = error instanceof Error ? error.message : "run_cancel_failed"; + } finally { this.busy = false; } + } + /** Recover a running/terminal run by id after a disconnect (RUNMON-FR-003). */ async loadRun(runId: string, apiFn = api.fetchApi): Promise { this.state = "loading"; @@ -88,7 +114,14 @@ export class RunMonitorModel { } async loadResult(runId: string, apiFn = api.fetchApi): Promise { - this.result = await apiFn(`/scenario-runs/${encodeURIComponent(runId)}/result`); + if (this.resultLoading) return; + this.resultLoading = true; + this.error = ""; + try { + this.result = await apiFn(`/scenario-runs/${encodeURIComponent(runId)}/result`); + } catch (error: unknown) { + this.error = error instanceof Error ? error.message : "run_result_failed"; + } finally { this.resultLoading = false; } } clear(): void { this.eventSource?.close(); diff --git a/frontend/src/lib/models/__tests__/AdminMcpCatalogModel.test.ts b/frontend/src/lib/models/__tests__/AdminMcpCatalogModel.test.ts new file mode 100644 index 000000000..eefab8795 --- /dev/null +++ b/frontend/src/lib/models/__tests__/AdminMcpCatalogModel.test.ts @@ -0,0 +1,50 @@ +// #region Test.AdminMcp.CatalogModel [C:3] [TYPE Module] [SEMANTICS test,admin,mcp,governance,model] +// @BRIEF AdminMcpCatalogModel invariants: load populates the projection; a failure keeps the last +// projection and exposes a typed error; non-Error rejections map to a fallback code. +// @RELATION VERIFIES -> [AdminMcp.CatalogModel] +import { describe, it, expect, vi } from 'vitest'; +import { AdminMcpCatalogModel } from '../AdminMcpCatalogModel.svelte'; + +const payload = { + catalog_version: '1.0.0', + endpoint_path: '/mcp', + discovery_path: '/.well-known/oauth-protected-resource/mcp', + tool_count: 0, + tools: [], + roles: [], + client_count: 0, + clients: [], +}; + +describe('AdminMcpCatalogModel', () => { + it('starts unloaded and populates on success', async () => { + const model = new AdminMcpCatalogModel(); + expect(model.loaded).toBe(false); + expect(model.data).toBeNull(); + + const apiFn = vi.fn().mockResolvedValue({ ...payload, catalog_version: '2.1.0' }); + await model.load(apiFn); + + expect(apiFn).toHaveBeenCalled(); + expect(model.loaded).toBe(true); + expect(model.loading).toBe(false); + expect(model.error).toBe(''); + expect(model.data?.catalog_version).toBe('2.1.0'); + }); + + it('keeps the last projection and records a typed error on failure', async () => { + const model = new AdminMcpCatalogModel(); + await model.load(vi.fn().mockResolvedValue(payload)); + await model.load(vi.fn().mockRejectedValue(new Error('boom'))); + + expect(model.error).toBe('boom'); + expect(model.data?.catalog_version).toBe('1.0.0'); // last success intact + }); + + it('maps a non-Error rejection to the fallback code', async () => { + const model = new AdminMcpCatalogModel(); + await model.load(vi.fn().mockRejectedValue('string-failure')); + expect(model.error).toBe('mcp_catalog_load_failed'); + }); +}); +// #endregion Test.AdminMcp.CatalogModel diff --git a/frontend/src/lib/routes.ts b/frontend/src/lib/routes.ts index 928805a82..a994a026b 100644 --- a/frontend/src/lib/routes.ts +++ b/frontend/src/lib/routes.ts @@ -7,7 +7,9 @@ // Before this registry, routes were hardcoded as strings in 40+ locations across the codebase, // causing 404 errors when routes were renamed or not yet created. TypeScript catches typos in // function names and parameter types at compile time. The link-integrity test scans all href/goto -// usages and validates them against this registry's output patterns. +// usages and validates them against this registry's output patterns. The integrity test also +// scans the dashboard-testing/load-testing trees for raw href/goto/resolve() literals so those +// routes cannot bypass this registry (previously they used local $app/paths resolve() strings). // @REJECTED String constants without functions rejected — dynamic segments (ids, envIds) need // parameterized builders. Class-based registry rejected — plain object with arrow functions is // tree-shakeable and works in both Svelte templates and TypeScript. @@ -102,6 +104,33 @@ export const ROUTES = { history: () => '/validation-tasks/history', }, + // ── Dashboard Testing (042 registry / 044 runs / 045 center / 046 automation / 047 analytics) ── + dashboardTesting: { + /** 042 scenario registry hub (list/detail entry point). */ + scenarios: () => '/dashboard-testing/scenarios', + scenarioEdit: (id: string) => + `/dashboard-testing/scenarios/${encodeURIComponent(id)}/edit`, + scenarioAnalytics: (id: string) => + `/dashboard-testing/scenarios/${encodeURIComponent(id)}/analytics`, + runDetail: (scenarioId: string, runId: string) => + `/dashboard-testing/scenarios/${encodeURIComponent(scenarioId)}/runs/${encodeURIComponent(runId)}`, + /** 045 Global Run Operations Center — the human approval/monitoring hub. Pass + * waitingForMe to deep-link straight into the "awaiting my decision" view. */ + runs: (waitingForMe?: boolean) => + waitingForMe ? '/dashboard-testing/runs?waiting_for_me=true' : '/dashboard-testing/runs', + /** 047 investigation queue. */ + analytics: () => '/dashboard-testing/analytics', + analyticsCase: (caseId: string) => + `/dashboard-testing/analytics/cases/${encodeURIComponent(caseId)}`, + /** 046 schedule/trigger management. */ + automation: () => '/dashboard-testing/automation', + }, + + // ── Load Testing (040) ─────────────────────────────────── + loadTesting: { + detail: (id: string | number) => `/load-testing/${encodeURIComponent(String(id))}`, + }, + // ── Reports ────────────────────────────────────────────── reports: { list: () => '/reports', @@ -125,6 +154,7 @@ export const ROUTES = { roles: () => '/admin/roles', settings: () => '/admin/settings', llmSettings: () => '/admin/settings/llm', + mcp: () => '/admin/mcp', }, // ── Storage ────────────────────────────────────────────── diff --git a/frontend/src/lib/stores/__tests__/test_scenarioRuns.ts b/frontend/src/lib/stores/__tests__/test_scenarioRuns.ts new file mode 100644 index 000000000..68e241aa8 --- /dev/null +++ b/frontend/src/lib/stores/__tests__/test_scenarioRuns.ts @@ -0,0 +1,146 @@ +// #region Test.ScenarioRuns [C:3] [TYPE Module] [SEMANTICS test,scenario,run,store,waiting,badge] +// @BRIEF Unit tests for the waiting-for-me scenario-run count store — initial state, refresh, +// dedup, fail-closed auth disabling, error retry, and subscriber contracts. +// @RELATION DEPENDS_ON -> [Stores.ScenarioRuns.WaitingStore] +// @TEST_EDGE: external_fail -> fetchApi rejects (network); store keeps last count and stays enabled +// @TEST_EDGE: invalid_type -> fetchApi resolves without a numeric total; count falls back to 0 +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +vi.mock('$lib/api', () => ({ + api: { + fetchApi: vi.fn(), + }, +})); + +const WAITING_URL = '/scenario-runs?waiting_for_me=true&page_size=1'; + +describe('scenarioRuns waiting-count store', () => { + beforeEach(() => { + vi.resetModules(); + }); + + it('has correct initial state', async () => { + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + expect(scenarioWaitingCount.current).toBe(0); + expect(scenarioWaitingCount.loading).toBe(false); + expect(scenarioWaitingCount.disabled).toBe(false); + }); + + it('refresh() fetches the waiting total and updates the count', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockResolvedValue({ total: 4, items: [{}] }); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + const result = await scenarioWaitingCount.refresh(); + + expect(api.fetchApi).toHaveBeenCalledWith(WAITING_URL); + expect(result).toBe(4); + expect(scenarioWaitingCount.current).toBe(4); + }); + + it('refresh() falls back to 0 when total is missing or non-numeric', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockResolvedValue({}); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + await scenarioWaitingCount.refresh(); + expect(scenarioWaitingCount.current).toBe(0); + }); + + it('refresh() dedups concurrent calls into one request', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + let resolvePromise!: (v: { total: number }) => void; + vi.mocked(api.fetchApi).mockReturnValue(new Promise((r) => { resolvePromise = r; }) as never); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + const p1 = scenarioWaitingCount.refresh(); + const p2 = scenarioWaitingCount.refresh(); + + expect(api.fetchApi).toHaveBeenCalledTimes(1); + resolvePromise({ total: 2 }); + expect(await p1).toBe(2); + expect(await p2).toBe(2); + }); + + it('401 disables further polling', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockRejectedValue({ status: 401, message: 'Unauthorized' }); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + await scenarioWaitingCount.refresh(); + expect(scenarioWaitingCount.disabled).toBe(true); + + await scenarioWaitingCount.refresh(); + expect(api.fetchApi).toHaveBeenCalledTimes(1); + }); + + it('403 disables further polling', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockRejectedValue({ status: 403, message: 'Forbidden' }); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + await scenarioWaitingCount.refresh(); + expect(scenarioWaitingCount.disabled).toBe(true); + }); + + it('generic error keeps the store enabled (retriable)', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockRejectedValue(new Error('Network error')); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + await scenarioWaitingCount.refresh(); + expect(scenarioWaitingCount.disabled).toBe(false); + + await scenarioWaitingCount.refresh(); + expect(api.fetchApi).toHaveBeenCalledTimes(2); + }); + + it('error without .message string is handled', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockRejectedValue('boom'); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + const result = await scenarioWaitingCount.refresh(); + expect(result).toBe(0); + expect(scenarioWaitingCount.disabled).toBe(false); + }); + + it('subscribe fires immediately and after refresh; unsubscribe stops it', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockResolvedValue({ total: 5 }); + + const { scenarioWaitingCount } = await import('../scenarioRuns.svelte.js'); + const spy = vi.fn(); + const unsubscribe = scenarioWaitingCount.subscribe(spy); + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledWith(0); + + await scenarioWaitingCount.refresh(); + expect(spy).toHaveBeenCalledWith(5); + + spy.mockClear(); + unsubscribe(); + vi.mocked(api.fetchApi).mockResolvedValue({ total: 6 }); + await scenarioWaitingCount.refresh(); + expect(spy).not.toHaveBeenCalled(); + }); + + it('refreshScenarioWaiting is the named poll alias', async () => { + const { api } = await import('$lib/api'); + vi.mocked(api.fetchApi).mockClear(); + vi.mocked(api.fetchApi).mockResolvedValue({ total: 1 }); + + const { refreshScenarioWaiting } = await import('../scenarioRuns.svelte.js'); + await refreshScenarioWaiting(); + expect(api.fetchApi).toHaveBeenCalledWith(WAITING_URL); + }); +}); +// #endregion Test.ScenarioRuns diff --git a/frontend/src/lib/stores/scenarioRuns.svelte.ts b/frontend/src/lib/stores/scenarioRuns.svelte.ts new file mode 100644 index 000000000..b07840a93 --- /dev/null +++ b/frontend/src/lib/stores/scenarioRuns.svelte.ts @@ -0,0 +1,85 @@ +// #region Stores.ScenarioRuns.WaitingStore [C:3] [TYPE Store] [SEMANTICS scenario,run,store,waiting,badge,sidebar] +// @ingroup Stores +// @BRIEF Waiting-for-me scenario-run count for the sidebar approval badge (045 RUNMON-FR-009): +// makes the human checkpoint loop discoverable instead of a page the analyst must guess. +// @LAYER UI +// @RELATION DEPENDS_ON -> [Api.ApiModule.FetchApi] +// @UX_STATE Idle -> waiting count 0, badge hidden. +// @UX_STATE Ready -> waiting count N>0, sidebar "Тестирование дашбордов" badge shows N. +// @UX_STATE Disabled -> run center not accessible (401/403) -> polling stops, count stays 0. +// @INVARIANT refresh() reads only the authoritative server total (waiting_for_me=true); it never +// derives the count client-side, mirroring GlobalRunCenterModel's server-narrowing rule. +// @INVARIANT A non-2xx authority answer never fabricates a count — it leaves the last value and, +// for 401/403, disables further polling (bounded, fail-closed). +// @RATIONALE Mirrors Stores.Health.HealthStore: module-level $state atoms + getters + subscriber set +// keeps Svelte 5 reactivity for the Sidebar $derived badge while allowing an interval poll. +// The count request uses page_size=1 because only `total` is consumed (bounded payload). +// @REJECTED Polling the full run list to count client-side rejected — the run center already returns +// an exact server total for waiting_for_me, so a heavy list fetch would be wasteful. +import { api } from '../api'; +import { SvelteSet } from 'svelte/reactivity'; +import { log } from '$lib/cot-logger'; + +interface RunCenterTotal { + total: number; +} + +let _waitingCount = $state(0); +let _loading = $state(false); +let _isDisabled = false; + +const _subs = new SvelteSet<(_v: number) => void>(); +let _inflight: Promise | null = null; + +function _notify(): void { + _subs.forEach((fn) => fn(_waitingCount)); +} + +// #region Stores.ScenarioRuns.WaitingStore.Refresh [C:3] [TYPE Function] +// @BRIEF Fetch the waiting-for-me run total; dedup concurrent calls; fail closed on auth denial. +// @PRE Caller may invoke from an interval; repeated in-flight calls share one request. +// @POST Resolves the current waiting count; on 401/403 disables further polling. +async function refresh(): Promise { + if (_isDisabled) return _waitingCount; + if (_inflight) return _inflight; + + _loading = true; + _inflight = (async () => { + try { + const resp = await api.fetchApi('/scenario-runs?waiting_for_me=true&page_size=1'); + _waitingCount = typeof resp?.total === 'number' && resp.total >= 0 ? resp.total : 0; + _notify(); + return _waitingCount; + } catch (error: unknown) { + const apiError = error as { status?: number; message?: string }; + if (apiError?.status === 401 || apiError?.status === 403) { + log('ScenarioRunsStore', 'EXPLORE', 'Run center not accessible — stop waiting-count polling', {}, String(apiError.status)); + _isDisabled = true; + } else { + log('ScenarioRunsStore', 'EXPLORE', 'Waiting-count refresh failed', {}, error instanceof Error ? error.message : String(error)); + } + return _waitingCount; + } finally { + _loading = false; + _inflight = null; + } + })(); + return _inflight; +} +// #endregion Stores.ScenarioRuns.WaitingStore.Refresh + +export const scenarioWaitingCount = { + get current() { return _waitingCount; }, + get loading() { return _loading; }, + get disabled() { return _isDisabled; }, + subscribe(fn: (_v: number) => void) { + fn(_waitingCount); + _subs.add(fn); + return () => { _subs.delete(fn); }; + }, + refresh, +}; + +/** Named alias for Sidebar interval polling. */ +export const refreshScenarioWaiting = refresh; +// #endregion Stores.ScenarioRuns.WaitingStore diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index 2cc8bf343..a4b9ec2cb 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -65,7 +65,7 @@ }; }); - let isLoginPage = $derived(page.url.pathname === '/login'); + let isLoginPage = $derived(page.url.pathname === '/login' || page.url.pathname === '/oauth-consent'); let isAgentPage = $derived(page.url.pathname === '/agent'); let isExpanded = $derived(sidebarStore.value?.isExpanded ?? true); let isProductionContext = $derived($isProductionContextStore); diff --git a/frontend/src/routes/admin/+page.svelte b/frontend/src/routes/admin/+page.svelte index 9ff01f787..f5b1c859d 100644 --- a/frontend/src/routes/admin/+page.svelte +++ b/frontend/src/routes/admin/+page.svelte @@ -50,6 +50,12 @@ description: $t.nav.admin_llm_desc, icon: 'sparkles', }, + { + label: $t.nav.admin_mcp, + path: '/admin/mcp', + description: $t.nav.admin_mcp_desc, + icon: 'cpu', + }, ]; diff --git a/frontend/src/routes/admin/__tests__/admin-mcp.test.ts b/frontend/src/routes/admin/__tests__/admin-mcp.test.ts new file mode 100644 index 000000000..a3cca54b4 --- /dev/null +++ b/frontend/src/routes/admin/__tests__/admin-mcp.test.ts @@ -0,0 +1,135 @@ +// #region Tests.AdminMcp.AdminMcpPageTest [C:3] [TYPE Module] [SEMANTICS test,admin,mcp,governance,page,rbac] +// @BRIEF Admin MCP governance page (UX audit Fix 5): renders the server info, tool catalog, per-role +// visibility matrix and DCR clients from the server-owned projection; expands a role; error+retry. +// @RELATION VERIFIES -> [Admin.Route.Mcp] +// @TEST_EDGE: load failure -> typed error state with retry +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; +import McpPage from '../mcp/+page.svelte'; + +const mockTranslations = { + nav: { admin_mcp: 'MCP' }, + admin: { + mcp: { + title: 'MCP Governance', + subtitle: 'Read-only governance', + server: 'Server', + catalog_version: 'Catalog version', + endpoint: 'Endpoint', + discovery: 'Discovery', + tools: 'Tools', + tools_total: 'Total tools', + roles: 'Visibility by role', + roles_total: 'Roles', + col_tool: 'Tool', + col_risk: 'Risk', + col_permission: 'Required permission', + col_service: 'Service', + col_service_hint: 'Whether service (machine) clients may call', + col_approval: 'Approval', + deprecated: 'Deprecated', + show_tools: 'Show tools', + hide_tools: 'Hide tools', + admin_badge: 'ADMIN', + perm_auth_only: 'Authenticated only', + yes: 'yes', + no: 'no', + clients: 'Clients (DCR)', + clients_total: 'Clients', + active: 'Active', + revoked: 'Revoked', + empty_roles: 'No roles configured.', + empty_clients: 'No registered clients.', + loading: 'Loading MCP…', + error: 'Failed to load', + retry: 'Retry', + risk_safe: 'safe', + risk_guarded: 'guarded', + client_confidential: 'confidential', + client_public: 'public', + }, + }, +}; + +vi.mock('$lib/i18n/index.svelte.js', () => ({ + t: { subscribe: (fn: (v: unknown) => void) => { fn(mockTranslations); return () => {}; } }, + getT: () => mockTranslations, + _: (key: string) => key, +})); +vi.mock('$lib/cot-logger', () => ({ log: vi.fn(), setTraceId: vi.fn(), getTraceId: () => 'test-trace' })); +vi.mock('$app/navigation', () => ({ goto: vi.fn(), push: vi.fn(), replace: vi.fn(), prefetch: vi.fn(), prefetchRoutes: vi.fn() })); +vi.mock('$app/environment', () => ({ browser: true, dev: true, building: false })); +vi.mock('$lib/auth/store.svelte.js', () => { + const authState = { user: { username: 'admin', roles: ['admin'] }, token: 'admin-token', isAuthenticated: true, loading: false }; + return { auth: { subscribe: (fn: (v: typeof authState) => void) => { fn(authState); return () => {}; }, setToken: vi.fn(), setUser: vi.fn(), logout: vi.fn(), setLoading: vi.fn() } }; +}); +vi.mock('$lib/auth/permissions.js', () => ({ hasPermission: () => true })); + +const mockGetCatalog = vi.hoisted(() => vi.fn()); +vi.mock('$lib/api', () => ({ api: { getMcpCatalog: mockGetCatalog }, fetchApi: vi.fn() })); + +const payload = { + catalog_version: '1.0.0', + endpoint_path: '/mcp', + discovery_path: '/.well-known/oauth-protected-resource/mcp', + tool_count: 2, + tools: [ + { name: 'list_environments', risk_level: 'safe', requires_approval: false, service_allowed: true, deprecated: false, deprecation_note: null, required_resource: null, required_action: null }, + { name: 'superset_execute_sql', risk_level: 'guarded', requires_approval: false, service_allowed: false, deprecated: true, deprecation_note: 'use X', required_resource: 'plugin:superset_sql', required_action: 'EXECUTE' }, + ], + roles: [ + { role_id: 'r-admin', name: 'Admin', description: null, is_admin: true, visible_count: 2, visible_tools: ['list_environments', 'superset_execute_sql'] }, + { role_id: 'r-viewer', name: 'Viewer', description: null, is_admin: false, visible_count: 1, visible_tools: ['list_environments'] }, + ], + client_count: 1, + clients: [ + { client_id: 'c1', client_name: 'Claude Desktop', client_type: 'confidential', is_revoked: false, created_at: '2026-09-01T00:00:00', scopes: ['mcp'], redirect_uris: ['https://x/cb'] }, + ], +}; + +describe('Admin MCP governance page', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockGetCatalog.mockResolvedValue(payload); + }); + + it('renders server info, tools, roles and clients after load', async () => { + render(McpPage); + + await waitFor(() => expect(screen.getByText('MCP Governance')).toBeTruthy()); + expect(mockGetCatalog).toHaveBeenCalled(); + // server endpoint is absolute (origin from mocked $app/state) + expect(screen.getByTestId('mcp-endpoint').textContent).toContain('http://localhost/mcp'); + // tool catalog rows + expect(screen.getByText('list_environments')).toBeTruthy(); + expect(screen.getByText('superset_execute_sql')).toBeTruthy(); + // permission-None tool shows the auth-only label; permissioned tool shows resource:action + expect(screen.getByText('Authenticated only')).toBeTruthy(); + expect(screen.getByText('plugin:superset_sql:EXECUTE')).toBeTruthy(); + // role matrix + expect(screen.getByText('Admin')).toBeTruthy(); + expect(screen.getByText('Viewer')).toBeTruthy(); + // clients + expect(screen.getByText('Claude Desktop')).toBeTruthy(); + }); + + it('expands a role to reveal its visible tools (label flips)', async () => { + render(McpPage); + await waitFor(() => expect(screen.getByText('Viewer')).toBeTruthy()); + + const toggles = screen.getAllByText('Show tools'); + expect(toggles.length).toBe(2); + fireEvent.click(toggles[0]); + await waitFor(() => expect(screen.getByText('Hide tools')).toBeTruthy()); + }); + + it('shows a typed error state with retry when the load fails', async () => { + mockGetCatalog.mockRejectedValueOnce(new Error('catalog boom')); + render(McpPage); + + await waitFor(() => expect(screen.getByText('Failed to load')).toBeTruthy()); + expect(screen.getByText('catalog boom')).toBeTruthy(); + expect(screen.getByText('Retry')).toBeTruthy(); + }); +}); +// #endregion Tests.AdminMcp.AdminMcpPageTest diff --git a/frontend/src/routes/admin/mcp/+page.svelte b/frontend/src/routes/admin/mcp/+page.svelte new file mode 100644 index 000000000..c25388f61 --- /dev/null +++ b/frontend/src/routes/admin/mcp/+page.svelte @@ -0,0 +1,208 @@ + + + + + + + + + + + + + +{mcp.title} + + +
+ + {#snippet subtitle()} +

{mcp.subtitle}

+ {/snippet} +
+ + {#if model.loading} +
+ {mcp.loading} +
+ {:else if model.error} + + {:else if data} + +

{mcp.server}

+
+
+
{mcp.catalog_version}
+
{data.catalog_version}
+
+
+
{mcp.endpoint}
+
{endpointUrl}
+
+
+
{mcp.discovery}
+
{discoveryUrl}
+
+
+
+ + +
+

{mcp.roles}

+ {mcp.roles_total}: {data.roles.length} +
+ {#if data.roles.length === 0} +

{mcp.empty_roles}

+ {:else} +
    + {#each data.roles as role (role.role_id)} +
  • +
    +
    + {role.name} + {#if role.is_admin} + {mcp.admin_badge} + {/if} +
    +
    + {role.visible_count} / {data.tool_count} + +
    +
    + {#if expandedRoles.has(role.role_id)} +
    + {#each role.visible_tools as tool (tool)} + {tool} + {/each} +
    + {/if} +
  • + {/each} +
+ {/if} +
+ + +
+

{mcp.tools}

+ {mcp.tools_total}: {data.tool_count} +
+
+ + + + + + + + + + + + {#each data.tools as tool (tool.name)} + + + + + + + + {/each} + +
{mcp.col_tool}{mcp.col_risk}{mcp.col_permission}{mcp.col_service}{mcp.col_approval}
+ {tool.name} + {#if tool.deprecated} + {mcp.deprecated} + {/if} + {riskLabel(tool.risk_level)} + {tool.required_resource ? `${tool.required_resource}:${tool.required_action}` : mcp.perm_auth_only} + {tool.service_allowed ? mcp.yes : mcp.no}{tool.requires_approval ? mcp.yes : mcp.no}
+
+
+ + +
+

{mcp.clients}

+ {mcp.clients_total}: {data.client_count} +
+ {#if data.clients.length === 0} +

{mcp.empty_clients}

+ {:else} +
    + {#each data.clients as client (client.client_id)} +
  • +
    + {client.client_name} + {client.client_id} · {clientTypeLabel(client.client_type)} +
    +
    + {#if client.scopes.length} + {client.scopes.join(", ")} + {/if} + + {client.is_revoked ? mcp.revoked : mcp.active} + +
    +
  • + {/each} +
+ {/if} +
+ {/if} +
+
+ \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/analytics/+page.svelte b/frontend/src/routes/dashboard-testing/analytics/+page.svelte index 9cf81d936..83002985d 100644 --- a/frontend/src/routes/dashboard-testing/analytics/+page.svelte +++ b/frontend/src/routes/dashboard-testing/analytics/+page.svelte @@ -9,38 +9,44 @@ -Очередь расследований +{dt.queue_title}
- + {#snippet subtitle()} -

Открытие кейса явное — очередь сама не запускает агента.

+

{dt.analytics_subtitle}

{/snippet} {#snippet actions()} - Запуски сценариев → + {dt.analytics_runs_link} {/snippet}
@@ -52,4 +58,4 @@ onRetry={() => { model.error = ""; void model.load(); }} />
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/+page.svelte b/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/+page.svelte index 3b29cc948..e9cd68c49 100644 --- a/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/+page.svelte +++ b/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/+page.svelte @@ -8,31 +8,33 @@ -Кейс расследования +{dt.case_title}
- + {#snippet subtitle()} -

Case {caseId} · disposition не меняет историческую правду запуска.

+

{dt.case_page_case} {caseId} · {dt.case_page_note}

{/snippet} {#snippet actions()} - ← Очередь расследований + {dt.case_page_back} {/snippet}
void model.load(caseId)} />
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/__tests__/case.ux.test.ts b/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/__tests__/case.ux.test.ts index 777600c3e..7908c7e3e 100644 --- a/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/__tests__/case.ux.test.ts +++ b/frontend/src/routes/dashboard-testing/analytics/cases/[caseId]/__tests__/case.ux.test.ts @@ -33,13 +33,13 @@ describe("Analytics case route", () => { .mockResolvedValueOnce({ id: "case-1", fingerprint: "fp-1", scenario_id: "s1", status: "resolved", disposition: "confirmed", decision_version: 2, created_at: null }); render(CasePage); - await screen.findByRole("button", { name: "Записать disposition" }); - await fireEvent.click(screen.getByRole("button", { name: "Записать disposition" })); + await screen.findByRole("button", { name: "Закрыть кейс" }); + await fireEvent.click(screen.getByRole("button", { name: "Закрыть кейс" })); await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); const [endpoint, options] = fetchMock.mock.calls[1] as [string, { body?: string }]; expect(endpoint).toBe("/scenario-analytics/cases/case-1/disposition"); - expect(JSON.parse(options.body ?? "{}")).toEqual({ disposition: "confirmed", expected_version: 1 }); + expect(JSON.parse(options.body ?? "{}")).toEqual({ disposition: "resolved", expected_version: 1, verification_evidence: { reconciled: true } }); await waitFor(() => expect(screen.getByText("resolved")).toBeTruthy()); }); diff --git a/frontend/src/routes/dashboard-testing/automation/+page.svelte b/frontend/src/routes/dashboard-testing/automation/+page.svelte index a70117973..e9cd4184e 100644 --- a/frontend/src/routes/dashboard-testing/automation/+page.svelte +++ b/frontend/src/routes/dashboard-testing/automation/+page.svelte @@ -5,21 +5,24 @@ -Автоматизация сценариев +{dt.automation_title}
- ← Сценарии -

Автоматизация сценариев

+ {dt.runs_back_scenarios} +

{dt.automation_title}

- Schedule/trigger management для scenario runs (не cron-планировщик 009 и не verification run 037). + {dt.automation_subtitle}

- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/runs/+page.svelte b/frontend/src/routes/dashboard-testing/runs/+page.svelte index e17bbf4ed..256d12def 100644 --- a/frontend/src/routes/dashboard-testing/runs/+page.svelte +++ b/frontend/src/routes/dashboard-testing/runs/+page.svelte @@ -5,80 +5,88 @@ -Запуски сценариев +{dt.runs_title}
- ← Сценарии -

Запуски сценариев

-

- Global Run Operations Center · Scenario runs (не Verification run 037 и не Load test 040). -

+ {dt.runs_back_scenarios} +

{dt.runs_title}

+

{dt.runs_subtitle}

- Автоматизация + {dt.runs_automation}
-
+
{#if model.loading} -
Загрузка запусков…
+
{dt.runs_loading}
{:else if model.error} {:else} {#if model.waitingForMe} @@ -86,26 +94,26 @@ void model.dispose(runId, decision, comment)} /> {:else} -
+
-
Всего: {model.total}
+
{dt.runs_total}: {model.total}
{/if} {/if}
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/runs/__tests__/center.ux.test.ts b/frontend/src/routes/dashboard-testing/runs/__tests__/center.ux.test.ts new file mode 100644 index 000000000..d4c1b9dd3 --- /dev/null +++ b/frontend/src/routes/dashboard-testing/runs/__tests__/center.ux.test.ts @@ -0,0 +1,46 @@ +// #region Test.ScenarioRun.CenterUX [C:3] [TYPE Module] [SEMANTICS test,scenario,run,center,route,regression] +// @BRIEF Route-level regression for the Run Center fetch loop: an empty server list must +// trigger exactly ONE /scenario-runs fetch. The former `$effect(() => { if (!rows.length +// && !loading) load() })` re-fired on every completion (~60 RPS runaway on a fresh DB) +// because load() mutates the very state the effect depends on. +// @RELATION BINDS_TO -> [ScenarioRun.Route.Center] +// @TEST_EDGE: empty_list_single_fetch -> no refetch loop +// @TEST_INVARIANT one-shot initial load -> VERIFIED_BY: [loads exactly once on empty list] +import { render, screen } from "@testing-library/svelte"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { page } from "$app/state"; +import { api } from "$lib/api"; +import CenterPage from "../+page.svelte"; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("RunCenter route (center.ux)", () => { + it("loads the run list exactly once when the server returns an empty list", async () => { + page.url = new URL("http://localhost/dashboard-testing/runs"); + const fetchMock = vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [], total: 0 }); + + render(CenterPage); + + expect(await screen.findByText("Запусков не найдено.")).toBeTruthy(); + // Give any (hypothetical) re-triggered effects time to fire again. + await new Promise((resolve) => setTimeout(resolve, 80)); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledWith("/scenario-runs"); + }); + + it("deep link ?waiting_for_me=true issues the narrowed query once", async () => { + page.url = new URL("http://localhost/dashboard-testing/runs?waiting_for_me=true"); + const fetchMock = vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [], total: 0 }); + + render(CenterPage); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledWith("/scenario-runs?waiting_for_me=true"); + }); +}); +// #endregion Test.ScenarioRun.CenterUX diff --git a/frontend/src/routes/dashboard-testing/runs/__tests__/runs_waiting_deeplink.ux.test.ts b/frontend/src/routes/dashboard-testing/runs/__tests__/runs_waiting_deeplink.ux.test.ts new file mode 100644 index 000000000..267f84039 --- /dev/null +++ b/frontend/src/routes/dashboard-testing/runs/__tests__/runs_waiting_deeplink.ux.test.ts @@ -0,0 +1,48 @@ +// #region Test.ScenarioRun.Route.WaitingDeepLink [C:3] [TYPE Module] [SEMANTICS test,scenario,run,center,deeplink,waiting,ux] +// @RELATION VERIFIES -> [ScenarioRun.Route.Center] +// @TEST_EDGE: ?waiting_for_me=true -> run center opens on the "awaiting my decision" view (badge target) +import { render, screen, waitFor } from "@testing-library/svelte"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("$app/state", () => ({ + page: { url: new URL("http://localhost/dashboard-testing/runs?waiting_for_me=true"), params: {} }, +})); +vi.mock("$lib/cot-logger", () => ({ log: vi.fn(), setTraceId: vi.fn(), getTraceId: () => "t" })); + +const mockFetch = vi.hoisted(() => vi.fn()); +vi.mock("$lib/api", () => ({ api: { fetchApi: mockFetch } })); + +import RunsPage from "../+page.svelte"; + +const runRow = { + id: "run-1", + scenario_id: "s1", + scenario_key: "sales-smoke", + scenario_name: "Sales Smoke", + scenario_revision_id: "rev-1", + environment_id: "env-prod", + status: "waiting_human", + phase: "waiting_human", + trigger_source: "manual", + created_at: null, + pending_checkpoint: null, +}; + +describe("Run center waiting_for_me deep link (Fix 2 polish)", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockFetch.mockResolvedValue({ items: [runRow], total: 1 }); + }); + + it("opens the waiting view and loads server-filtered when ?waiting_for_me=true", async () => { + render(RunsPage); + + await waitFor(() => expect(mockFetch).toHaveBeenCalled()); + // the first load is already narrowed by the deep-linked flag (server-side, per the model invariant) + expect(String(mockFetch.mock.calls[0][0])).toContain("waiting_for_me=true"); + // the waiting-for-me checkbox reflects the deep-linked state + const box = (await screen.findByRole("checkbox")) as HTMLInputElement; + expect(box.checked).toBe(true); + }); +}); +// #endregion Test.ScenarioRun.Route.WaitingDeepLink diff --git a/frontend/src/routes/dashboard-testing/scenarios/+page.svelte b/frontend/src/routes/dashboard-testing/scenarios/+page.svelte new file mode 100644 index 000000000..2fbf2a74d --- /dev/null +++ b/frontend/src/routes/dashboard-testing/scenarios/+page.svelte @@ -0,0 +1,206 @@ + + + + + + + + + + + + + +{dt.registry_title} + +
+ + {#snippet subtitle()} +

{dt.registry_subtitle}

+ {/snippet} + {#snippet actions()} + {dt.registry_runs_hub} + {/snippet} +
+ +
+ + + + +
+ + {#if model.loading} +
+ {dt.registry_loading} +
+ {:else if model.error} + + {:else if model.entries.length === 0} +
+ {dt.registry_empty} +
+ {:else} +
+
    + {#each model.entries as entry (entry.scenario_id)} +
  • +
    +
    + {entry.name || entry.scenario_key} + {lifecycleLabel(entry.lifecycle_status)} + {healthLabel(entry.health)} +
    +

    + {entry.scenario_key} · {dt.registry_owner}: {entry.owner_username || "—"} · + {dt.registry_envs}: {entry.environment_ids?.length ?? 0} +

    +
    +
    + {dt.registry_edit} + {dt.registry_analytics} + {#if entry.last_run_id} + {dt.registry_last_run} + {/if} +
    +
  • + {/each} +
+
+ {dt.registry_total}: {model.total} + {#if model.total > PAGE_SIZE} + + {/if} +
+
+ {/if} +
+ \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/scenarios/[id]/analytics/+page.svelte b/frontend/src/routes/dashboard-testing/scenarios/[id]/analytics/+page.svelte index 2b7a5ff6d..d66310dd7 100644 --- a/frontend/src/routes/dashboard-testing/scenarios/[id]/analytics/+page.svelte +++ b/frontend/src/routes/dashboard-testing/scenarios/[id]/analytics/+page.svelte @@ -11,7 +11,8 @@ -Аналитика сценария +{dt.scenario_analytics_title}
- + {#snippet subtitle()} -

Scenario {scenarioId} · здоровье, тренд и повторяющиеся отказы из истории запусков.

+

{dt.scenario_analytics_prefix} {scenarioId} · {dt.scenario_analytics_subtitle}

{/snippet} {#snippet actions()} - ← Регистр сценариев + {dt.scenario_analytics_back} {/snippet}
{#if model.loading} -
Загрузка аналитики…
+
{dt.scenario_analytics_loading}
{:else if model.error} {:else if model.health || model.trends || model.recurring.length > 0}
@@ -58,8 +60,8 @@
{:else}
- Аналитика недоступна — нет истории запусков + {dt.scenario_analytics_empty}
{/if}
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/scenarios/[id]/edit/+page.svelte b/frontend/src/routes/dashboard-testing/scenarios/[id]/edit/+page.svelte index 795fde005..fbde5836e 100644 --- a/frontend/src/routes/dashboard-testing/scenarios/[id]/edit/+page.svelte +++ b/frontend/src/routes/dashboard-testing/scenarios/[id]/edit/+page.svelte @@ -1,85 +1,128 @@ - + - + + + -Редактор сценария +{dt.editor_title}
- ← В регистр -

{model.editor?.scenario_key ?? "Редактор сценария"}

+ {dt.editor_back} +

{model.editor?.scenario_key ?? dt.editor_title}

{#if model.editor}

Revision {model.editor.base_revision_id} · {model.editor.content_hash.slice(0, 12)}

{/if}
-
- - -
{#if model.loading} -
Загрузка редактора…
+
{dt.editor_loading}
{:else if model.error} {:else if model.editor}
-
+
-

Граф проверки

-

Read-only projection · dirty: {String(model.editor.dirty)}

+

{dt.editor_graph_title}

+

{dt.editor_graph_hint}

{#if steps.length === 0} -
Шаги отсутствуют
+
{dt.editor_steps_empty}
{:else} {#each steps as step, index (String(step.logical_step_id ?? index))} {/each} - {#if firstAssertion} - ).comparison ?? "exact") as "exact" | "absolute" | "relative" | "range" | "row_set"} - initialBaselineRef={String((firstAssertion[1] as Record).baseline_ref ?? "baseline:")} - /> - {/if} {/if} + {#if firstAssertion} + ).comparison ?? "exact") as "exact" | "absolute" | "relative" | "range" | "row_set"} + initialBaselineRef={String((firstAssertion[1] as Record).baseline_ref ?? "baseline:")} + initialThreshold={Number((firstAssertion[1] as Record).threshold) || null} + onchange={updateAssertion} + /> + {/if} +
{/if}
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/+page.svelte b/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/+page.svelte index 72688e2ae..c8bdcb30b 100644 --- a/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/+page.svelte +++ b/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/+page.svelte @@ -7,7 +7,10 @@ -Мониторинг scenario run +{dt.monitor_title}
- ← Запуски сценариев -

Мониторинг scenario run

+ {dt.monitor_back} +

{dt.monitor_title}

- Run {runId} · Scenario run (не Verification run 037 и не Load test 040) · {model.run?.status ?? "…"} + {dt.monitor_run_prefix} {runId} · {dt.monitor_scenario_run} · {model.run?.status ?? "…"}

{#if model.state === "loading" && !model.run} -
Восстановление запуска по run id…
+
{dt.monitor_recovering}
{:else if model.state === "error" && !model.run} {:else if model.run} + {#if model.error} + + {/if} + {#if ["queued", "running", "waiting_human", "pending_approval"].includes(model.run.status)} + + {/if}
@@ -69,18 +89,19 @@
{/if}
- + \ No newline at end of file diff --git a/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/__tests__/run.ux.test.ts b/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/__tests__/run.ux.test.ts index ad0e795ff..0d9e812d1 100644 --- a/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/__tests__/run.ux.test.ts +++ b/frontend/src/routes/dashboard-testing/scenarios/[id]/runs/[runId]/__tests__/run.ux.test.ts @@ -9,8 +9,6 @@ import { page } from "$app/state"; import { api } from "$lib/api"; import DetailPage from "../+page.svelte"; -vi.mock("$app/paths", () => ({ resolve: (path: string) => path })); - beforeEach(() => { page.params = { id: "scenario-1", runId: "run-1" }; }); @@ -58,7 +56,8 @@ describe("RunMonitor route (run.ux)", () => { await fireEvent.click(screen.getByRole("button", { name: "False positive" })); await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/scenario-runs/run-1/human/decision", expect.anything())); - const body = JSON.parse(String((fetchMock.mock.calls.at(-1)?.[1] as { body?: string })?.body ?? "{}")); + const decisionCall = fetchMock.mock.calls.find(([endpoint]) => endpoint === "/scenario-runs/run-1/human/decision"); + const body = JSON.parse(String((decisionCall?.[1] as { body?: string })?.body ?? "{}")); expect(body.disposition).toBe("false_positive"); }); diff --git a/frontend/src/routes/dashboard-testing/scenarios/__tests__/scenarios_index.ux.test.ts b/frontend/src/routes/dashboard-testing/scenarios/__tests__/scenarios_index.ux.test.ts new file mode 100644 index 000000000..74da07eb5 --- /dev/null +++ b/frontend/src/routes/dashboard-testing/scenarios/__tests__/scenarios_index.ux.test.ts @@ -0,0 +1,94 @@ +// #region Test.ScenarioRegistry.Route.Index [C:3] [TYPE Module] [SEMANTICS test,scenario,registry,route,index,ux] +// @RELATION VERIFIES -> [ScenarioRegistry.Route.Index] +// @TEST_EDGE: rows render with SSOT ROUTES links to edit/analytics/last-run +// @TEST_EDGE: empty registry -> empty state; load failure -> typed error + retry +import { fireEvent, render, screen, waitFor } from "@testing-library/svelte"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { api } from "$lib/api"; +import IndexPage from "../+page.svelte"; + +const entry = { + scenario_id: "s1", + scenario_key: "sales-smoke", + name: "Sales Smoke", + description: null, + dashboard_id: 42, + environment_ids: ["env-prod"], + owner_id: "u1", + owner_username: "alice", + tags: [], + metadata_version: "1", + current_revision_id: "rev-1", + lifecycle_status: "READY", + validation_status: "valid", + last_run_id: "run-1", + last_successful_run_id: "run-1", + health: "pass", + baseline_compatibility: null, + last_modified_at: null, + created_at: null, +}; + +beforeEach(() => { + vi.restoreAllMocks(); +}); + +describe("Scenario registry index route", () => { + it("loads on mount and renders an entry with SSOT ROUTES action links", async () => { + const fetchMock = vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [entry], total: 1 }); + render(IndexPage); + + expect(await screen.findByRole("heading", { level: 1, name: "Реестр сценариев" })).toBeTruthy(); + expect(await screen.findByText("Sales Smoke")).toBeTruthy(); + expect(fetchMock).toHaveBeenCalledWith("/dashboard-testing/scenarios?page=1&page_size=20"); + + const edit = screen.getByRole("link", { name: "Редактировать" }) as HTMLAnchorElement; + expect(edit.getAttribute("href")).toBe("/dashboard-testing/scenarios/s1/edit"); + + const analytics = screen.getByRole("link", { name: "Аналитика" }) as HTMLAnchorElement; + expect(analytics.getAttribute("href")).toBe("/dashboard-testing/scenarios/s1/analytics"); + + const lastRun = screen.getByRole("link", { name: "Последний запуск" }) as HTMLAnchorElement; + expect(lastRun.getAttribute("href")).toBe("/dashboard-testing/scenarios/s1/runs/run-1"); + + expect(screen.getByText("Sales Smoke")).toBeTruthy(); + expect(await screen.findByText(/Всего:\s*1/)).toBeTruthy(); + }); + + it("omits the last-run link when the entry has no run history", async () => { + vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [{ ...entry, last_run_id: null }], total: 1 }); + render(IndexPage); + + expect(await screen.findByText("Sales Smoke")).toBeTruthy(); + expect(screen.queryByRole("link", { name: "Последний запуск" })).toBeNull(); + }); + + it("shows the empty state when the registry has no scenarios", async () => { + vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [], total: 0 }); + render(IndexPage); + + expect(await screen.findByText("Сценариев не найдено.")).toBeTruthy(); + }); + + it("shows a typed error state when the registry load fails", async () => { + vi.spyOn(api, "fetchApi").mockRejectedValue(new Error("boom")); + render(IndexPage); + + expect(await screen.findByText("Не удалось загрузить реестр")).toBeTruthy(); + expect(screen.getByText("boom")).toBeTruthy(); + }); + + it("paginates server-side when total exceeds the page size", async () => { + const fetchMock = vi.spyOn(api, "fetchApi").mockResolvedValue({ items: [entry], total: 25 }); + render(IndexPage); + + expect(await screen.findByText("Sales Smoke")).toBeTruthy(); + expect(screen.getByText(/Страница/)).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "Вперед" })); + await waitFor(() => + expect(fetchMock).toHaveBeenCalledWith("/dashboard-testing/scenarios?page=2&page_size=20"), + ); + }); +}); +// #endregion Test.ScenarioRegistry.Route.Index diff --git a/frontend/src/routes/dashboards/[id]/components/DashboardHeader.svelte b/frontend/src/routes/dashboards/[id]/components/DashboardHeader.svelte index 5fced18ca..413745469 100644 --- a/frontend/src/routes/dashboards/[id]/components/DashboardHeader.svelte +++ b/frontend/src/routes/dashboards/[id]/components/DashboardHeader.svelte @@ -9,6 +9,7 @@ import { t } from "$lib/i18n/index.svelte.js"; import Icon from "$lib/ui/Icon.svelte"; import BranchSelector from "$lib/components/git/BranchSelector.svelte"; + import { ROUTES } from "$lib/routes"; let { dashboard, @@ -37,7 +38,7 @@ envId: envId || "", route: `/dashboards/${objectId}`, }); - return `/agent?${params.toString()}`; + return ROUTES.agent(params.toString()); }); // 039 T007/T009: scenario mode opens /agent with contextVersion=2 + scenario intent (AGUI-FR-002). @@ -52,7 +53,7 @@ contextVersion: "2", intent: "build_dashboard_test_scenario", }); - return `/agent?${params.toString()}`; + return ROUTES.agent(params.toString()); }); @@ -112,10 +113,10 @@ - AI + {$t.assistant?.mcp_entry_short || "MCP"} {$t.load_testing?.nav || "Load test"} diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte index 1e982c319..623b81912 100644 --- a/frontend/src/routes/login/+page.svelte +++ b/frontend/src/routes/login/+page.svelte @@ -32,6 +32,15 @@ import { SvelteURLSearchParams } from "svelte/reactivity"; let showPassword = $state(false); let returnUrl: string | null = $state(null); + function oauthConsentUrl(): string | null { + if (page.url.searchParams.get('mcp_oauth') !== '1') return null; + const required = ['client_id', 'redirect_uri', 'code_challenge', 'code_challenge_method']; + if (required.some((key) => !page.url.searchParams.get(key))) return null; + const params = new URLSearchParams(page.url.searchParams); + params.delete('mcp_oauth'); + return `/oauth-consent?${params.toString()}`; + } + // Read returnUrl from query params on mount onMount(async () => { adfsConfigured = (await api.fetchApi<{ configured: boolean }>('/auth/adfs-configured').catch(() => ({ configured: false }))).configured; @@ -71,8 +80,12 @@ import { SvelteURLSearchParams } from "svelte/reactivity"; try { const user = await api.fetchApi('/auth/me'); auth.setUser(user); - // Use returnUrl if valid, otherwise go home - if (returnUrl) { + const consentUrl = oauthConsentUrl(); + // OAuth authorization parameters are preserved only in the browser and are + // never included in the application's JWT or callback URL. + if (consentUrl) { + goto(consentUrl, { replaceState: true }); + } else if (returnUrl) { goto(returnUrl, { replaceState: true }); } else { goto(ROUTES.home(), { replaceState: true }); @@ -103,7 +116,10 @@ import { SvelteURLSearchParams } from "svelte/reactivity"; onMount(() => { if ($auth.isAuthenticated) { - if (returnUrl) { + const consentUrl = oauthConsentUrl(); + if (consentUrl) { + goto(consentUrl, { replaceState: true }); + } else if (returnUrl) { goto(returnUrl, { replaceState: true }); } else { goto(ROUTES.home(), { replaceState: true }); diff --git a/frontend/src/routes/oauth-consent/+page.svelte b/frontend/src/routes/oauth-consent/+page.svelte new file mode 100644 index 000000000..89eb9ed52 --- /dev/null +++ b/frontend/src/routes/oauth-consent/+page.svelte @@ -0,0 +1,68 @@ + + + + + + + + + + +
+ +

Authorize MCP client

+ {#if isValid} +

Allow this client to act as your ss-tools account.

+
+
Client
{clientId}
+
Requested scopes
{scope}
+
+ {#if error}{/if} +
+ + +
+ {:else} + + + {/if} +
+
+ diff --git a/frontend/src/routes/settings/SystemSettings.svelte b/frontend/src/routes/settings/SystemSettings.svelte index 326d21b5f..068d1b273 100644 --- a/frontend/src/routes/settings/SystemSettings.svelte +++ b/frontend/src/routes/settings/SystemSettings.svelte @@ -1,4 +1,4 @@ - + @@ -39,6 +39,9 @@ { key: "auth_max_attempts", min: 1, max: 100 }, { key: "auth_attempt_window", min: 30, max: 3600 }, { key: "auth_ban_duration", min: 60, max: 86400 }, + { key: "mcp_oauth_access_minutes", min: 1, max: 60 }, + { key: "mcp_oauth_refresh_default_days", min: 1, max: 90 }, + { key: "mcp_oauth_refresh_max_days", min: 1, max: 365 }, { key: "translate_baseline_expiry_days", min: 1, max: 3650 }, ] as const; @@ -47,7 +50,7 @@ const value = settings[key]; if (typeof value !== "number" || Number.isNaN(value)) return false; return value < min || value > max; - }), + }) || settings.mcp_oauth_refresh_default_days > settings.mcp_oauth_refresh_max_days, ); async function handleSave() { @@ -278,6 +281,47 @@ + +
+

MCP OAuth

+

Set the lifetime of the short-lived access token and each user’s rotating refresh-token connection.

+ +
+
+ 60 ? "Value must be between 1 and 60" : ""} + /> + 90 ? "Value must be between 1 and 90" : ""} + /> + 365 || settings.mcp_oauth_refresh_default_days > settings.mcp_oauth_refresh_max_days ? "Maximum must be 1–365 days and no shorter than the default" : ""} + /> +
+
+
+

{$t.settings?.translate_baseline_expiry || "Translation baseline"}

diff --git a/frontend/src/types/scenario-analytics.ts b/frontend/src/types/scenario-analytics.ts index e3db20594..fa45a6a7b 100644 --- a/frontend/src/types/scenario-analytics.ts +++ b/frontend/src/types/scenario-analytics.ts @@ -27,7 +27,8 @@ export type InvestigationCaseStatus = | "accepted" | "reopened"; -export type DispositionKind = "confirmed" | "false_positive" | "duplicate" | "fixed" | "accepted_risk" | "wont_fix"; +/** Terminal case decisions accepted by the 047 disposition API. */ +export type DispositionKind = "resolved" | "accepted"; export interface InvestigationCase { id: string; diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js index 3251241d7..35a77f20f 100644 --- a/frontend/tailwind.config.js +++ b/frontend/tailwind.config.js @@ -34,6 +34,7 @@ export default { admin: { from: '#3c1f2b', to: '#4a2431', text: '#e66f78', ring: '#fca5a5' }, maintenance: { from: '#3c2e1d', to: '#4a351d', text: '#f4bd69', ring: '#f4bd69' }, assistant: { from: '#302449', to: '#3d2b58', text: '#c084fc', ring: '#bd94fa' }, + testing: { from: '#0f3a4a', to: '#14505f', text: '#56d8d5', ring: '#56d8d5' }, }, }, width: { sidebar: '240px', 'sidebar-collapsed': '64px' }, diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 5847a7e45..9aa3af70b 100755 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -24,6 +24,10 @@ export default defineConfig({ plugins: [sveltekit()], server: { proxy: { + '^/(mcp(?:/|$)|oauth/|\\.well-known/)': { + target: process.env.BACKEND_URL || 'http://127.0.0.1:8000', + changeOrigin: false + }, '/api': { target: process.env.BACKEND_URL || 'http://127.0.0.1:8000', changeOrigin: true, diff --git a/run.sh b/run.sh index c1798ee2b..3e477eff8 100755 --- a/run.sh +++ b/run.sh @@ -295,6 +295,73 @@ ensure_jwt_secret() { ensure_jwt_secret +# MCP OAuth uses an asymmetric signing key so resource servers can verify tokens through JWKS. +# This development launcher persists a generated key locally; production compose profiles must +# continue to provide MCP_JWT_PRIVATE_KEY explicitly from their secret manager. +ensure_mcp_oauth_key() { + local ENV_FILE="backend/.env" + local key="" + + if [ -f "$ENV_FILE" ]; then + # The PEM is stored on one dotenv line with literal \n separators and is expanded + # by src.services.mcp_keys at runtime. + for line in $(grep "^MCP_JWT_PRIVATE_KEY=" "$ENV_FILE" | head -1); do + key="${line#MCP_JWT_PRIVATE_KEY=}" + done + fi + + if [ -n "$key" ] && MCP_JWT_PRIVATE_KEY="$key" python3 -c ' +import os +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +key = serialization.load_pem_private_key(os.environ["MCP_JWT_PRIVATE_KEY"].replace("\\n", "\n").encode(), password=None) +raise SystemExit(0 if isinstance(key, RSAPrivateKey) and key.key_size >= 2048 else 1) +' 2>/dev/null; then + export MCP_JWT_PRIVATE_KEY="$key" + echo "MCP OAuth key preflight: existing MCP_JWT_PRIVATE_KEY reused from $ENV_FILE" + return + fi + + if ! command -v openssl >/dev/null 2>&1; then + echo "Error: openssl is required to generate MCP_JWT_PRIVATE_KEY for local development." >&2 + exit 1 + fi + local new_key + new_key=$(openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 2>/dev/null | sed ':a;N;$!ba;s/\n/\\n/g') + if [ -z "$new_key" ]; then + echo "Error: unable to generate MCP_JWT_PRIVATE_KEY." >&2 + exit 1 + fi + # Earlier development versions wrote a multiline PEM with echo, which leaves invalid + # continuation lines in dotenv files. Replace the whole old block atomically with one + # escaped line; Python's dotenv reader and our loader both then receive the same value. + python3 - "$ENV_FILE" "$new_key" <<'PY' +import sys +from pathlib import Path + +path = Path(sys.argv[1]) +encoded_key = sys.argv[2] +source = path.read_text(encoding="utf-8") if path.exists() else "" +result: list[str] = [] +skipping_pem = False +for line in source.splitlines(): + if line.startswith("MCP_JWT_PRIVATE_KEY="): + skipping_pem = True + continue + if skipping_pem: + if line.strip() == "-----END PRIVATE KEY-----": + skipping_pem = False + continue + result.append(line) +result.append(f"MCP_JWT_PRIVATE_KEY={encoded_key}") +path.write_text("\n".join(result) + "\n", encoding="utf-8") +PY + export MCP_JWT_PRIVATE_KEY="$new_key" + echo "MCP OAuth key preflight: MCP_JWT_PRIVATE_KEY generated and saved to $ENV_FILE" +} + +ensure_mcp_oauth_key + # Backend dependency management setup_backend() { if [ "$SKIP_INSTALL" = true ]; then diff --git a/scripts/mcp_proxy_fixture.py b/scripts/mcp_proxy_fixture.py new file mode 100644 index 000000000..f04417980 --- /dev/null +++ b/scripts/mcp_proxy_fixture.py @@ -0,0 +1,28 @@ +# #region Tooling.McpProxyFixture [C:2] [TYPE Module] [SEMANTICS docker,mcp,nginx,fixture] +# @BRIEF Echo only synthetic transport facts for the isolated nginx smoke; no application database. +import json +from http.server import BaseHTTPRequestHandler, HTTPServer + + +# #region Tooling.McpProxyFixture.Handler [C:2] [TYPE Class] +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Mcp-Session-Id", self.headers.get("Mcp-Session-Id", "fixture-session")) + self.end_headers() + self.wfile.write(json.dumps({ + "path": self.path, "method": self.command, "host": self.headers.get("Host"), + "scheme": self.headers.get("X-Forwarded-Proto"), + "authorization": self.headers.get("Authorization") == "Bearer smoke-fixture", + "session": self.headers.get("Mcp-Session-Id"), + }).encode()) + + do_POST = do_GET + do_DELETE = do_GET +# #endregion Tooling.McpProxyFixture.Handler + + +if __name__ == "__main__": + HTTPServer(("0.0.0.0", 8000), Handler).serve_forever() +# #endregion Tooling.McpProxyFixture diff --git a/scripts/mcp_proxy_smoke.py b/scripts/mcp_proxy_smoke.py new file mode 100644 index 000000000..948cbc40e --- /dev/null +++ b/scripts/mcp_proxy_smoke.py @@ -0,0 +1,74 @@ +# #region Tooling.McpProxySmoke [C:3] [TYPE Module] [SEMANTICS docker,mcp,nginx,verification] +# @BRIEF Isolated real nginx smoke for HTTP/TLS MCP routing, authority and protocol headers. +# @POST Containers and network created by this invocation are removed, including on assertion failure. +# @REJECTED Reusing the development compose project could attach tests to the operator database. +from __future__ import annotations + +import json +import subprocess +import time +import urllib.request +import uuid +from pathlib import Path + + +# #region Tooling.McpProxySmoke.Command [C:2] [TYPE Function] +def docker(*args: str) -> str: + return subprocess.check_output(["docker", *args], text=True).strip() +# #endregion Tooling.McpProxySmoke.Command + + +# #region Tooling.McpProxySmoke.Run [C:3] [TYPE Function] +def main() -> None: + root = Path(__file__).resolve().parents[1] + prefix = "ss-mcp-proxy-smoke-" + uuid.uuid4().hex[:10] + network, backend, frontend = prefix, prefix + "-backend", prefix + "-frontend" + try: + docker("network", "create", network) + docker( + "run", "-d", "--name", backend, "--network", network, "--network-alias", "backend", + "-v", f"{root / 'scripts/mcp_proxy_fixture.py'}:/fixture.py:ro", + "python:3.12-alpine", "python", "/fixture.py", + ) + docker( + "run", "-d", "--name", frontend, "--network", network, + "-p", "127.0.0.1::80", + "-v", f"{root / 'docker/nginx.conf'}:/etc/nginx/conf.d/default.conf:ro", + "nginx:1.27-alpine", + ) + docker("exec", frontend, "nginx", "-t") + port = docker("port", frontend, "80/tcp").rsplit(":", 1)[1] + origin = f"http://127.0.0.1:{port}" + for _ in range(50): + try: + urllib.request.urlopen(origin + "/.well-known/oauth-authorization-server", timeout=2) + break + except OSError: + time.sleep(0.2) + for path, method in [ + ("/.well-known/oauth-authorization-server", "GET"), + ("/.well-known/oauth-protected-resource/mcp", "GET"), + ("/oauth/token", "POST"), ("/oauth/register", "POST"), + ("/oauth/register/fixture", "DELETE"), ("/mcp", "POST"), ("/mcp/", "GET"), + ]: + request = urllib.request.Request( + origin + path, method=method, + data=b'{"jsonrpc":"2.0"}' if method == "POST" else None, + headers={"Authorization": "Bearer smoke-fixture", "Mcp-Session-Id": "fixture-session"}, + ) + with urllib.request.urlopen(request, timeout=5) as response: + payload = json.load(response) + assert response.headers["Mcp-Session-Id"] == "fixture-session" + assert payload == {"path": path, "method": method, "host": f"127.0.0.1:{port}", + "scheme": "http", "authorization": True, "session": "fixture-session"} + print("PASS: nginx routes discovery, OAuth and MCP with external port, bearer and session headers") + finally: + for name in (frontend, backend): + subprocess.run(["docker", "rm", "-f", name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["docker", "network", "rm", network], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +# #endregion Tooling.McpProxySmoke.Run + + +if __name__ == "__main__": + main() +# #endregion Tooling.McpProxySmoke diff --git a/specs/038-dashboard-scenario-model/contracts/modules.md b/specs/038-dashboard-scenario-model/contracts/modules.md index 301f6c447..bb9613b66 100644 --- a/specs/038-dashboard-scenario-model/contracts/modules.md +++ b/specs/038-dashboard-scenario-model/contracts/modules.md @@ -189,16 +189,18 @@ bindings in `RunPreflight`. @BRIEF Persistent external MCP agent/user authoring, exploratory sandbox and promotion contract. @RELATION DEPENDS_ON -> [ScenarioGraph.ServerOwnedPipeline] @RELATION DISPATCHES -> [ScenarioRegistry.SaveContinuation] +@RELATION CALLS -> [ScenarioRegistry.CreateInitial] -`create_authoring_session` creates or idempotently returns a server-owned workspace. `propose_test_plan`, `start_exploration`, `get_exploration_result`, `propose_graph_revision`, `get_graph_diff`, and `promote_to_scenario` operate on that persistent workspace. Every mutation carries an idempotency key and expected `cas_version`; stale versions return typed 409 with no partial state. +`create_authoring_session` creates or idempotently returns a server-owned workspace for an existing scenario revision. `bootstrap_authoring_scenario` accepts only a bounded InitialScenarioIntent and server-issued compiled/draft-pack handles, calls `ScenarioRegistry.CreateInitial`, and returns a workspace bound to the new current revision. The two entry paths are mutually exclusive: an unbound workspace may hold a test plan or exploration receipt, but cannot propose, promote, save, activate, or launch a graph. `propose_test_plan`, `start_exploration`, `get_exploration_result`, `propose_graph_revision`, `get_graph_diff`, and `promote_to_scenario` operate on the persistent workspace. Every mutation carries an idempotency key and expected `cas_version`; stale versions return typed 409 with no partial state. Exploration executes only in an isolated sandbox with allowlisted origins/APIs/actions, bounded time/size/network budgets, cancellation, durable operation receipts, server-owned artifact ownership and cleanup. Shell, credentials, cookies, filesystem/network escape and production side effects are forbidden. Sandbox readiness/security is a release gate, not an implementation claim. `start_exploration` may yield only `AuthoringArtifact` and `ExplorationResult`; `propose_graph_revision` converts them to typed registered-action candidates. The server supplies reviewed templates/actions and does not generate arbitrary Playwright code. `promote_to_scenario` invokes deterministic Compile/Validate, presents a server-computed diff, requires user review, then hands only valid server handles to 042. Production execution accepts only the resulting promoted immutable revision; raw code and artifacts never pass through as authority. @INVARIANT Authoring artifacts and ExecutionProgram are separate domains; an artifact digest, caller digest, URL, path or source text cannot establish graph, revision or run authority. +@INVARIANT A first scenario is created only through the server-owned bootstrap transaction; no client-side fixture, synthetic base revision, or unbound test plan is a registry creation substitute. @INVARIANT The future code-backed provider is unimplemented and separately gated; it is not implied by sandbox support. -@TEST_EDGE sandbox_limit_or_cancel -> exploration_failed; invalid_candidate -> validation_blocked; stale_cas -> 409; unreviewed_diff -> no promotion. +@TEST_EDGE bootstrap replay -> same scenario/revision/workspace; unbound proposal -> typed state error with no registry row; sandbox_limit_or_cancel -> exploration_failed; invalid_candidate -> validation_blocked; stale_cas -> 409; unreviewed_diff -> no promotion. ## @} ScenarioGraph.AgentAuthoringWorkspace #endregion DashboardScenarioModel.Modules diff --git a/specs/042-dashboard-scenario-registry/contracts/modules.md b/specs/042-dashboard-scenario-registry/contracts/modules.md index 56fb05c90..6129de33b 100644 --- a/specs/042-dashboard-scenario-registry/contracts/modules.md +++ b/specs/042-dashboard-scenario-registry/contracts/modules.md @@ -29,6 +29,21 @@ def list_scenarios(db, filters, page, page_size): ... def get_scenario(db, scenario_id): ... # #endregion ScenarioRegistry.Get +## @{ ScenarioRegistry.CreateInitial [C:5] [TYPE Function] +@BRIEF Create the first registry entry and its immutable current revision from server-owned validated handles. +@PRE Caller has scenario:create; the dashboard/environment binding is authorized; the compiled graph and draft-pack handles are server-issued, valid, and mutually bound by content hash. +@POST Creates exactly one ScenarioRegistryEntry and one initial ScenarioRevision with activation_status=current; returns their opaque IDs and content hash. A matching idempotency replay returns the same IDs. +@SIDE_EFFECT Writes the registry entry, immutable revision, audit record, and materialization outbox in one transaction. +@DATA_CONTRACT InitialScenarioIntent + CompiledScenarioHandle + DraftPackHandle -> ScenarioRegistryEntry + ScenarioRevision +@INVARIANT A client never uploads a graph, content hash, or revision ID as authority. Initial creation does not require a synthetic base revision. +@RELATION DEPENDS_ON -> [ScenarioGraph.ServerOwnedPipeline] +@RELATION CALLED_BY -> [ScenarioGraph.AgentAuthoringBootstrap] +@RATIONALE The first scenario has no base revision, while normal RevisionChain requires one; a dedicated creation transition removes the circular dependency without weakening revision immutability. +@REJECTED Seeding a registry entry or base revision in the MCP client/test fixture as a substitute for a production creation path. +@TEST_EDGE duplicate-idempotency-key -> same IDs; stale-or-unbound-handle -> no rows; unauthorized-dashboard -> no disclosure. +def create_initial_scenario(db, intent, compiled_handle, draft_pack_handle, actor, idempotency_key): ... +## @} ScenarioRegistry.CreateInitial + # #region ScenarioRegistry.RevisionChain [C:4] [TYPE Function] [SEMANTICS scenario,registry,revision,chain] # @ingroup ScenarioRegistry # @BRIEF Append an immutable candidate revision on validated save. diff --git a/specs/046-dashboard-scenario-automation/contracts/modules.md b/specs/046-dashboard-scenario-automation/contracts/modules.md index fefe0cb25..e196c3f11 100644 --- a/specs/046-dashboard-scenario-automation/contracts/modules.md +++ b/specs/046-dashboard-scenario-automation/contracts/modules.md @@ -55,4 +55,22 @@ def run_retention(db, policy): ... # @BRIEF Report scheduled-run counts, success rate, trigger distribution, repeated-failure alerts. def automation_metrics(db): ... # #endregion Automation.Metrics + +# #region Automation.McpSchedule [C:5] [TYPE Function] [SEMANTICS scenario,automation,mcp,schedule,policy] +# @ingroup ScenarioAutomation +# @BRIEF Expose schedule, trigger-rule, policy and automation-metric management through curated MCP operations. +# @PRE Caller has the same automation scopes as the REST surface; each write supplies an idempotency key and an explicit active revision, environment and policy input. +# @POST List/get operations return bounded server-owned projections. Upsert/delete operations return the durable schedule/rule/policy projection or a typed approval_required envelope; no duplicate scheduler job is registered on replay. +# @SIDE_EFFECT Schedule/rule/policy writes may update APScheduler registration; a PROD due event may create one approval gate but never dispatch before its decision. +# @DATA_CONTRACT McpScheduleRequest -> ScenarioSchedule | ScenarioTriggerRule | AutomationPolicy | AutomationMetricsProjection +# @INVARIANT A revision containing HumanSteps is rejected before schedule, run, queue, notification or approval-gate mutation. MCP wrappers reuse Automation.Schedule/Trigger/ApplyPolicy and never implement a second scheduler. +# @RELATION CALLS -> [Automation.Schedule] +# @RELATION CALLS -> [Automation.Trigger] +# @RELATION CALLS -> [Automation.ApplyPolicy] +# @RELATION CALLS -> [Automation.Metrics] +# @RATIONALE The 050 external-client boundary must have the same policy-governed automation capability as the 046 UI/API; hiding it behind a browser surface breaks MCP parity. +# @REJECTED A generic MCP payload that can invoke arbitrary scheduler jobs or bypass revision eligibility, deduplication, environment policy or PROD gates. +# @TEST_EDGE human-step revision -> no side effect; replay -> same schedule ID; stale revision -> typed conflict; PROD due event -> one pending gate before dispatch. +# def manage_automation_over_mcp(db, request, actor): ... +# #endregion Automation.McpSchedule #endregion ScenarioAutomation.Modules diff --git a/specs/046-dashboard-scenario-automation/spec.md b/specs/046-dashboard-scenario-automation/spec.md index 66a7428c8..8ceedeb56 100644 --- a/specs/046-dashboard-scenario-automation/spec.md +++ b/specs/046-dashboard-scenario-automation/spec.md @@ -75,6 +75,7 @@ 1. **Given** automation is configured **When** the Automation Management UI opens **Then** schedules, trigger rules, and policies are listed and editable (create/update/delete/enable). 2. **Given** an external system needs to trigger a run **When** it calls `POST /scenarios/{id}/trigger` **Then** a run starts (distinct from configuring a trigger rule). 3. **Given** a PROD external trigger **When** invoked **Then** an ActionApprovalGate is required before dispatch. +4. **Given** an authenticated external MCP client with automation scopes **When** it manages schedules, trigger rules or policies **Then** it receives the same bounded projections, validation, RBAC and gate outcomes as the Automation Management UI/API. --- @@ -114,6 +115,8 @@ - **SCAUTO-FR-014**: Automation management and policy decisions MUST be completed in persistent pages, agent cases or inline cards; modal/dialog interaction MUST NOT be required. - **SCAUTO-FR-015**: Scheduler semantics MUST be explicit (timezone, DST, misfire_grace_time, coalesce, max_instances, missed-execution policy, scheduler-restart handling). - **SCAUTO-FR-016**: Retention MUST use layered tiers; the analytics minimum history window (047) MUST be guaranteed independent of run retention. +- **SCAUTO-FR-017**: MCP MUST expose curated operations to list, upsert and delete schedules and trigger rules; get/upsert automation policy; and get automation metrics. Each mutation MUST accept an idempotency key, explicit active revision and environment, reuse the 046 services, and return the same typed validation/conflict/approval outcomes as REST. Generic scheduler-job invocation is forbidden. +- **SCAUTO-FR-018**: An MCP schedule mutation for a revision containing HumanSteps MUST be rejected before schedule, run, queue, notification or approval-gate mutation. A scheduled PROD due event for an eligible revision MUST create at most one durable gate before dispatch; denial or expiry leaves dispatch unstarted. ### Key Entities diff --git a/specs/050-mcp-interface/plans/initial-scenario-test-pack-automation-handoff.md b/specs/050-mcp-interface/plans/initial-scenario-test-pack-automation-handoff.md new file mode 100644 index 000000000..6481163dc --- /dev/null +++ b/specs/050-mcp-interface/plans/initial-scenario-test-pack-automation-handoff.md @@ -0,0 +1,100 @@ +## @{ McpInterface.InitialScenarioTestPackAutomation.Handoff [C:5] [TYPE ADR] +@BRIEF Implementation handoff: allow an external MCP client to create a first scenario, persist a complete test pack, and configure safe automation. +@RELATION DEPENDS_ON -> [ScenarioGraph.AgentAuthoringWorkspace] +@RELATION DEPENDS_ON -> [ScenarioRegistry.CreateInitial] +@RELATION DEPENDS_ON -> [ScenarioExecution.RunPreflight] +@RELATION DEPENDS_ON -> [Automation.Schedule] +@RATIONALE Current MCP authoring can edit an existing revision, but an unbound workspace cannot propose a graph; tests mask this by pre-seeding ScenarioRegistryEntry and ScenarioRevision. +@REJECTED Creating registry rows or synthetic base revisions in an MCP client, browser client, or test fixture as the production bootstrap path. + +## Goal + +An authenticated MCP user can create a dashboard scenario from server-owned dashboard context; complete and save a test pack; activate the resulting immutable revision; and configure a schedule only for an automation-eligible revision. + +## Verified current gap + +- `create_authoring_session` permits `scenario_id=null`. +- `propose_graph_revision` rejects that workspace because both `scenario_id` and `base_revision_id` are required. +- Existing MCP E2E tests call `_seed_registry(...)` before their session. +- MCP exposes no schedule, trigger-rule, policy or automation-metrics tools although specs 046 and 050 require schedule management through MCP. + +## Required design + +### 1. Initial scenario bootstrap + +Add a curated MCP tool named `bootstrap_authoring_scenario`. + +Input: bounded `InitialScenarioIntent` (title, dashboard ID, allowed environment IDs, selected case IDs, objective) plus opaque server-issued compiled-scenario and draft-pack handles. It must not accept a graph, revision ID, content hash, SQL, arbitrary code, source path, URL, cookie, or secret. + +Server transaction: + +1. Re-resolve dashboard/environment ACL and ownership. +2. Verify compiled and draft-pack handles are valid, save-eligible and bound to the same server-computed content hash. +3. Call `ScenarioRegistry.CreateInitial` to write one registry entry, one immutable current revision, audit provenance and materialization outbox atomically. +4. Create a workspace bound to that scenario and base revision. +5. Return opaque `scenario_id`, `revision_id`, `workspace_id`, `content_hash`, CAS version and activation state. + +Invariants: idempotency replay returns the same IDs; failed validation/ACL/CAS creates no row; initial creation never relies on a synthetic base revision; only a server-owned graph handle is persisted. + +### 2. Full test-pack profile + +Introduce a typed server-owned `TestPackProfile`/`InitialScenarioIntent` mapping: + +- dashboard context and selected checklist case IDs; +- chart/metric references, filter bindings and selector requirements; +- parameter defaults and safe fixtures; +- evidence requirements and metric/visual baseline references; +- explicit unresolved state (`needs_context`, `needs_selector`, `needs_baseline`) rather than guessed values. + +The compiler must produce `preview_only` when unresolved requirements exist. Only a valid, baseline-complete pack can be passed to initial creation or normal save. + +### 3. MCP automation parity + +Add curated tools, each reusing 046 services and the same REST RBAC/policy checks: + +- `list_scenario_schedules`, `upsert_scenario_schedule`, `delete_scenario_schedule`; +- `list_scenario_trigger_rules`, `upsert_scenario_trigger_rule`, `delete_scenario_trigger_rule`; +- `get_scenario_automation_policy`, `upsert_scenario_automation_policy`; +- `get_scenario_automation_metrics`. + +Schedule writes accept only an explicit active revision, environment, cron/timezone, misfire/concurrency/dedup settings and idempotency key. A revision containing human steps is rejected before any schedule/gate/run write. PROD schedule dispatch stays gate-controlled and requires a separate approval decision. + +## Implementation order + +1. Add/align contracts and schemas in specs 038, 042, 046 and 050. +2. Implement `ScenarioRegistry.CreateInitial` with migration only if the existing registry model lacks fields for title/environment ownership; add transactional unit tests. +3. Implement `bootstrap_authoring_scenario` MCP schema, tool registration, RBAC and invocation provenance. +4. Implement `TestPackProfile` validation and draft-pack eligibility; add fixture dashboard tests with metric, visual, filter and unresolved branches. +5. Add MCP automation wrappers around existing 046 routes/services; do not duplicate scheduling logic. +6. Replace seeded-registry MCP E2E setup with a no-preseed initial-creation E2E; then cover save, activation, manual run and scheduled eligibility. +7. Add real scheduler callback integration evidence for eligible PROD and verify `pending_approval` before any dispatch. + +## Acceptance checks + +- A fresh database, no registry seed: external MCP client creates a first scenario and it appears in `GET /scenarios`. +- Repeating an identical bootstrap key returns the original IDs; changing the payload with the same key yields typed idempotency conflict. +- Invalid handle, stale dashboard context, missing selector/baseline or revoked scope leaves registry/outbox/workspace unchanged. +- Full test pack reports explicit coverage for selected checks and never invents metric expectations. +- Only an active, automation-eligible revision can be scheduled; human-step revisions have zero schedule/run/gate/queue side effects. +- A PROD scheduled due event creates at most one durable gate before dispatch; deny leaves no run dispatch. +- MCP schedule CRUD matches 046 REST outcome and RBAC behavior. + +## Estimated scope + +| Workstream | Production LOC | Test/fixture LOC | +|---|---:|---:| +| Initial bootstrap + registry transaction + MCP registration | 450-750 | 350-550 | +| Test-pack profile and baseline binding | 400-700 | 300-500 | +| MCP schedule/trigger/policy parity | 250-450 | 250-400 | +| Real scheduling E2E and provider/scheduler proof | 100-200 | 300-600 | +| Total | 1,200-2,100 | 1,200-2,050 | + +Specification, OpenAPI, traceability and task updates are expected to add 300-550 Markdown/YAML lines. Total implementation is roughly 2,700-4,700 LOC including tests. + +## Non-goals + +- Do not run arbitrary browser code, SQL, shell commands or client-supplied graphs. +- Do not execute a production deployment, migration, backup or scheduled run merely to prove the MCP path. +- Do not make materialized `scenario.yaml` or `runner.plan.json` authoritative. + +## @} McpInterface.InitialScenarioTestPackAutomation.Handoff diff --git a/specs/050-mcp-interface/spec.md b/specs/050-mcp-interface/spec.md index 352cf2466..defeab9ab 100644 --- a/specs/050-mcp-interface/spec.md +++ b/specs/050-mcp-interface/spec.md @@ -167,7 +167,7 @@ HumanCheckpoint disposition (`waiting_human` runs, 044) is also completable insi - **MCPX-FR-003**: The `/mcp` endpoint MUST authenticate every request through the Authorization Model above; `tools/list` MUST filter by caller RBAC and every invocation MUST re-enforce permissions server-side (single server-side policy source; the agent-side `_tool_filter`/`_guard_tool_permission` logic is absorbed here). - **MCPX-FR-004**: Every tool invocation MUST persist AgentAction provenance (principal, tool, arguments digest, outcome, linked AgentRun where applicable) and MUST pass deterministic ACL/environment/capacity checks before execution, inheriting AGSTAB-FR-011. - **MCPX-FR-005**: Non-delegated risky actions MUST return the typed `approval_required` envelope bound to a durable ActionApprovalGate. The approval loop MUST be completable entirely within MCP (`list_pending_approvals` + `decide_approval`); web gate cards (042/043/045 product pages) remain an equal renderer of the same durable gates. Denial MUST record cancellation with zero side effects; decision tools MUST reject service principals and expired/decided gates with typed errors. -- **MCPX-FR-006**: The scenario-authoring chain (inspect query model, compile, validate, resolve, draft-pack, request-save) MUST be fully available via MCP; all mutable state MUST live server-side (WorkingDraft, revisions, candidates). +- **MCPX-FR-006**: The scenario-authoring chain (inspect query model, compile, validate, resolve, draft-pack, initial bootstrap, request-save) MUST be fully available via MCP; all mutable state MUST live server-side (WorkingDraft, revisions, candidates). - **MCPX-FR-007**: Tool responses MUST be bounded; artifacts larger than the inline limit MUST be returned as typed refs with digests resolvable through existing artifact APIs. - **MCPX-FR-007a**: MCP transport and every tool schema MUST enforce server-owned request byte, JSON-depth, collection-count, string-length, graph-size, and per-session rate limits before dispatch. Rejection is typed and creates no mutable state; bounded responses alone are insufficient. - **MCPX-FR-008**: The initial catalog MUST provide 1:1 parity with the current 37 tools across domains: environments/health/tasks, git/deploy/migration/backup/maintenance, Superset operations (read + admin CRUD), baseline capture/approval/verification, scenario compile/validate/resolve/draft-pack/save. `show_capabilities` is retired in favor of standard `tools/list`. @@ -187,6 +187,8 @@ HumanCheckpoint disposition (`waiting_human` runs, 044) is also completable insi - **MCPX-FR-022**: The catalog MUST provide the persistent `AgentAuthoringWorkspace` operations `create_authoring_session`, `propose_test_plan`, `start_exploration`, `get_exploration_result`, `propose_graph_revision`, `get_graph_diff`, and `promote_to_scenario` (or an explicitly versioned equivalent) with server-owned state, provenance, idempotency and CAS. - **MCPX-FR-023**: Authoring exploration MUST use an isolated, allowlisted, time/size/network-bounded and cancellable sandbox with durable receipts and artifact ownership; shell, credential, filesystem/network escape and production side effects MUST be rejected. Sandbox readiness is a release gate, not an implementation claim. - **MCPX-FR-024**: MCP MUST pass authoring output only as typed 038 action candidates/graph proposals through deterministic compile/validate, user-reviewed diff, and 042 handle-based save. Raw code, browser URLs, cookies, secrets, filesystem paths and caller digests MUST never establish authority; code-backed production execution is a separate unimplemented contract. +- **MCPX-FR-025**: MCP MUST provide `bootstrap_authoring_scenario` for a first scenario. It accepts only a bounded InitialScenarioIntent and server-issued valid compiled/draft-pack handles; atomically creates the registry entry, initial current revision, provenance/outbox and a workspace bound to that revision. It MUST NOT require or accept a client-created base revision, graph, content hash or revision ID. +- **MCPX-FR-026**: MCP MUST expose the SCAUTO-FR-017 automation operations with identical REST policy/RBAC behavior. Schedule mutations require an explicit active revision, environment and idempotency key; they reject HumanStep revisions before any durable side effect and preserve the 046 PROD gate before dispatch. ### Canonical Scenario MCP Names @@ -195,6 +197,7 @@ The following snake_case names are the canonical MCP names for the complete auth | Canonical MCP name | Responsibility | Legacy REST operationId alias(es) | |---|---|---| | `inspect_dashboard_context` | Inspect dashboard/query context | `inspectDashboardQueryModel` | +| `bootstrap_authoring_scenario` | Atomically create a first scenario, initial current revision and bound workspace from server-owned handles | `scenarioRegistry.create` | | `create_authoring_session` | Create persistent authoring workspace | none; MCP-only workspace operation | | `propose_test_plan` | Record typed test-plan intent | none; MCP-only workspace operation | | `start_exploration` | Start bounded authoring exploration | none; MCP-only workspace operation | @@ -209,6 +212,9 @@ The following snake_case names are the canonical MCP names for the complete auth | `request_save` | Create immutable candidate revision, or eligible initial current revision | `editor.save`, `scenarioRegistry.create` | | `activate_revision` | CAS-activate an eligible materialized revision | `scenarioRegistry.activateCurrentRevision` | | `start_scenario_run` | Start a run pinned to an explicit promoted revision | `scenarioRun.start` | +| `list_scenario_schedules` / `upsert_scenario_schedule` / `delete_scenario_schedule` | Manage schedule projections through 046 policy | `automation.listSchedules`, `automation.upsertSchedule`, `automation.deleteSchedule` | +| `list_scenario_trigger_rules` / `upsert_scenario_trigger_rule` / `delete_scenario_trigger_rule` | Manage event trigger rules through 046 policy | `automation.listTriggerRules`, `automation.upsertTriggerRule`, `automation.deleteTriggerRule` | +| `get_scenario_automation_policy` / `upsert_scenario_automation_policy` / `get_scenario_automation_metrics` | Read or manage automation policy and observability | `automation.getPolicy`, `automation.upsertPolicy`, `automation.metrics` | `promote_to_scenario` does not activate and does not advance `current_revision`. It creates or updates server-owned validated handles or a server-stored save request. `request_save` creates a `candidate`; only the separate `activate_revision` operation can advance `current_revision`, after eligibility, materialization, policy, required approval, and CAS checks. Initial creation is the sole explicit exception when the initial eligible revision is created as `current`. `start_scenario_run` must receive an explicit promoted `revision_id` and verified `content_hash`, never a candidate or an implicit latest/current target. @@ -231,13 +237,13 @@ The following snake_case names are the canonical MCP names for the complete auth ### AgentAuthoringWorkspace MCP operations -The MCP catalog MUST expose the following target contract for persistent co-authoring: `create_authoring_session`, `propose_test_plan`, `start_exploration`, `get_exploration_result`, `propose_graph_revision`, `get_graph_diff`, and `promote_to_scenario`. Names MAY be versioned during implementation, but the operation semantics and ownership boundary are normative. +The MCP catalog MUST expose `bootstrap_authoring_scenario` for initial creation and the following target contract for persistent co-authoring of an existing revision: `create_authoring_session`, `propose_test_plan`, `start_exploration`, `get_exploration_result`, `propose_graph_revision`, `get_graph_diff`, and `promote_to_scenario`. Names MAY be versioned during implementation, but the operation semantics and ownership boundary are normative. All mutable workspace, proposal, exploration, artifact, review and promotion state is server-owned. Mutating operations require authenticated principal/delegation, idempotency key and expected workspace CAS version; replays return the original result and changed requests or stale versions return typed 409 without partial mutation. Read operations enforce object ACL and return bounded refs/digests for large traces/screenshots. `start_exploration` uses only the isolated sandbox contract: allowlisted origins/APIs/actions, no shell/credential/filesystem escape, bounded time/size/network, cancellation, operation receipts, artifact ownership and no production side effects. The MCP server does not generate arbitrary Playwright code; it exposes reviewed templates/actions and consumes sandbox traces/candidates. Raw code, URLs, cookies, secrets, paths and caller digests are rejected as authority. -The operation chain is `session -> plan -> exploration -> typed proposal -> 038 compile/validate -> user-reviewed diff -> 042 save/promotion -> immutable revision`. `promote_to_scenario` cannot skip user review or required approval. 044 accepts only the resulting promoted revision. Code-backed production execution is a separate future, unimplemented contract. +The initial chain is `inspect -> compile/validate -> draft-pack -> bootstrap_authoring_scenario -> immutable current revision`. The existing-scenario chain is `session -> plan -> exploration -> typed proposal -> 038 compile/validate -> user-reviewed diff -> 042 save/promotion -> immutable revision`. An unbound workspace is not a creation path and cannot propose or save a graph. `promote_to_scenario` cannot skip user review or required approval. 044 accepts only the resulting promoted revision. Code-backed production execution is a separate future, unimplemented contract. The following table is the single cross-spec stage contract. A handle is an opaque server-issued reference; a digest is computed and verified by the owner named in @@ -251,6 +257,7 @@ cannot establish authority with a graph, caller-computed digest, path, or file. | validate | `CompiledScenarioHandle` or server graph | 038 `ScenarioGraph.Validator` | `ValidationResultHandle` | server validation-result digest bound to compiled hash | immutable server validation result | invalid/blocking findings produce no draft, revision, gate, or run | `Test.Scenario.Validator`, `Test.Scenario.Validator.Edge` | | resolve | server compiled handle + typed resolution + expected base | 038 resolver; 042 owns revision CAS when persisted | new `CompiledScenarioHandle` | new server `content_hash`, parent hash link | immutable server compile result; no in-place graph edit | stale base is `409 STALE_REVISION`; no partial graph or revision mutation | `Test.Scenario.Resolver`, `Test.Scenario.Resolver.Edge` | | draft-pack | valid compiled/validation handles + registered templates | 038 `ScenarioGraph.PackCompiler` | `DraftPackHandle` | server `draft_pack_digest` over rendered manifest/bytes | server draft registry, `save_eligible` or `preview_only` | unresolved/error/unsafe input is `preview_only`; no registry revision or launch side effect | `Test.Scenario.Pack`, `Test.Scenario.Pack.Security` | +| initial bootstrap | InitialScenarioIntent + valid compiled/draft-pack handles + idempotency key | 042 `ScenarioRegistry.CreateInitial` | ScenarioRegistryEntry + initial current ScenarioRevision + bound workspace | server-verified content hash and draft digest | PostgreSQL registry/revision/workspace + outbox | invalid, stale, unauthorized or replay-conflicting input creates no partial row; no synthetic base revision | `test_mcp_initial_scenario_e2e` | | request-save | compiled/draft handles + expected base + idempotency key | 042 registry transaction | `ScenarioRevision` (`candidate`, or initial `current`) | server-verified graph/content hash and draft digest | PostgreSQL revision + outbox; materialization async | CAS/idempotency failure is atomic; no row/outbox on rejection; save never activates | `test_scenario_registry`, `test_revisions` | | run preflight | selected `ScenarioRevision` + typed bindings + server target snapshot | 044 `RunPreflight` | `RunPreflightHandle` | server preflight digest over revision/target/bindings/policy | durable preflight record attached to launch request | missing/invalid context, selector, baseline, policy, or revision mismatch blocks before dispatch/I/O | `test_scenario_runner`, `test_scenario_automation_api` | | runner-plan | eligible preflight + immutable revision | 044 `RunnerPlan.Derive` | `RunnerPlanHandle` | server descriptor/plan digest | persisted on `ScenarioRun`; git `runner.plan.json` is reference only | altered/unknown descriptor rejects before lease, execution, or provider I/O | `test_scenario_runner_plan`, `test_scenario_dispatch` | diff --git a/specs/050-mcp-interface/tasks.md b/specs/050-mcp-interface/tasks.md index 3163313e0..8a1bfb749 100644 --- a/specs/050-mcp-interface/tasks.md +++ b/specs/050-mcp-interface/tasks.md @@ -41,6 +41,13 @@ - [x] T027 Authoring sandbox contract tests: isolated runtime, origin/API/action allowlists, no shell/credential/filesystem escape, limits, cancellation, receipts, artifact ownership and zero production side effects; retain exploratory traces/screenshots/diagnostics as bounded refs. - [x] T028 Authoring promotion E2E: sandbox output -> typed proposal -> deterministic 038 compile/validate -> user diff review -> 042 handle-based save -> immutable revision; reject raw code/URLs/cookies/secrets/paths/caller digests and keep code-backed production execution unimplemented. Доказательство: `pytest tests/test_mcp_authoring_promotion_e2e.py -q` → `8 passed`: полный прогон через `tools/call` — `start_exploration` теперь ставит `queued` при зарегистрированном раннере (wiring `provider_available=get_registered_runner() is not None`; регистрация `default_runner`+deployment context в `bootstrap_live_execution_composition`) → реальный `execute_scheduled_exploration_dispatch` из потокового контекста планировщика → `exploration_passed` с observations/proposed_graph/evidence_ref (`draft:exploration-*`) при [EXT:Browser]-дабле; `get_exploration_result` остаётся ограниченной проекцией без утечки наблюдений; значение `observed_dashboard_title` в сохранённой ревизии выводится только из наблюдения; `propose→promote→diff→request_save→activate` завершается `current`-ревизией без продвижения до отдельного CAS-активации. Негативные ветки: typed ops с SQL/`../`/`\\`/`drop` отклоняются до предложения и CAS; exploration-spec с code-токенами и незарегистрированными действиями не персистируется; `GraphRevisionInput`/`PromoteScenarioInput`/`RequestSaveInput`/`ActivateRevisionInput`/`ExplorationInput` структурно отвергают `digest`/`content_hash`. Дополнительно: диспетчерский soak (`test_mcp_ops_parity.py`) — 3 цикла поллера, каждое одобренное действие диспетчеризуется ровно один раз (`14 passed`). Полный срез: `83 passed` (8 файлов MCP-вертикали); полный backend suite **11182 passed**. +## Phase 2b — Initial scenario and automation parity + +- [ ] T029 Implement `ScenarioRegistry.CreateInitial` and `bootstrap_authoring_scenario`; prove a fresh external MCP client creates a first registry scenario without a seeded base revision. +- [ ] T029a Add typed InitialScenarioIntent/TestPackProfile validation and server-owned metric/filter/selector/baseline bindings; unresolved requirements must be `preview_only`, never guessed. +- [ ] T029b Expose 046 schedule, trigger-rule, policy and automation-metrics management through curated MCP tools with REST-equivalent RBAC, idempotency and PROD gate behavior. +- [ ] T029c Add fresh-DB MCP E2E for bootstrap → visible registry entry → revision activation → manual run, plus scheduler eligibility/PROD-gate integration evidence. + ## Phase 3 — Frontend decommission (flag-driven) - [x] T030 HandoffSurface: страница-инструкция + копируемый промпт с контекстом дашборда; кнопка «Создать сценарий тестирования» переключается на handoff. diff --git a/specs/WORKSTATE-043-047.md b/specs/WORKSTATE-043-047.md index cbd1cf357..66198b16e 100644 --- a/specs/WORKSTATE-043-047.md +++ b/specs/WORKSTATE-043-047.md @@ -1892,3 +1892,192 @@ frontend 3435/0 @ round 4 — both predate only the concurrent logging migration Статус: **не реализовано** — аудит read-only по запросу; к имплементации готов минимум Fix 1+2+4 (устраняют оба CRITICAL + SSOT-нарушение) с vitest/svelte-check/eslint-гейтами. + +## Checkpoint — 2026-09-04 (UX-audit remediation IMPLEMENTED — Fix 1+2+3+4 + registry hub) + +Implemented the actionable minimum of the read-only UX audit above (Fix 1+2+4), plus Fix 3 +(honest entries) and the scenario-registry hub the audit's Fix 2 "Сценарии" nav item implies. +Gates run per AGENTS.md frontend checks (`npm run test` / `npm run lint` / `npm run build`); +the project has no `svelte-check` script, so the "svelte-check gate" is covered by `vite build`. + +### Fix 4 — ROUTES SSOT for dashboard-testing / load-testing +- `src/lib/routes.ts`: added `ROUTES.dashboardTesting.{scenarios, scenarioEdit, scenarioAnalytics, + runDetail, runs, analytics, analyticsCase, automation}` + `ROUTES.loadTesting.detail`; every + builder maps to a real route file (registry index created this round). @RATIONALE records that + the integrity test now scans these trees. +- Converted ALL hardcoded `resolve("/dashboard-testing/...")` SSOT bypasses to ROUTES builders in + 7 pages (runs ×3, automation, analytics ×2, analytics case, scenario edit/analytics/run-detail) + + DashboardHeader load-testing href + DashboardHeader/agent hrefs now `ROUTES.agent(...)`. +- Hardened `routes-link-integrity.test.ts`: `/dashboard-testing` + `/load-testing` added to the + watched prefixes AND a `resolve("/dashboard-testing|/load-testing...")` bypass detector (the + audit MEDIUM #5 — these trees were previously uncovered). `routes.test.ts` +13 builder pins. +- Removed a now-dead `$app/paths` vi.mock in run.ux.test.ts orphaned by the conversion. + +### Scenario registry hub (NEW — makes the "Сценарии" nav item real; fixes 4 dead back-links) +- `src/routes/dashboard-testing/scenarios/+page.svelte`: searchable/filterable registry list over + the previously **unused** `ScenarioRegistryModel` (042 list/read only — never starts a run/agent); + rows link via ROUTES to edit / analytics / last-run. Previously `/dashboard-testing/scenarios` + was a DEAD route that four "← Сценарии" back-links pointed at. i18n `dashboard_testing.registry_*` + ru/en. UX test `scenarios_index.ux.test.ts` (4): rows+SSOT links, no-run-history, empty, error+retry. + +### Fix 2 — approval loop reachable from navigation (CRITICAL 2) +- `sidebarNavigation.ts`: new `dashboard_testing` category in the Operations section (no new section + id → the existing exact-section/categories tests stay green). Per-subitem RBAC mirrors the exact + backend `has_permission` gates: Сценарии→`dashboard:testing READ`, Запуски→`scenario RUN`, + Аналитика→`scenario:result VIEW`, Автоматизация→`scenario:automation TRIGGER`; category itself + unpermissioned (visibility derives from subitems → hidden entirely when none pass). +- `stores/scenarioRuns.svelte.ts` (NEW): waiting-for-me count store (server-authoritative total via + `/scenario-runs?waiting_for_me=true&page_size=1`; fail-closed 401/403 disable; inflight dedup; + mirrors HealthStore). `test_scenarioRuns.ts` (9): state/refresh/dedup/auth-disable/retry/subscribe. +- `Sidebar.svelte`: warning-token badge on the `dashboard_testing` category (count expanded / dot + collapsed) + 60s poll gated on `scenario:RUN` — turns the approval loop into a discoverable signal + (directly addresses "продукт висит в ожидании ненаходимого действия"). Metadata BINDS_TO/@UX_FEEDBACK updated. +- `nav.json` ru/en keys; `category.testing` tailwind token. `sidebarNavigation.test.ts` +4 RBAC tests. + +### Fix 1 — HandoffSurface actionable (CRITICAL 1) +- `HandoffSurface.svelte`: renders the REAL MCP endpoint from `page.url.origin` (`{origin}/mcp`) as a + copyable block + "Copy URL", the OAuth discovery URL (`{origin}/.well-known/oauth-protected-resource/mcp`, + verified against `backend/src/api/mcp_oauth.py` + `app.py` `/mcp` mount), a 3-step onboarding and the + docs/INSTALL.md «MCP клиент» pointer — closing "«Подключите MCP-клиент» without how/where". Offline + invariant preserved (synchronous origin/props/i18n derivation, no network). Context-parameterized + prompt (Story 5 AC2) unchanged. i18n `assistant.handoff_*` ru/en; context test +3 (endpoint, + discovery, onboarding+copy controls). **HandoffSurface lints 0-warning.** + +### Fix 3 — honest entries (HIGH #3 bait-and-switch) +- TopNavbar assistant button + DashboardHeader "AI" button relabeled to «MCP-ассистент» / «MCP» with + tooltip «Инструкция по подключению AI-ассистента (MCP)» — no longer promises in-app chat. `assistant.mcp_entry_*` ru/en. + +### Verification evidence (this round) +- **Full frontend suite: 3486 passed, 0 failed (200 files)** (was 3435; +51 = new builder pins, + sidebar RBAC, store, registry index, handoff endpoint/onboarding). +- **eslint: 0 errors / 354 warnings** (baseline 340). The +14 are ALL the accepted + `svelte/no-navigation-without-resolve` class: the codebase's established ROUTES convention is bare + `href={ROUTES.x()}`/`goto(ROUTES.x())` (98 such warnings pre-exist; `resolve(ROUTES())` appears + **nowhere**), so SSOT-compliant navigation deliberately carries the same accepted warning. No new + error/a11y/unused-var warnings introduced; Sidebar's 3 each-key warnings are pre-existing. +- **Production build (adapter-static): green.** GRACE-Poly anchors balanced in every touched file; + store MCL `log(src, marker, intent, payload, error)` mirrors HealthStore (src-first frontend facade). +- Recorded decision: bare `ROUTES.x()` chosen over `resolve(ROUTES.x())` for consistency with the + dominant convention (base path empty under adapter-static → `resolve()` is identity anyway). + +### Not done (optional / out of minimum scope) +- Fix 5 (MCP status/admin page — endpoint, discovery, per-role tool list): audit-optional and larger; deferred. +- Broader product-GO gates from prior checkpoints unchanged and NOT touched by this frontend UX round: + semantic index rebuild (Axiom), full backend suite re-run on the landed logging-SSOT migration, + and browser E2E on a live stand (would need the backend+frontend stack up). Product status per the + round-1 closure review remains pending formal re-sign-off. + +## Checkpoint — 2026-09-05 (UX-audit "остатки" — Fix 5 admin MCP governance + Fix 2 polish, UI/UX discussed first) + +Per the operator's request the remaining UI/UX was discussed and decided BEFORE implementing. Decisions: +Fix 5 = **admin governance (all 47 tools × roles)** mounted under `/admin/*`; polish = **badge→waiting +view** + **registry extra filters & pagination**. (First-visit onboarding was declined.) + +### Fix 5 — admin MCP governance surface (audit finding #4: "настроек/статуса MCP в UI нет вообще") +- Grounding first: MCP's only REST surface is OAuth (`/oauth/*`, `/.well-known/*`); the role-dependent + tool catalog is exposed **only over the MCP protocol** (`tools/list`), and `/api/ready` carries 044 + provider readiness, not the catalog. So a governance view needs a small NEW backend projection. +- Backend `backend/src/api/routes/admin_mcp.py` (new module, keeps `admin.py` under INV_7): read-only + `GET /api/admin/mcp/catalog`, gated `has_permission("admin:roles","READ")` (same gate as the role/ + permission inventory). Returns catalog_version (`MCP_CATALOG_VERSION`), endpoint/discovery paths, + the full frozen catalog (name/risk_level/requires_approval/service_allowed/deprecated/required + permission), a per-role visible-tool matrix, and a read-only DCR client list (`OAuthClient`, scopes/ + redirect_uris parsed; **never** secret/secret_hash). Registered in `app.py` (413 routes; import verified). +- The per-role visibility helper `_visible_tool_names` mirrors `RbacFastMCP._can_use_tool`'s human + branch exactly (permission None → visible; `start_scenario_run` → scenario RUN or RUN_PROD; else + exact role resource/action match; admin bypass). `tests/api/test_admin_mcp_catalog.py` (8) pins it to + the SAME exact admin/viewer/analyst subsets SC-004 pins for the protocol → UI cannot drift from tools/list. +- Frontend: `api.getMcpCatalog`; `models/AdminMcpCatalogModel.svelte.ts` (read-only, last-projection-on- + error); `routes/admin/mcp/+page.svelte` (ProtectedRoute admin:roles; server card w/ absolute endpoint+ + discovery, full tool table, expandable role×visibility matrix, DCR client list); `ROUTES.admin.mcp()`; + sidebar admin subitem «MCP» (admin:roles READ) + admin hub card; i18n `admin.mcp.*` + `nav.admin_mcp*` ru/en. +- **Real defect found & fixed by the page test:** the load `$effect` used `!loaded && !loading`, which + re-fires after a FAILED load (loading toggles, loaded stays false) → an auto-retry loop hammering the + endpoint. Switched to a `started` guard (load once + manual Retry), matching the registry hub. This is + the same latent pattern some sibling pages still carry (runs/analytics use rows/loaded guards). + +### Fix 2 polish — badge → "ожидают меня" view; registry filters + pagination +- `ROUTES.dashboardTesting.runs(waitingForMe?)` → `?waiting_for_me=true`; run center now READS that param + on entry (`page.url.searchParams`) and opens directly on `WaitingForMeView`; the Sidebar waiting badge + (expanded count) is now a button navigating to `runs(true)` (`stopPropagation` so it doesn't toggle the + category). The collapsed dot stays an indicator. Turns the passive count into a one-click approval entry. +- Scenario registry hub gained owner / tag / dashboard_id filters + server-side pagination (PageSize 20, + prev/next, page X/Y) over the existing `ScenarioRegistryModel.loadList` query; filter change resets to + page 1 (@INVARIANT). i18n `dashboard_testing.registry_*` ru/en extended. + +### Verification evidence (this round) +- Frontend: **full suite 3498 passed, 0 failed (204 files)** (was 3486); eslint **0 errors / 354 warnings** + (UNCHANGED — Fix 5 added no nav-href warnings; admin/mcp page has no internal links); build green + (adapter-static); anchors balanced in every new/edited file; all touched i18n JSON parses; `git diff --check` clean. +- Backend: admin/mcp + admin + mcp-rbac-visibility + catalog-version slice **42 passed**; MCP slice + **55 passed**; scoped dashboard-testing OpenAPI **25 passed** (unaffected by the new /api/admin route); + ruff + `compileall` clean; `app.py` imports with `/api/admin/mcp/catalog` registered. Full backend suite + NOT re-run this round (change is one isolated additive endpoint + registration; scoped slices + app + import are proportionate) — the prior round-5 number (11243) stands pending the logging-SSOT re-run. + +### Remaining after this round +- Fix 5 shipped **read-only** governance. DCR client MANAGEMENT (revoke/rotate) and automated key-rotation + expiry remain open (separate features the audit listed); the view exposes clients but performs no mutation. +- Fix 5 was the last audit UI/UX item; all five audit fixes (1–5) are now implemented. Deferred product + decisions (M-03 self-approval, service-branch catalog permissions, adapter idempotency, multi-binding + exploration context, TTL/expiry) and the broader GO gates (semantic rebuild, full backend suite on the + landed logging migration, browser E2E on a live stand, closure-gate re-sign-off) are unchanged. + +## Checkpoint — 2026-09-05 (orthogonal UI/UX review + i18n remediation) + +Per operator request an independent UI/UX pass was run on the newly delivered surfaces, with i18n +completeness as an explicit gate. Findings (orthogonal, from a fresh pair of eyes): + +- **i18n debt (primary):** the dashboard-testing feature area still carried hardcoded Russian UI + strings — `runs/+page.svelte` (~25 strings), `WaitingForMeView.svelte` (~12) — violating the + "no hardcoded UI strings" invariant. My two new pages additionally used English `|| "…"` fallback + literals and rendered raw enum tokens (risk_level, client_type, lifecycle_status, health) untranslated. +- **Bug:** scenario registry `dashboard_id` filter sent `NaN` in the query for non-numeric input. +- **UX clarity:** admin/mcp "Сервис" column (service_allowed yes/no) was ambiguous — what "yes" grants + is not obvious; added a clarifying tooltip. +- **Minor:** admin/mcp page lacked a document ``. + +Remediated: +- `runs/+page.svelte` + `WaitingForMeView.svelte` fully migrated to `$t` (`dashboard_testing.runs_*`, + `waiting_*`); all hardcoded RU strings removed (only a `@BRIEF` metadata comment references the label). +- `scenarios/+page.svelte` + `admin/mcp/+page.svelte`: fallback literals removed (i18n keys are the only + source), lifecycle/health/risk/client_type enums translated (`ls_*`, `health_*`, `risk_*`, `client_*`) + with raw-token fallback for unknown values (drift-safe); `dashboard_id` NaN guard added; admin/mcp + `<title>` added; service column disambiguated via `col_service_hint`. +- i18n locales extended ru/en: `dashboard-testing.json` (+runs/waiting/ls/health ≈45 keys), + `admin.json` `mcp.*` (+risk/client/service-hint keys); nav/assistant unchanged this round. +- Test fixture for the admin/mcp page broadened to the full `admin.mcp` key set. + +Verification: frontend **full suite 3498 passed / 0 failed (204 files)**; eslint **0 errors / 354 warnings** +(unchanged — no new nav-href); build green; no residual Cyrillic in the four touched templates; all four +edited locale JSONs parse. `WaitingForMeView.test.ts` (real-i18n, ru labels) still green. + +## Checkpoint — 2026-09-05 (i18n sweep COMPLETE — analytics/editor/automation/run surfaces) + +The previously-documented remaining i18n debt is now cleared: the analytics/automation pages, +scenario detail pages (`[id]/edit`, `[id]/analytics`, `[id]/runs/[runId]`) and the entire scenario +component trees were migrated off hardcoded Russian strings to `$t` (`dashboard_testing.*`): +- scenario-analytics: CaseWorkspace, QueueList, TrendsChart, AgentActionTimeline, RecurringFailuresList, + HealthCard + analytics/queue + case routes. +- scenario-run: HumanCheckpointPanel, RunTimeline, RunComparison, RunHistoryList, ScenarioResultView, + RunConfigurationPanel + run-detail monitor route. +- scenario-editor: ConstrainedAssertionEditor, VisualDagCanvas, AgentActionPanel, EditRevisionDiff + + scenario edit route. +- scenario-automation: AutomationPanel, ScheduleForm + automation route. +- Locales extended (ru/en) with ~150 keys. Policy: ru values = the current rendered text (some terms + stay English where they currently ship untranslated, e.g. "attention item(s)", "Investigate with + agent", "occurrence(s)", "group(s)") so real-i18n tests stay green; wiring is complete and the + locale entries are now the single place to localize later. +- Fixed a stale route test `case.ux.test.ts` ("Записать disposition" → current "Закрыть кейс" + + resolved/verification_evidence CAS body); it previously asserted a pre-refactor disposition flow. + +Gates: frontend **3494 passed / 4 failed (204 files)**; the 4 failures are PRE-EXISTING (verified in +isolation, none touched by this workstream): +1. `routes-link-integrity` — `src/routes/oauth-consent/+page.svelte:44 goto('/login')` raw SSOT bypass + (untracked file, not part of this workstream). +2-3. `InvestigationModels.test.ts` (2) — stale vs the prior-round `InvestigationCaseModel.dispose` + signature change (`rationale.trim is not a function`, CAS version 1 vs 2). +4. `settings_page.ux.test.ts` (1) — pre-existing numeric-range save guard, unrelated to dashboard-testing. +Lint **0 errors / 358 warnings** (+4 tolerated `no-navigation-without-resolve`); build green; no residual +hardcoded Russian outside a single `@BRIEF` comment. The 4 pre-existing failures are out of i18n scope +and left for a separate cleanup. diff --git a/specs/production-043-047-2026-09-05-plan.md b/specs/production-043-047-2026-09-05-plan.md new file mode 100644 index 000000000..64369f6be --- /dev/null +++ b/specs/production-043-047-2026-09-05-plan.md @@ -0,0 +1,50 @@ +# Завершение 043–047 — 2026-09-05 + +Запрос: завершить dashboard testing UI/UX по спекам; MCP должен быть доступен при Docker deployment, а frontend инструкции должны отражать реальный способ подключения. + +## Границы и решения + +- Сохранить исходное незакоммиченное дерево; продолжить с последних checkpoints WORKSTATE, не считать ранние исторические gaps текущими без проверки. +- Implement: Docker reverse proxy, MCP/OAuth/discovery, публичные URL, deployment configuration и MCP onboarding/admin hints; релевантные тесты. +- Implement UI: оставшиеся dashboard testing экраны/компоненты, RU/EN, loading/error/empty/retry, доступность и реальные пути действий. +- Verify: независимое соответствие актуальным спекам, текущие suites и browser evidence; production-файлы не редактирует. +- После реализации: согласовать исправления с независимыми проверками, актуализировать semantic navigation и WORKSTATE доказательствами текущего дерева. +- Не заявлять production ready на основе старых счётчиков тестов или одного наличия кода. Непроверенные внешние зависимости указывать явно. + +## Найдено + +- Docker nginx проксировал только API/WS: MCP, OAuth и discovery попадали в SPA. Исправление в работе у Implement. +- Последний WORKSTATE фиксирует оставшиеся hardcoded RU строки в редакторе, деталях запуска, аналитике, автоматизации и компонентных деревьях. + +## Доказательства + +### Выполнено в текущем продолжении + +- Docker nginx (HTTP и TLS) проксирует `/mcp`, `/oauth/*` и `/.well-known/*` в backend, выключает + buffering для Streamable HTTP и сохраняет внешний authority через `Host: $http_host`. +- Compose передаёт MCP allowlists, доверие к внутреннему proxy и закрывает direct backend port на + loopback. `SERVICE_JWT` теперь также обязателен для enterprise compose. +- `scripts/mcp_proxy_smoke.py` проверен с реальными временными `nginx:1.27-alpine` и + `python:3.12-alpine`: discovery, OAuth, `/mcp`, внешний порт, Bearer и MCP session header прошли; + созданные контейнеры и сеть удалены скриптом. +- UI: endpoint и discovery видны на handoff, sidebar ведёт в сценарии/запуски/аналитику/автоматизацию, + run detail восстанавливает состояние и умеет отменять запуск, editor подключает constrained assertion + и typed dependency WorkingDraft/save flow, case closure использует ровно `resolved|accepted` контракт. + +### Текущее доказательство + +- focused frontend Vitest: 28 passed (handoff, MCP admin, scenario registry/sidebar, case workspace); + плюс 13 passed (case/editor/run-detail); production `npm run build` и `npm run lint -- --quiet` passed. +- backend: `ruff check` touched MCP/API modules and `compileall` passed; focused MCP/analytics run was + started, but its final aggregate output was unavailable after the prior worker stopped, so this note + does not report it as suite-close evidence. +- Browser CDP/E2E remains unavailable (no Chrome on port 9222). Local `/api/ready` passed; it reports + screenshot/browser providers unregistered because no live deployment binding is configured. + +### Remaining release gate + +- Run browser E2E against an authenticated Docker deployment with a real configured live-provider binding; + test MCP discovery → OAuth client → `tools/list` over the deployed public origin. +- Run full backend/frontend suites on the final combined dirty tree, then update spec task checkmarks only + with those command results. Existing per-user OAuth authorize requires a client-supplied authenticated + session; the UI wording deliberately no longer promises a standalone consent screen.