diff --git a/backend/tests/core/test_project_features_manifest.py b/backend/tests/core/test_project_features_manifest.py new file mode 100644 index 000000000..aba654d81 --- /dev/null +++ b/backend/tests/core/test_project_features_manifest.py @@ -0,0 +1,52 @@ +# #region Test.Core.ProjectFeaturesManifest [C:2] [TYPE Module] [SEMANTICS test,features,manifest,guard] +# @BRIEF Guard — every nav feature-id from the frontend projectSections.json manifest must exist +# as a field on FeaturesConfig, otherwise the settings "Разделы проекта" toggle would +# silently fail to persist (FeaturesConfig(**patch) drops unknown keys). +# @RELATION BINDS_TO -> [Core.ConfigModels.FeaturesConfig] +# @RELATION BINDS_TO -> [EXT:frontend:SidebarNavigation] +# @RATIONALE The settings features tab derives its toggles from the sidebar nav registry +# (frontend/src/lib/components/layout/sidebarNavigation.ts). The shared JSON manifest +# is the cross-language contract: the frontend guard test pins nav ids to it, this +# test pins backend model fields to it. +import json +from pathlib import Path + +from src.core.config_models import FeaturesConfig + +MANIFEST_PATH = ( + Path(__file__).resolve().parents[3] + / "frontend" + / "src" + / "lib" + / "components" + / "layout" + / "projectSections.json" +) + + +# #region Test.Core.ProjectFeaturesManifest.Helpers [TYPE Function] +def _nav_feature_ids() -> list[str]: + with MANIFEST_PATH.open(encoding="utf-8") as fh: + manifest = json.load(fh) + return list(manifest["navFeatures"]) +# #endregion Test.Core.ProjectFeaturesManifest.Helpers + + +# #region Test.Core.ProjectFeaturesManifest.TestProjectFeaturesManifest [C:1] [TYPE Class] +# @ingroup Test +class TestProjectFeaturesManifest: + def test_manifest_exists_and_lists_features(self) -> None: + assert MANIFEST_PATH.is_file(), f"Manifest missing: {MANIFEST_PATH}" + ids = _nav_feature_ids() + assert ids, "projectSections.json must list nav feature ids" + + def test_every_nav_feature_exists_on_features_config(self) -> None: + model_fields = set(FeaturesConfig.model_fields) + missing = [fid for fid in _nav_feature_ids() if fid not in model_fields] + assert not missing, ( + "Feature ids present in projectSections.json but missing from FeaturesConfig " + f"(a settings toggle would not persist): {missing}" + ) +# #endregion Test.Core.ProjectFeaturesManifest.TestProjectFeaturesManifest + +# #endregion Test.Core.ProjectFeaturesManifest diff --git a/frontend/src/lib/components/layout/Sidebar.svelte b/frontend/src/lib/components/layout/Sidebar.svelte index c9535c4c6..93d791594 100644 --- a/frontend/src/lib/components/layout/Sidebar.svelte +++ b/frontend/src/lib/components/layout/Sidebar.svelte @@ -4,6 +4,7 @@ + @@ -32,11 +33,16 @@ import { SvelteSet } from "svelte/reactivity"; import { onMount, untrack } from "svelte"; import { t } from "$lib/i18n/index.svelte.js"; import { auth } from "$lib/auth/store.svelte.js"; - import { buildSidebarSections } from "$lib/components/layout/sidebarNavigation.js"; - import { fetchApi } from "$lib/api.js"; - import { browser } from "$app/environment"; - import { ROUTES } from "$lib/routes"; - import Icon from "$lib/ui/Icon.svelte"; + import { buildSidebarSections } from "$lib/components/layout/sidebarNavigation.js"; + import { + getFeatures, + isFeatureEnabled, + isLoaded as featuresLoaded, + loadFeatures, + } from "$lib/stores/features.svelte.js"; + import { browser } from "$app/environment"; + import { ROUTES } from "$lib/routes"; + import Icon from "$lib/ui/Icon.svelte"; let _authState = $state({ user: null, token: null, isAuthenticated: false, loading: true }); onMount(() => { @@ -44,14 +50,11 @@ import { SvelteSet } from "svelte/reactivity"; return unsub; }); - let features = $state({}); - let cleanupInterval = null; - let sections = $derived( buildSidebarSections( t, _authState.user || null, - features, + getFeatures(), ), ); @@ -81,6 +84,17 @@ import { SvelteSet } from "svelte/reactivity"; return () => clearInterval(id); }); + // Poll dashboard health only while the health_monitor flag is enabled. The flags come from the + // reactive features store, so toggling the flag in Settings restarts/stops polling live — + // without the reload the old onMount fetch required. The refresh call itself is untracked: + // the effect must depend only on the flag, not on anything refresh() reads or writes. + $effect(() => { + if (!featuresLoaded() || !isFeatureEnabled("health_monitor")) return; + untrack(() => healthStore.refresh()); + const interval = setInterval(() => untrack(() => healthStore.refresh()), 5 * 60 * 1000); + return () => clearInterval(interval); + }); + function withExpandedCategory(categoryId) { expandedCategories.add(categoryId); } @@ -209,26 +223,7 @@ import { SvelteSet } from "svelte/reactivity"; }); onMount(() => { - fetchApi("/settings/features") - .then((res) => { - features = res; - if (res.health_monitor) { - healthStore.refresh(); - const interval = setInterval(() => healthStore.refresh(), 5 * 60 * 1000); - cleanupInterval = interval; - } - }) - .catch(() => { - features = {}; - healthStore.refresh().then(() => { - const interval = setInterval(() => healthStore.refresh(), 5 * 60 * 1000); - cleanupInterval = interval; - }).catch(() => {}); - }); - - return () => { - if (cleanupInterval) clearInterval(cleanupInterval); - }; + void loadFeatures(); }); diff --git a/frontend/src/lib/components/layout/__tests__/projectSections.test.ts b/frontend/src/lib/components/layout/__tests__/projectSections.test.ts new file mode 100644 index 000000000..c08340e7e --- /dev/null +++ b/frontend/src/lib/components/layout/__tests__/projectSections.test.ts @@ -0,0 +1,62 @@ +// #region Tests.ProjectSections.Guard [C:2] [TYPE Module] [SEMANTICS test, sidebar, features, manifest, guard] +// @SEMANTICS: tests, sidebar, features, manifest +// @BRIEF: Guard — nav feature-ids, the projectSections.json manifest, and what buildSidebarSections +// surfaces must stay in sync. Catches a raw requiredFeature string that bypassed the manifest +// and a manifest id that no nav node uses anymore. +// @LAYER Tests +// @RELATION DEPENDS_ON -> [EXT:frontend:SidebarNavigation] +// @RELATION BINDS_TO -> [Core.ConfigModels.FeaturesConfig] +// @TEST_INVARIANT: NavFeatureManifestSync -> VERIFIED_BY: nav_ids_match_manifest, admin_view_surfaces_manifest, every_node_has_context. + +import { describe, it, expect } from "vitest"; +import { buildSidebarSections, getTogglableFeatureNodes } from "../sidebarNavigation"; +import manifest from "../projectSections.json"; + +const adminUser = { roles: [{ name: "Admin", permissions: [] }] }; + +// #region Tests.ProjectSections.Guard.NavFeatureIdsFromBuiltSections [TYPE Function] +// @BRIEF: Collect feature ids surfaced by buildSidebarSections for an admin with all flags enabled. +function navFeatureIdsFromBuiltSections(): string[] { + const seen = new Set(); + for (const section of buildSidebarSections({ nav: {} }, adminUser, {})) { + for (const category of section.categories) { + if (category.requiredFeature) seen.add(category.requiredFeature); + for (const sub of category.subItems || []) { + if (sub.requiredFeature) seen.add(sub.requiredFeature); + } + } + } + return [...seen].sort(); +} +// #endregion Tests.ProjectSections.Guard.NavFeatureIdsFromBuiltSections + +describe("projectSections manifest guard", () => { + it("nav_ids_match_manifest: getTogglableFeatureNodes covers exactly the manifest ids", () => { + const fromRegistry = getTogglableFeatureNodes().map((node) => node.featureId).sort(); + expect(fromRegistry).toEqual([...manifest.navFeatures].sort()); + }); + + it("admin_view_surfaces_manifest: buildSidebarSections exposes every manifest flag", () => { + expect(navFeatureIdsFromBuiltSections()).toEqual([...manifest.navFeatures].sort()); + }); + + it("every_node_has_context: each togglable node carries section and category context", () => { + const nodes = getTogglableFeatureNodes(); + expect(nodes.length).toBeGreaterThan(0); + for (const node of nodes) { + expect(node.featureId, "featureId must be set").toBeTruthy(); + expect(node.labelKey, `labelKey missing for ${node.featureId}`).toBeTruthy(); + expect(node.sectionId, `sectionId missing for ${node.featureId}`).toBeTruthy(); + expect(node.sectionLabelKey, `sectionLabelKey missing for ${node.featureId}`).toBeTruthy(); + expect(node.categoryId, `categoryId missing for ${node.featureId}`).toBeTruthy(); + expect(node.categoryLabelKey, `categoryLabelKey missing for ${node.featureId}`).toBeTruthy(); + } + }); + + it("groups follow nav order: resources → operations → system", () => { + const nodes = getTogglableFeatureNodes(); + const sectionOrder = [...new Set(nodes.map((node) => node.sectionId))]; + expect(sectionOrder).toEqual(["resources", "operations", "system"]); + }); +}); +// #endregion Tests.ProjectSections.Guard diff --git a/frontend/src/lib/components/layout/projectSections.json b/frontend/src/lib/components/layout/projectSections.json new file mode 100644 index 000000000..e041ecd27 --- /dev/null +++ b/frontend/src/lib/components/layout/projectSections.json @@ -0,0 +1,16 @@ +{ + "version": 1, + "navFeatures": [ + "health_monitor", + "translate", + "translate_dictionaries", + "migration", + "git_integration", + "backup", + "dataset_mapper", + "debug", + "storage_manager", + "maintenance_banner", + "llm_dashboard_validation" + ] +} diff --git a/frontend/src/lib/components/layout/sidebarNavigation.ts b/frontend/src/lib/components/layout/sidebarNavigation.ts index fe74985dd..ee6443e09 100644 --- a/frontend/src/lib/components/layout/sidebarNavigation.ts +++ b/frontend/src/lib/components/layout/sidebarNavigation.ts @@ -12,9 +12,49 @@ // @LAYER UI // @RELATION DEPENDS_ON -> [Auth.Permissions.PermissionsModuleModule] // @RELATION BINDS_TO -> [Layout.Sidebar] +// @RELATION BINDS_TO -> [Settings.FeaturesSettings] // @INVARIANT: Admin role can access all categories and subitems through permission utility. +// @INVARIANT: Every requiredFeature in SIDEBAR_SECTIONS is listed in projectSections.json and has a +// matching FeaturesConfig field on the backend (enforced by Tests.ProjectSections.Guard +// and the backend manifest guard test). The settings "Разделы проекта" tab derives its +// toggles from the same registry, so a new gated route appears there automatically. import { hasPermission } from "$lib/auth/permissions.js"; +import projectSections from "./projectSections.json"; + +/** + * Feature ids that gate sidebar routes. The id list lives in projectSections.json and is the + * single source shared with the backend manifest guard (FeaturesConfig field check). + */ +export type NavFeatureId = (typeof projectSections.navFeatures)[number]; + +interface NavItemDef { + labelKey: string; + labelFallback?: string; + path: string; + requiredPermission?: string; + requiredAction?: string; + requiredFeature?: NavFeatureId; +} + +interface CategoryDef { + id: string; + labelKey: string; + labelFallback?: string; + icon: string; + tone: string; + path: string; + requiredPermission?: string; + requiredAction?: string; + requiredFeature?: NavFeatureId; + subItems: NavItemDef[]; +} + +interface SectionDef { + id: string; + labelKey: string; + categories: CategoryDef[]; +} interface NavItem { label: string; @@ -56,6 +96,186 @@ interface User { roles?: UserRole[]; } +// #region Layout.SidebarNavigation.SidebarSectionsRegistry [TYPE Data] +// @BRIEF Static navigation registry — single source for the sidebar structure and the settings +// feature toggles (getTogglableFeatureNodes). Labels are stored as i18n keys and resolved +// at build time so the registry itself stays locale-independent. +const SIDEBAR_SECTIONS: SectionDef[] = [ + // ── Section 1: Resources ───────────────────────────────── + { + id: "resources", + labelKey: "section_resources", + categories: [ + { + id: "dashboards", + labelKey: "dashboards", + icon: "dashboard", + tone: "from-category-dashboards-from to-category-dashboards-to text-category-dashboards-text ring-category-dashboards-ring", + path: "/dashboards", + requiredPermission: "plugin:migration", + requiredAction: "READ", + subItems: [ + { labelKey: "overview", path: "/dashboards", requiredPermission: "plugin:migration", requiredAction: "READ" }, + { labelKey: "health_center", path: "/dashboards/health", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "health_monitor" }, + ], + }, + { + id: "datasets", + labelKey: "datasets", + icon: "database", + tone: "from-category-datasets-from to-category-datasets-to text-category-datasets-text ring-category-datasets-ring", + path: "/datasets", + requiredPermission: "plugin:migration", + requiredAction: "READ", + subItems: [ + { labelKey: "all_datasets", path: "/datasets", requiredPermission: "plugin:migration", requiredAction: "READ" }, + ], + }, + { + id: "migration", + labelKey: "migration", + icon: "layers", + tone: "from-category-migration-from to-category-migration-to text-category-migration-text ring-category-migration-ring", + path: "/migration", + requiredPermission: "plugin:migration", + requiredAction: "READ", + requiredFeature: "migration", + subItems: [ + { labelKey: "migration_overview", labelFallback: "Overview", path: "/migration", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" }, + { labelKey: "migration_mappings", labelFallback: "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" }, + ], + }, + ], + }, + + // ── Section 2: Operations ────────────────────────────────── + { + id: "operations", + labelKey: "section_operations", + categories: [ + { + id: "git", + labelKey: "git", + icon: "activity", + tone: "from-category-git-from to-category-git-to text-category-git-text ring-category-git-ring", + path: "/git", + requiredFeature: "git_integration", + subItems: [ + { labelKey: "git_repo_status", labelFallback: "Repository Status", path: "/git", requiredFeature: "git_integration" }, + ], + }, + { + id: "translation", + labelKey: "translation", + icon: "translate", + tone: "from-category-translation-from to-category-translation-to text-category-translation-text ring-category-translation-ring", + path: "/translate", + requiredPermission: "translate.job", + requiredAction: "VIEW", + requiredFeature: "translate", + subItems: [ + { labelKey: "translation_jobs", path: "/translate", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" }, + { labelKey: "translation_dictionaries", path: "/translate/dictionaries", requiredPermission: "translate.dictionary", requiredAction: "VIEW", requiredFeature: "translate_dictionaries" }, + { labelKey: "translation_history", path: "/translate/history", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" }, + ], + }, + { + id: "validation", + labelKey: "validation", + icon: "activity", + tone: "from-category-validation-from to-category-validation-to text-category-validation-text ring-category-validation-ring", + path: "/validation-tasks", + requiredPermission: "validation.task", + requiredAction: "VIEW", + requiredFeature: "llm_dashboard_validation", + subItems: [ + { labelKey: "validation_tasks", path: "/validation-tasks", requiredPermission: "validation.task", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" }, + { labelKey: "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", + labelKey: "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: [ + { labelKey: "dt_scenarios", path: "/dashboard-testing/scenarios", requiredPermission: "dashboard:testing", requiredAction: "READ" }, + { labelKey: "dt_runs", path: "/dashboard-testing/runs", requiredPermission: "scenario", requiredAction: "RUN" }, + { labelKey: "dt_analytics", path: "/dashboard-testing/analytics", requiredPermission: "scenario:result", requiredAction: "VIEW" }, + { labelKey: "dt_automation", path: "/dashboard-testing/automation", requiredPermission: "scenario:automation", requiredAction: "TRIGGER" }, + ], + }, + { + id: "reports", + labelKey: "reports", + icon: "reports", + tone: "from-category-reports-from to-category-reports-to text-category-reports-text ring-category-reports-ring", + path: "/reports", + requiredPermission: "tasks", + requiredAction: "READ", + subItems: [ + { labelKey: "all_reports", labelFallback: "All Reports", path: "/reports", requiredPermission: "tasks", requiredAction: "READ" }, + ], + }, + ], + }, + + // ── Section 3: System ──────────────────────────────────── + { + id: "system", + labelKey: "section_system", + categories: [ + { + id: "tools", + labelKey: "tools", + icon: "list", + tone: "from-category-tools-from to-category-tools-to text-category-tools-text ring-category-tools-ring", + path: "/tools/mapper", + subItems: [ + { labelKey: "tools_mapper", path: "/tools/mapper", requiredFeature: "dataset_mapper" }, + { labelKey: "tools_debug", path: "/tools/debug", requiredFeature: "debug" }, + { labelKey: "tools_storage", path: "/tools/storage", requiredFeature: "storage_manager" }, + { labelKey: "tools_backups", path: "/tools/backups", requiredFeature: "backup" }, + ], + }, + { + id: "admin", + labelKey: "admin", + icon: "admin", + tone: "from-category-admin-from to-category-admin-to text-category-admin-text ring-category-admin-ring", + path: "/admin/users", + subItems: [ + { labelKey: "admin_users", path: "/admin/users", requiredPermission: "admin:users", requiredAction: "READ" }, + { labelKey: "admin_roles", path: "/admin/roles", requiredPermission: "admin:roles", requiredAction: "READ" }, + { labelKey: "admin_settings", path: "/admin/settings", requiredPermission: "admin:settings", requiredAction: "READ" }, + { labelKey: "admin_llm", path: "/admin/settings/llm", requiredPermission: "admin:settings", requiredAction: "READ" }, + { labelKey: "admin_mcp", path: "/admin/mcp", requiredPermission: "admin:roles", requiredAction: "READ" }, + ], + }, + { + id: "maintenance", + labelKey: "maintenance", + labelFallback: "Maintenance", + icon: "activity", + tone: "from-category-maintenance-from to-category-maintenance-to text-category-maintenance-text ring-category-maintenance-ring", + path: "/maintenance", + requiredPermission: "maintenance", + requiredAction: "READ", + requiredFeature: "maintenance_banner", + subItems: [ + { labelKey: "maintenance", labelFallback: "Maintenance", path: "/maintenance", requiredPermission: "maintenance", requiredAction: "READ", requiredFeature: "maintenance_banner" }, + ], + }, + ], + }, +]; +// #endregion Layout.SidebarNavigation.SidebarSectionsRegistry + // #region Layout.SidebarNavigation.IsItemAllowedFunction [TYPE Function] // @BRIEF: Check whether a single menu node can be shown for a given user. // @PRE: item can contain optional requiredPermission/requiredAction. @@ -77,186 +297,42 @@ function isFeatureEnabled(item: { requiredFeature?: string }, features: Record = {}): Section[] { - const nav = i18nState?.nav || {}; - - // ── Section 1: Resources ───────────────────────────────── - const resources: Section = { - id: "resources", - label: nav.section_resources, - categories: [ - { - id: "dashboards", - label: nav.dashboards, - icon: "dashboard", - tone: "from-category-dashboards-from to-category-dashboards-to text-category-dashboards-text ring-category-dashboards-ring", - path: "/dashboards", - requiredPermission: "plugin:migration", - requiredAction: "READ", - subItems: [ - { label: nav.overview, path: "/dashboards", requiredPermission: "plugin:migration", requiredAction: "READ" }, - { label: nav.health_center, path: "/dashboards/health", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "health_monitor" }, - ], - }, - { - id: "datasets", - label: nav.datasets, - icon: "database", - tone: "from-category-datasets-from to-category-datasets-to text-category-datasets-text ring-category-datasets-ring", - path: "/datasets", - requiredPermission: "plugin:migration", - requiredAction: "READ", - subItems: [ - { label: nav.all_datasets, path: "/datasets", requiredPermission: "plugin:migration", requiredAction: "READ" }, - ], - }, - { - id: "migration", - label: nav.migration, - icon: "layers", - tone: "from-category-migration-from to-category-migration-to text-category-migration-text ring-category-migration-ring", - path: "/migration", - requiredPermission: "plugin:migration", - requiredAction: "READ", - requiredFeature: "migration", - subItems: [ - { label: nav.migration_overview || "Overview", path: "/migration", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" }, - { label: nav.migration_mappings || "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" }, - ], - }, - ], - }; - - // ── Section 2: Operations ────────────────────────────────── - const operations: Section = { - id: "operations", - label: nav.section_operations, - categories: [ - { - id: "git", - label: nav.git, - icon: "activity", - tone: "from-category-git-from to-category-git-to text-category-git-text ring-category-git-ring", - path: "/git", - requiredFeature: "git_integration", - subItems: [ - { label: nav.git_repo_status || "Repository Status", path: "/git", requiredFeature: "git_integration" }, - ], - }, - { - id: "translation", - label: nav.translation, - icon: "translate", - tone: "from-category-translation-from to-category-translation-to text-category-translation-text ring-category-translation-ring", - path: "/translate", - requiredPermission: "translate.job", - requiredAction: "VIEW", - requiredFeature: "translate", - subItems: [ - { label: nav.translation_jobs, path: "/translate", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" }, - { label: nav.translation_dictionaries, path: "/translate/dictionaries", requiredPermission: "translate.dictionary", requiredAction: "VIEW", requiredFeature: "translate_dictionaries" }, - { label: nav.translation_history, path: "/translate/history", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" }, - ], - }, - { - id: "validation", - label: nav.validation, - icon: "activity", - tone: "from-category-validation-from to-category-validation-to text-category-validation-text ring-category-validation-ring", - path: "/validation-tasks", - requiredPermission: "validation.task", - requiredAction: "VIEW", - requiredFeature: "llm_dashboard_validation", - subItems: [ - { label: nav.validation_tasks, path: "/validation-tasks", requiredPermission: "validation.task", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" }, - { 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, - icon: "reports", - tone: "from-category-reports-from to-category-reports-to text-category-reports-text ring-category-reports-ring", - path: "/reports", - requiredPermission: "tasks", - requiredAction: "READ", - subItems: [ - { label: nav.all_reports || "All Reports", path: "/reports", requiredPermission: "tasks", requiredAction: "READ" }, - ], - }, - ], - }; - - // ── Section 3: System ──────────────────────────────────── - const system: Section = { - id: "system", - label: nav.section_system, - categories: [ - { - id: "tools", - label: nav.tools, - icon: "list", - tone: "from-category-tools-from to-category-tools-to text-category-tools-text ring-category-tools-ring", - path: "/tools/mapper", - subItems: [ - { label: nav.tools_mapper, path: "/tools/mapper", requiredFeature: "dataset_mapper" }, - { label: nav.tools_debug, path: "/tools/debug", requiredFeature: "debug" }, - { label: nav.tools_storage, path: "/tools/storage", requiredFeature: "storage_manager" }, - { label: nav.tools_backups, path: "/tools/backups", requiredFeature: "backup" }, - ], - }, - { - id: "admin", - label: nav.admin, - icon: "admin", - tone: "from-category-admin-from to-category-admin-to text-category-admin-text ring-category-admin-ring", - path: "/admin/users", - subItems: [ - { label: nav.admin_users, path: "/admin/users", requiredPermission: "admin:users", requiredAction: "READ" }, - { 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" }, - ], - }, - { - id: "maintenance", - label: nav.maintenance || "Maintenance", - icon: "activity", - tone: "from-category-maintenance-from to-category-maintenance-to text-category-maintenance-text ring-category-maintenance-ring", - path: "/maintenance", - requiredPermission: "maintenance", - requiredAction: "READ", - requiredFeature: "maintenance_banner", - subItems: [ - { label: nav.maintenance || "Maintenance", path: "/maintenance", requiredPermission: "maintenance", requiredAction: "READ", requiredFeature: "maintenance_banner" }, - ], - }, - ], - }; - - const allSections = [resources, operations, system]; + const allSections: Section[] = SIDEBAR_SECTIONS.map((section) => ({ + id: section.id, + label: resolveLabel(i18nState, section), + categories: section.categories.map((category) => ({ + id: category.id, + label: resolveLabel(i18nState, category), + icon: category.icon, + tone: category.tone, + path: category.path, + requiredPermission: category.requiredPermission, + requiredAction: category.requiredAction, + requiredFeature: category.requiredFeature, + subItems: category.subItems.map((sub) => ({ + label: resolveLabel(i18nState, sub), + path: sub.path, + requiredPermission: sub.requiredPermission, + requiredAction: sub.requiredAction, + requiredFeature: sub.requiredFeature, + })), + })), + })); // Filter by permissions and features return allSections @@ -279,4 +355,64 @@ export function buildSidebarSections(i18nState: I18nNavState, user: User | null } // #endregion Layout.SidebarNavigation.BuildSidebarSectionsFunction +// #region Layout.SidebarNavigation.GetTogglableFeatureNodesFunction [TYPE Function] +// @BRIEF: Collect every sidebar feature flag, for the settings "Разделы проекта" tab. +// @PRE: SIDEBAR_SECTIONS is the static registry; no user/RBAC filtering is applied (settings are admin-only). +// @POST: Returns one node per distinct requiredFeature in nav order (duplicates — a category and its +// subitems sharing one flag — collapse to the first occurrence), with section/category context. +// @RATIONALE: The settings tab derives its toggle list from this registry instead of a hardcoded +// copy, so adding a gated route to the sidebar makes it appear in settings automatically. +export interface TogglableFeatureNode { + featureId: NavFeatureId; + labelKey: string; + labelFallback?: string; + sectionId: string; + sectionLabelKey: string; + categoryId: string; + categoryLabelKey: string; + categoryLabelFallback?: string; +} + +export function getTogglableFeatureNodes(): TogglableFeatureNode[] { + const nodes: TogglableFeatureNode[] = []; + const seenFeatureIds = new Set(); + const pushNode = (node: TogglableFeatureNode): void => { + if (seenFeatureIds.has(node.featureId)) return; + seenFeatureIds.add(node.featureId); + nodes.push(node); + }; + for (const section of SIDEBAR_SECTIONS) { + for (const category of section.categories) { + if (category.requiredFeature) { + pushNode({ + featureId: category.requiredFeature, + labelKey: category.labelKey, + labelFallback: category.labelFallback, + sectionId: section.id, + sectionLabelKey: section.labelKey, + categoryId: category.id, + categoryLabelKey: category.labelKey, + categoryLabelFallback: category.labelFallback, + }); + } + for (const sub of category.subItems) { + if (sub.requiredFeature) { + pushNode({ + featureId: sub.requiredFeature, + labelKey: sub.labelKey, + labelFallback: sub.labelFallback, + sectionId: section.id, + sectionLabelKey: section.labelKey, + categoryId: category.id, + categoryLabelKey: category.labelKey, + categoryLabelFallback: category.labelFallback, + }); + } + } + } + } + return nodes; +} +// #endregion Layout.SidebarNavigation.GetTogglableFeatureNodesFunction + // #endregion Layout.SidebarNavigation.SidebarNavigationModule diff --git a/frontend/src/lib/i18n/locales/en/settings.json b/frontend/src/lib/i18n/locales/en/settings.json index 4f037006f..2e7773603 100644 --- a/frontend/src/lib/i18n/locales/en/settings.json +++ b/frontend/src/lib/i18n/locales/en/settings.json @@ -112,6 +112,7 @@ "env_update": "Update Environment", "features": "Features", "features_description": "Enable or disable top-level application features.", + "features_extra": "Additional features", "feature_health_monitor": "Health Monitor", "feature_health_monitor_hint": "Dashboard health monitoring and validation report aggregation.", "save_features": "Save feature settings", diff --git a/frontend/src/lib/i18n/locales/ru/settings.json b/frontend/src/lib/i18n/locales/ru/settings.json index bc3e9fe30..d230d7f87 100644 --- a/frontend/src/lib/i18n/locales/ru/settings.json +++ b/frontend/src/lib/i18n/locales/ru/settings.json @@ -112,6 +112,7 @@ "env_update": "Обновить окружение", "features": "Разделы проекта", "features_description": "Включение и отключение разделов приложения.", + "features_extra": "Дополнительные функции", "feature_health_monitor": "Health Monitor", "feature_health_monitor_hint": "Мониторинг здоровья дашбордов и агрегация отчётов валидации.", "save_features": "Сохранить настройки разделов", diff --git a/frontend/src/lib/stores/__tests__/test_features.ts b/frontend/src/lib/stores/__tests__/test_features.ts new file mode 100644 index 000000000..b0f5e0b28 --- /dev/null +++ b/frontend/src/lib/stores/__tests__/test_features.ts @@ -0,0 +1,96 @@ +// #region Test.Features [C:2] [TYPE Module] [SEMANTICS test, features, store, flags] +// @BRIEF Unit tests for the reactive feature-flag store — defaults, setFeatures, load dedup, error recovery. +// @RELATION DEPENDS_ON -> [Stores.Features.FeaturesStore] +// @TEST_EDGE: unknown_flag -> isFeatureEnabled returns true for ids absent from the flags dict (default-on posture) +// @TEST_EDGE: external_fail -> fetchApi rejection degrades to empty flags without throwing +// @TEST_SCENARIO: concurrent_load -> two loadFeatures() calls share one in-flight request + +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +vi.mock('$lib/api.js', () => ({ + fetchApi: vi.fn(), +})); + +vi.mock('$lib/cot-logger', () => ({ + log: vi.fn(), +})); + +import { fetchApi } from '$lib/api.js'; + +describe('features store', () => { + beforeEach(() => { + vi.resetModules(); + vi.mocked(fetchApi).mockReset(); + }); + + it('starts unloaded with all flags treated as enabled', async () => { + const store = await import('../features.svelte.js'); + + expect(store.isLoaded()).toBe(false); + expect(store.getFeatures()).toEqual({}); + expect(store.isFeatureEnabled('health_monitor')).toBe(true); + expect(store.isFeatureEnabled('anything_unknown')).toBe(true); + }); + + it('setFeatures stores a copy and marks the store loaded', async () => { + const store = await import('../features.svelte.js'); + + const next = { health_monitor: true, migration: false }; + store.setFeatures(next); + + // Mutating the source object must not leak into the store state. + next.migration = true; + + expect(store.isLoaded()).toBe(true); + expect(store.getFeatures()).toEqual({ health_monitor: true, migration: false }); + expect(store.isFeatureEnabled('migration')).toBe(false); + }); + + it('setFeatures tolerates null/undefined payloads', async () => { + const store = await import('../features.svelte.js'); + + store.setFeatures(null); + expect(store.isLoaded()).toBe(true); + expect(store.getFeatures()).toEqual({}); + }); + + it('loadFeatures fetches /settings/features and stores the result', async () => { + vi.mocked(fetchApi).mockResolvedValueOnce({ health_monitor: false, migration: true }); + const store = await import('../features.svelte.js'); + + const flags = await store.loadFeatures(); + + expect(fetchApi).toHaveBeenCalledWith('/settings/features'); + expect(store.isLoaded()).toBe(true); + expect(flags).toEqual({ health_monitor: false, migration: true }); + expect(store.isFeatureEnabled('health_monitor')).toBe(false); + }); + + it('concurrent loadFeatures calls share one request', async () => { + let resolveFetch: (value: unknown) => void = () => {}; + vi.mocked(fetchApi).mockImplementationOnce( + () => new Promise((resolve) => { resolveFetch = resolve; }), + ); + const store = await import('../features.svelte.js'); + + const first = store.loadFeatures(); + const second = store.loadFeatures(); + + resolveFetch({ migration: false }); + await Promise.all([first, second]); + + expect(fetchApi).toHaveBeenCalledTimes(1); + }); + + it('loadFeatures degrades to empty flags on fetch failure', async () => { + vi.mocked(fetchApi).mockRejectedValueOnce(new Error('network down')); + const store = await import('../features.svelte.js'); + + const flags = await store.loadFeatures(); + + expect(flags).toEqual({}); + expect(store.isLoaded()).toBe(true); + expect(store.isFeatureEnabled('migration')).toBe(true); + }); +}); +// #endregion Test.Features diff --git a/frontend/src/lib/stores/features.svelte.ts b/frontend/src/lib/stores/features.svelte.ts new file mode 100644 index 000000000..e984f7960 --- /dev/null +++ b/frontend/src/lib/stores/features.svelte.ts @@ -0,0 +1,59 @@ +// #region Stores.Features.FeaturesStore [C:2] [TYPE Store] [SEMANTICS features, flags, store, settings] +// @ingroup Stores +// @BRIEF Reactive feature-flag store shared by the sidebar and the settings "Разделы проекта" tab — +// saving toggles in settings rebuilds the left panel without a page reload. +// @LAYER UI +// @RELATION DEPENDS_ON -> [Api.ApiModule.FetchApi] +// @RELATION BINDS_TO -> [Layout.Sidebar] +// @RELATION BINDS_TO -> [Settings.Page.SettingsPage] +// @UX_STATE Loading -> flags empty, nav renders with defaults (all enabled). +// @UX_STATE Ready -> flags reflect the persisted FeaturesConfig. +// @PRE GET /settings/features is reachable (unauthenticated endpoint). +// @POST setFeatures(next) re-renders every consumer reading getFeatures()/isFeatureEnabled(). +// @RATIONALE Module-level $state store following the health.svelte.ts pattern: the sidebar and the +// settings features tab must read the same flags, so a save can push new flags into the +// nav without remounting. Concurrent loadFeatures() calls share one request. + +import { fetchApi } from "$lib/api.js"; +import { log } from "$lib/cot-logger"; + +let _flags = $state>({}); +let _loaded = $state(false); +let _inflight: Promise> | null = null; + +export function getFeatures(): Record { + return _flags; +} + +export function isLoaded(): boolean { + return _loaded; +} + +/** Unknown/missing ids are treated as enabled (matches the backend default-true posture). */ +export function isFeatureEnabled(id: string): boolean { + return _flags[id] !== false; +} + +export function setFeatures(next: Record | undefined | null): void { + _flags = { ...(next || {}) }; + _loaded = true; +} + +export async function loadFeatures(): Promise> { + if (_inflight) return _inflight; + _inflight = fetchApi("/settings/features") + .then((res) => { + setFeatures(res as Record); + return _flags; + }) + .catch((err) => { + log("FeaturesStore", "EXPLORE", "Failed to load feature flags", {}, String(err)); + setFeatures({}); + return _flags; + }) + .finally(() => { + _inflight = null; + }); + return _inflight; +} +// #endregion Stores.Features.FeaturesStore diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelte index c606aa762..879219a4f 100644 --- a/frontend/src/routes/settings/+page.svelte +++ b/frontend/src/routes/settings/+page.svelte @@ -28,6 +28,7 @@ import { Button, Skeleton, Tabs } from "$lib/ui"; import { log } from "$lib/cot-logger"; + import { setFeatures } from "$lib/stores/features.svelte.js"; import { normalizeTab, readTabFromUrl, @@ -80,6 +81,8 @@ response.mcp_oauth_refresh_default_days ??= 30; response.mcp_oauth_refresh_max_days ??= 90; settings = response; + // Push the fresh flags into the reactive store so the sidebar stays in sync. + setFeatures(response.features); } catch (err) { error = err.message || $t.settings?.load_failed; log("SettingsPage", "EXPLORE", "Failed to load settings", {}, String(err)); @@ -100,6 +103,8 @@ try { settings.llm = normalizeLlmSettings(settings.llm); await api.updateConsolidatedSettings(settings); + // Update the shared features store so the sidebar rebuilds without a page reload. + setFeatures(settings.features); notifications.success($t.settings?.save_success); } catch (err) { log("SettingsPage", "EXPLORE", "Failed to save settings", {}, String(err)); diff --git a/frontend/src/routes/settings/FeaturesSettings.svelte b/frontend/src/routes/settings/FeaturesSettings.svelte index a9cad7941..4edc569da 100644 --- a/frontend/src/routes/settings/FeaturesSettings.svelte +++ b/frontend/src/routes/settings/FeaturesSettings.svelte @@ -1,62 +1,93 @@ - + - - + + +
@@ -103,45 +124,65 @@ {$t.settings?.features_description || "Enable or disable application features. Disabled features are hidden from the UI and blocked at the API level."}

- {#each Object.entries(groupedFeatures) as [category, features]} + {#snippet toggleRow(feature: ToggleEntry, bordered: boolean)} +
+
+ + + {#if featureHelp(feature.id)} + + {/if} + + {#if featureHint(feature.id)} +

+ {featureHint(feature.id)} +

+ {/if} +
+ +
+ {/snippet} + + {#each navGroups as section (section.id)}

- {CATEGORIES[category] || category} + {navLabel(section.labelKey)}

-
- {#each features as feature, i} -
0} class:border-border={i > 0}> -
- - - {#if featureHelp(feature.id)} - - {/if} - - {#if featureHint(feature.id)} -

- {featureHint(feature.id)} -

- {/if} -
- -
- {/each} -
+ {#each section.categories as category (category.id)} +

+ {navLabel(category.labelKey, category.labelFallback)} +

+
+ {#each category.features as feature, i (feature.id)} + {@render toggleRow(feature, i > 0)} + {/each} +
+ {/each}
{/each} +
+

+ {$t.settings?.features_extra || "Additional features"} +

+
+ {#each EXTRA_FEATURES as feature, i (feature.id)} + {@render toggleRow(feature, i > 0)} + {/each} +
+
+